qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
2,975,824 | In googling I can't seem to find an example of intercepting event on a proxied type and it doesn't seem to be working for me. Is there a way I can do this (ie. use an IInterceptor when an event is invoked)? | 2010/06/04 | [
"https://Stackoverflow.com/questions/2975824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/326518/"
] | I've used this in a Universal app to determine if the code is running on an iPad
```
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
// Do iPad only stuff here
}
``` | Look at `UIDevice` and it's properties. There is a `systemVersion` string that will work for what you want. |
181,774 | I need help with connect a macbook to the hitachi cp-x400 projector. there are only a few ports on the macbook; 2 usb, one firewire/printer type usb (not sure if it is firewire or what it is exactly, but it definitely is the printer sized usb), ethernet, and thats about it. Please help. PC usually work when i plug it in. I have it a regular usb plugged into the macbook connecting to the printer type usb port on the projector and its not working. | 2010/08/28 | [
"https://superuser.com/questions/181774",
"https://superuser.com",
"https://superuser.com/users/47844/"
] | The script that you referenced isn't a greasemonkey script per se, it's a script that is part of greasemonkey. It's the thingy that runs in the background until you right click on the greasemonkey monkey in the status bar and open up the greasemonkey preferences or script manager. | Try updating/reinstalling Greasemonkey and Firefox. Preferably alternating between both a few times. |
181,774 | I need help with connect a macbook to the hitachi cp-x400 projector. there are only a few ports on the macbook; 2 usb, one firewire/printer type usb (not sure if it is firewire or what it is exactly, but it definitely is the printer sized usb), ethernet, and thats about it. Please help. PC usually work when i plug it in. I have it a regular usb plugged into the macbook connecting to the printer type usb port on the projector and its not working. | 2010/08/28 | [
"https://superuser.com/questions/181774",
"https://superuser.com",
"https://superuser.com/users/47844/"
] | The script that you referenced isn't a greasemonkey script per se, it's a script that is part of greasemonkey. It's the thingy that runs in the background until you right click on the greasemonkey monkey in the status bar and open up the greasemonkey preferences or script manager. | Okay, you can easily uninstall Greasemonkey and install everything again. If Firefox hangs at start, follow these steps:
Go to Start -> All Programs -> Mozilla Firefox -> Mozilla Firefox (Safe Mode)
But don't click that. Hold down Shift first. When you hold the key and click it, a dialog will appear.
Uncheck the stuff you want, but remember, you want to run Foxy with all the add-ons disabled.
When you are running Firefox with disabled add-ons, uninstall Greasemonkey normally, and start the normal Firefox. |
181,774 | I need help with connect a macbook to the hitachi cp-x400 projector. there are only a few ports on the macbook; 2 usb, one firewire/printer type usb (not sure if it is firewire or what it is exactly, but it definitely is the printer sized usb), ethernet, and thats about it. Please help. PC usually work when i plug it in. I have it a regular usb plugged into the macbook connecting to the printer type usb port on the projector and its not working. | 2010/08/28 | [
"https://superuser.com/questions/181774",
"https://superuser.com",
"https://superuser.com/users/47844/"
] | The script that you referenced isn't a greasemonkey script per se, it's a script that is part of greasemonkey. It's the thingy that runs in the background until you right click on the greasemonkey monkey in the status bar and open up the greasemonkey preferences or script manager. | I did nothing. It just suddenly cleared up. I have no scripts running so I have no idea why it should have given me that message.
EDIT: I up-voted a couple of answers here as they make sense, but my basic question is unanswered. Anyone else? |
11,107 | What is the difference in meaning between these two words and how does their usage differ? | 2015/11/02 | [
"https://russian.stackexchange.com/questions/11107",
"https://russian.stackexchange.com",
"https://russian.stackexchange.com/users/5201/"
] | **Чересчур** is one of those words that don't *sound* bookish, and yet you're radically less likely to hear it in everyday speech compared to **слишком**. **Чересчур** just isn't the word you'd immediately think of when seeking to express the idea of excess. But when you do hear it, it sounds perfectly natural and plain, "oh yeah, that's a word too."
Also I feel subjectively that **слишком** is more, as it were, focused. All other things being equal (i.e. discounting the abovementioned general likelihood to think of **слишком** as a word choice before you think of **чересчур**), you're more likely to pick **слишком** over **чересчур** if you think you can more or less point to the exact measure, or the exact cause, of the perceived excess. **Чересчур** is more of a "dunno, there's just too much of this here thing."
That said, **это уже слишком** "now that's enough!" makes you sound annoyed or angry while **это уже чересчур** is a more laid-back "now that would be going too far". | Well, the difference is in negative form:
For example, *Он не слишком умён* means *He's silly*. Yet negative *не чересчур* is almost never used except questions: *А не чересчур ли он умён?* etc.
Also *с лишком* literally means *with excess*, so if written as a whole *слишком* is an adverb, but separate *с лишком* is a noun.
**UPD.**
The etimology of "*чересчур*" is much more vague. First of all, of course, *чересчур* = *через чур*, but what is *чур*, anyway?
Certainly, we have the word *чур* as a part of "a guard spell" against the evil: *чур меня!* Also consider the verb *чураться* (to keep away, to shun). Still it helps a little, because *the meaning* of it is unknown. One option could be, for example, *Чур / Щур* (cf. *Пращур*) = *Ancestor* (so *Чур меня!* means smth. like *Ancestors [defend] me!*), but Vasmer dictionary gives this as "unlikely".
Another point is that *чур меня!* and *чересчур* may be not related in any way. Vasmer says that the word *Чур*, meaning a kind of *Limit* or *Bar*, is to be *reconstructed from* the word *Чересчур*. Personally I know only one appearance of the word *чур* in this sense: *Чуры не знать* means *To have no limits* (especially when someone eats too much). But it's a dialectal expression, and I'm not sure if *чересчур* is really related to *чуры не знать*. |
11,107 | What is the difference in meaning between these two words and how does their usage differ? | 2015/11/02 | [
"https://russian.stackexchange.com/questions/11107",
"https://russian.stackexchange.com",
"https://russian.stackexchange.com/users/5201/"
] | Well, the difference is in negative form:
For example, *Он не слишком умён* means *He's silly*. Yet negative *не чересчур* is almost never used except questions: *А не чересчур ли он умён?* etc.
Also *с лишком* literally means *with excess*, so if written as a whole *слишком* is an adverb, but separate *с лишком* is a noun.
**UPD.**
The etimology of "*чересчур*" is much more vague. First of all, of course, *чересчур* = *через чур*, but what is *чур*, anyway?
Certainly, we have the word *чур* as a part of "a guard spell" against the evil: *чур меня!* Also consider the verb *чураться* (to keep away, to shun). Still it helps a little, because *the meaning* of it is unknown. One option could be, for example, *Чур / Щур* (cf. *Пращур*) = *Ancestor* (so *Чур меня!* means smth. like *Ancestors [defend] me!*), but Vasmer dictionary gives this as "unlikely".
Another point is that *чур меня!* and *чересчур* may be not related in any way. Vasmer says that the word *Чур*, meaning a kind of *Limit* or *Bar*, is to be *reconstructed from* the word *Чересчур*. Personally I know only one appearance of the word *чур* in this sense: *Чуры не знать* means *To have no limits* (especially when someone eats too much). But it's a dialectal expression, and I'm not sure if *чересчур* is really related to *чуры не знать*. | Слишком is too serious while чересчур is only slighly disapproving as if you were approving it in essense or in the deep of your mind or it is generally a good property, just here it is unusually excessive. Like in the case of playing children:
>
> Вы слишком шумите! - You are producing too much noise, reduce it!
>
>
> Вы чересчур шумите! - Your noise is excessive. Even though I like it
> and think you essentially have the right to do it, it can be annoying
> for other people around.
>
>
> У вас слишком большой рост. - Your height is too large. You do not fit
> in the requirements. It is unlikely you will pass.
>
>
> У вас чересчур большой рост. - Large height is good in general, and I
> like(we look for) specifically tall people but I am a little concerned about yours
> because it may be excessive. Nevertheless, we can give you a try.
>
>
> |
11,107 | What is the difference in meaning between these two words and how does their usage differ? | 2015/11/02 | [
"https://russian.stackexchange.com/questions/11107",
"https://russian.stackexchange.com",
"https://russian.stackexchange.com/users/5201/"
] | **Чересчур** is one of those words that don't *sound* bookish, and yet you're radically less likely to hear it in everyday speech compared to **слишком**. **Чересчур** just isn't the word you'd immediately think of when seeking to express the idea of excess. But when you do hear it, it sounds perfectly natural and plain, "oh yeah, that's a word too."
Also I feel subjectively that **слишком** is more, as it were, focused. All other things being equal (i.e. discounting the abovementioned general likelihood to think of **слишком** as a word choice before you think of **чересчур**), you're more likely to pick **слишком** over **чересчур** if you think you can more or less point to the exact measure, or the exact cause, of the perceived excess. **Чересчур** is more of a "dunno, there's just too much of this here thing."
That said, **это уже слишком** "now that's enough!" makes you sound annoyed or angry while **это уже чересчур** is a more laid-back "now that would be going too far". | If I tried to compare translations, I'd say that '*слишком*' is '*too*' and '*чересчур*' is like '*too much*' or '*more than enough*'. For instance: '*Он слишком умный*' = '*He is too smart*' and '*Он чересчур умный*' is 'He is smart more than enough'.
Btw, with '*smart*' expressions above sound a bit depreciatingly. |
11,107 | What is the difference in meaning between these two words and how does their usage differ? | 2015/11/02 | [
"https://russian.stackexchange.com/questions/11107",
"https://russian.stackexchange.com",
"https://russian.stackexchange.com/users/5201/"
] | **Чересчур** is one of those words that don't *sound* bookish, and yet you're radically less likely to hear it in everyday speech compared to **слишком**. **Чересчур** just isn't the word you'd immediately think of when seeking to express the idea of excess. But when you do hear it, it sounds perfectly natural and plain, "oh yeah, that's a word too."
Also I feel subjectively that **слишком** is more, as it were, focused. All other things being equal (i.e. discounting the abovementioned general likelihood to think of **слишком** as a word choice before you think of **чересчур**), you're more likely to pick **слишком** over **чересчур** if you think you can more or less point to the exact measure, or the exact cause, of the perceived excess. **Чересчур** is more of a "dunno, there's just too much of this here thing."
That said, **это уже слишком** "now that's enough!" makes you sound annoyed or angry while **это уже чересчур** is a more laid-back "now that would be going too far". | Слишком is too serious while чересчур is only slighly disapproving as if you were approving it in essense or in the deep of your mind or it is generally a good property, just here it is unusually excessive. Like in the case of playing children:
>
> Вы слишком шумите! - You are producing too much noise, reduce it!
>
>
> Вы чересчур шумите! - Your noise is excessive. Even though I like it
> and think you essentially have the right to do it, it can be annoying
> for other people around.
>
>
> У вас слишком большой рост. - Your height is too large. You do not fit
> in the requirements. It is unlikely you will pass.
>
>
> У вас чересчур большой рост. - Large height is good in general, and I
> like(we look for) specifically tall people but I am a little concerned about yours
> because it may be excessive. Nevertheless, we can give you a try.
>
>
> |
11,107 | What is the difference in meaning between these two words and how does their usage differ? | 2015/11/02 | [
"https://russian.stackexchange.com/questions/11107",
"https://russian.stackexchange.com",
"https://russian.stackexchange.com/users/5201/"
] | If I tried to compare translations, I'd say that '*слишком*' is '*too*' and '*чересчур*' is like '*too much*' or '*more than enough*'. For instance: '*Он слишком умный*' = '*He is too smart*' and '*Он чересчур умный*' is 'He is smart more than enough'.
Btw, with '*smart*' expressions above sound a bit depreciatingly. | Слишком is too serious while чересчур is only slighly disapproving as if you were approving it in essense or in the deep of your mind or it is generally a good property, just here it is unusually excessive. Like in the case of playing children:
>
> Вы слишком шумите! - You are producing too much noise, reduce it!
>
>
> Вы чересчур шумите! - Your noise is excessive. Even though I like it
> and think you essentially have the right to do it, it can be annoying
> for other people around.
>
>
> У вас слишком большой рост. - Your height is too large. You do not fit
> in the requirements. It is unlikely you will pass.
>
>
> У вас чересчур большой рост. - Large height is good in general, and I
> like(we look for) specifically tall people but I am a little concerned about yours
> because it may be excessive. Nevertheless, we can give you a try.
>
>
> |
4,478,028 | i'm working in a project to recognize a bit code from an image like this, where black rectangle represents 0 bit, and white (white space, not visible) 1 bit.
[](https://i.stack.imgur.com/HHJqr.png)
Somebody have any idea to process the image in order to extract this informations? My project is written in java, but any solution is accepted.
---
thanks all for support.
I'm not an expert in image processing, I try to apply Edge Detection using Canny Edge Detector Implementation, free java implementation find [here](http://www.tomgibara.com/computer-vision/canny-edge-detector). I used this complete image [http://img257.imageshack.us/img257/5323/colorimg.png], reduce it (scale factor = 0.4) to have fast processing and this is the result [http://img222.imageshack.us/img222/8255/colorimgout.png]. Now, how i can decode white rectangle with 0 bit value, and no rectangle with 1?
The image have 10 line X 16 columns. I don't use python, but i can try to convert it to Java.
Many thanks to support. | 2010/12/18 | [
"https://Stackoverflow.com/questions/4478028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/546981/"
] | This is recognising good old **OMR (optical mark recognition)**.
The solution varies depending on the quality and consistency of the data you get, so noise is important.
Using an image processing library will clearly help.
**Simple case: No skew in the image and no stretch or shrinkage**
Create a horizontal and vertical profile of the image. i.e. sum up values in all columns and all rows and store in arrays. for an image of MxN (width x height) you will have M cells in horizontal profile and N cells in vertical profile.
Use a thresholding to find out which cells are white (empty) and which are black. This assumes you will get at least a couple of entries in each row or column. So black cells will define a location of interest (where you will expect the marks).
Based on this, you can define in lozenges in the form and you get coordinates of lozenges (rectangles where you have marks) and then you just add up pixel values in each lozenge and based on the number, you can define if it has mark or not.
**Case 2: Skew (slant in the image)**
Use fourier (FFT) to find the slant value and then transform it.
**Case 3: Stretch or shrink**
Pretty much the same as 1 but noise is higher and reliability less. | I am not familiar with Java, but in Python, you can use the imaging library to open the image. Then load the height and the widths, and segment the image into a grid accordingly, by Height/Rows and Width/Cols. Then, just look for black pixels in those regions, or whatever color PIL registers that black to be. This obviously relies on the grid like nature of the data.
Edit:
Doing Edge Detection may also be Fruitful. First apply an edge detection method like something from wikipedia. I have used the one found at archive.alwaysmovefast.com/basic-edge-detection-in-python.html. Then convert any grayscale value less than 180 (if you want the boxes darker just increase this value) into black and otherwise make it completely white. Then create bounding boxes, lines where the pixels are all white. If data isn't terribly skewed, then this should work pretty well, otherwise you may need to do more work. See here for the results: <http://imm.io/2BLd>
Edit2:
Denis, how large is your dataset and how large are the images? If you have thousands of these images, then it is not feasible to manually remove the borders (the red background and yellow bars). I think this is important to know before proceeding. Also, I think the prewitt edge detection may prove more useful in this case, since there appears to be less noise:

The previous method of segmenting may be applied, if you do preprocess to bin in the following manner, in which case you need only count the number of black or white pixels and threshold after some training samples.
 |
4,478,028 | i'm working in a project to recognize a bit code from an image like this, where black rectangle represents 0 bit, and white (white space, not visible) 1 bit.
[](https://i.stack.imgur.com/HHJqr.png)
Somebody have any idea to process the image in order to extract this informations? My project is written in java, but any solution is accepted.
---
thanks all for support.
I'm not an expert in image processing, I try to apply Edge Detection using Canny Edge Detector Implementation, free java implementation find [here](http://www.tomgibara.com/computer-vision/canny-edge-detector). I used this complete image [http://img257.imageshack.us/img257/5323/colorimg.png], reduce it (scale factor = 0.4) to have fast processing and this is the result [http://img222.imageshack.us/img222/8255/colorimgout.png]. Now, how i can decode white rectangle with 0 bit value, and no rectangle with 1?
The image have 10 line X 16 columns. I don't use python, but i can try to convert it to Java.
Many thanks to support. | 2010/12/18 | [
"https://Stackoverflow.com/questions/4478028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/546981/"
] | This is recognising good old **OMR (optical mark recognition)**.
The solution varies depending on the quality and consistency of the data you get, so noise is important.
Using an image processing library will clearly help.
**Simple case: No skew in the image and no stretch or shrinkage**
Create a horizontal and vertical profile of the image. i.e. sum up values in all columns and all rows and store in arrays. for an image of MxN (width x height) you will have M cells in horizontal profile and N cells in vertical profile.
Use a thresholding to find out which cells are white (empty) and which are black. This assumes you will get at least a couple of entries in each row or column. So black cells will define a location of interest (where you will expect the marks).
Based on this, you can define in lozenges in the form and you get coordinates of lozenges (rectangles where you have marks) and then you just add up pixel values in each lozenge and based on the number, you can define if it has mark or not.
**Case 2: Skew (slant in the image)**
Use fourier (FFT) to find the slant value and then transform it.
**Case 3: Stretch or shrink**
Pretty much the same as 1 but noise is higher and reliability less. | Aliostad has made some good comments.
This is OMR and you will find it much easier to get good consistent results with a good image processing library. www.leptonica.com is a free open source 'C' library that would be a very good place to start. It could process the skew and thresholding tasks for you. Thresholding to B/W would be a good start.
Another option would be IEvolution - <http://www.hi-components.com/nievolution.asp> for .NET.
To be successful you will need some type of reference / registration marks to allow for skew and stretch especially if you are using document scanning or capturing from a camera image. |
851,336 | i m having trouble in uploading multiple files with same input name:
```
<input type=file name="file">
<input type=file name="file">
<input type=file name="file">
```
at django side
```
print request.FILES :
<MultiValueDict: {u'file': [
<TemporaryUploadedFile: captcha_bg.jpg (image/jpeg)>,
<TemporaryUploadedFile: 001_using_git_with_django.mov (video/quicktime)>,
<TemporaryUploadedFile: ejabberd-ust.odt (application/vnd.oasis.opendocument.text)>
]}>
```
so all three files are under single request.FILES['file'] object . how do i handle for each files uploaded from here? | 2009/05/12 | [
"https://Stackoverflow.com/questions/851336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105169/"
] | ```
for f in request.FILES.getlist('file'):
# do something with the file f...
```
EDIT: I know this was an old answer, but I came across it just now and have edited the answer to actually be correct. It was previously suggesting that you could iterate directly over `request.FILES['file']`. To access all items in a MultiValueDict, you use `.getlist('file')`. Using just `['file']` will only return the last data value it finds for that key. | I dont think all three files will be under the single `request.FILES['file']` object. `request.FILES['file']` is likely to have either the 1st file or the last file from that list.
You need to uniquely name the input elements like so:
```
<input type=file name="file1">
<input type=file name="file2">
<input type=file name="file3">
```
..for example.
**EDIT: [Justin's answer](https://stackoverflow.com/questions/851336/multiple-files-upload-using-same-input-name-in-django/851372#856126) is better!** |
851,336 | i m having trouble in uploading multiple files with same input name:
```
<input type=file name="file">
<input type=file name="file">
<input type=file name="file">
```
at django side
```
print request.FILES :
<MultiValueDict: {u'file': [
<TemporaryUploadedFile: captcha_bg.jpg (image/jpeg)>,
<TemporaryUploadedFile: 001_using_git_with_django.mov (video/quicktime)>,
<TemporaryUploadedFile: ejabberd-ust.odt (application/vnd.oasis.opendocument.text)>
]}>
```
so all three files are under single request.FILES['file'] object . how do i handle for each files uploaded from here? | 2009/05/12 | [
"https://Stackoverflow.com/questions/851336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105169/"
] | Given your url points to *envia* you could manage multiple files like this:
```
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from django.http import HttpResponseRedirect
def envia(request):
for f in request.FILES.getlist('file'):
handle_uploaded_file(f)
return HttpResponseRedirect('/bulk/')
def handle_uploaded_file(f):
destination = open('/tmp/upload/%s'%f.name, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
``` | I dont think all three files will be under the single `request.FILES['file']` object. `request.FILES['file']` is likely to have either the 1st file or the last file from that list.
You need to uniquely name the input elements like so:
```
<input type=file name="file1">
<input type=file name="file2">
<input type=file name="file3">
```
..for example.
**EDIT: [Justin's answer](https://stackoverflow.com/questions/851336/multiple-files-upload-using-same-input-name-in-django/851372#856126) is better!** |
851,336 | i m having trouble in uploading multiple files with same input name:
```
<input type=file name="file">
<input type=file name="file">
<input type=file name="file">
```
at django side
```
print request.FILES :
<MultiValueDict: {u'file': [
<TemporaryUploadedFile: captcha_bg.jpg (image/jpeg)>,
<TemporaryUploadedFile: 001_using_git_with_django.mov (video/quicktime)>,
<TemporaryUploadedFile: ejabberd-ust.odt (application/vnd.oasis.opendocument.text)>
]}>
```
so all three files are under single request.FILES['file'] object . how do i handle for each files uploaded from here? | 2009/05/12 | [
"https://Stackoverflow.com/questions/851336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105169/"
] | I dont think all three files will be under the single `request.FILES['file']` object. `request.FILES['file']` is likely to have either the 1st file or the last file from that list.
You need to uniquely name the input elements like so:
```
<input type=file name="file1">
<input type=file name="file2">
<input type=file name="file3">
```
..for example.
**EDIT: [Justin's answer](https://stackoverflow.com/questions/851336/multiple-files-upload-using-same-input-name-in-django/851372#856126) is better!** | This code is the example
```
for f in request.FILES.getlist('myfile[]'):
if request.method == 'POST' and f:
myfile = f
filesystem = FileSystemStorage()
filename = filesystem.save(myfile.name, myfile)
``` |
851,336 | i m having trouble in uploading multiple files with same input name:
```
<input type=file name="file">
<input type=file name="file">
<input type=file name="file">
```
at django side
```
print request.FILES :
<MultiValueDict: {u'file': [
<TemporaryUploadedFile: captcha_bg.jpg (image/jpeg)>,
<TemporaryUploadedFile: 001_using_git_with_django.mov (video/quicktime)>,
<TemporaryUploadedFile: ejabberd-ust.odt (application/vnd.oasis.opendocument.text)>
]}>
```
so all three files are under single request.FILES['file'] object . how do i handle for each files uploaded from here? | 2009/05/12 | [
"https://Stackoverflow.com/questions/851336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105169/"
] | ```
for f in request.FILES.getlist('file'):
# do something with the file f...
```
EDIT: I know this was an old answer, but I came across it just now and have edited the answer to actually be correct. It was previously suggesting that you could iterate directly over `request.FILES['file']`. To access all items in a MultiValueDict, you use `.getlist('file')`. Using just `['file']` will only return the last data value it finds for that key. | Given your url points to *envia* you could manage multiple files like this:
```
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from django.http import HttpResponseRedirect
def envia(request):
for f in request.FILES.getlist('file'):
handle_uploaded_file(f)
return HttpResponseRedirect('/bulk/')
def handle_uploaded_file(f):
destination = open('/tmp/upload/%s'%f.name, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
``` |
851,336 | i m having trouble in uploading multiple files with same input name:
```
<input type=file name="file">
<input type=file name="file">
<input type=file name="file">
```
at django side
```
print request.FILES :
<MultiValueDict: {u'file': [
<TemporaryUploadedFile: captcha_bg.jpg (image/jpeg)>,
<TemporaryUploadedFile: 001_using_git_with_django.mov (video/quicktime)>,
<TemporaryUploadedFile: ejabberd-ust.odt (application/vnd.oasis.opendocument.text)>
]}>
```
so all three files are under single request.FILES['file'] object . how do i handle for each files uploaded from here? | 2009/05/12 | [
"https://Stackoverflow.com/questions/851336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105169/"
] | ```
for f in request.FILES.getlist('file'):
# do something with the file f...
```
EDIT: I know this was an old answer, but I came across it just now and have edited the answer to actually be correct. It was previously suggesting that you could iterate directly over `request.FILES['file']`. To access all items in a MultiValueDict, you use `.getlist('file')`. Using just `['file']` will only return the last data value it finds for that key. | This code is the example
```
for f in request.FILES.getlist('myfile[]'):
if request.method == 'POST' and f:
myfile = f
filesystem = FileSystemStorage()
filename = filesystem.save(myfile.name, myfile)
``` |
851,336 | i m having trouble in uploading multiple files with same input name:
```
<input type=file name="file">
<input type=file name="file">
<input type=file name="file">
```
at django side
```
print request.FILES :
<MultiValueDict: {u'file': [
<TemporaryUploadedFile: captcha_bg.jpg (image/jpeg)>,
<TemporaryUploadedFile: 001_using_git_with_django.mov (video/quicktime)>,
<TemporaryUploadedFile: ejabberd-ust.odt (application/vnd.oasis.opendocument.text)>
]}>
```
so all three files are under single request.FILES['file'] object . how do i handle for each files uploaded from here? | 2009/05/12 | [
"https://Stackoverflow.com/questions/851336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105169/"
] | Given your url points to *envia* you could manage multiple files like this:
```
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from django.http import HttpResponseRedirect
def envia(request):
for f in request.FILES.getlist('file'):
handle_uploaded_file(f)
return HttpResponseRedirect('/bulk/')
def handle_uploaded_file(f):
destination = open('/tmp/upload/%s'%f.name, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
``` | This code is the example
```
for f in request.FILES.getlist('myfile[]'):
if request.method == 'POST' and f:
myfile = f
filesystem = FileSystemStorage()
filename = filesystem.save(myfile.name, myfile)
``` |
6,335,408 | I have a perhaps silly question... I am trying to determine what is the best approach for typing a property whose value will be either "New" or "Used". Do I use an `enum` or should I just go with a `boolean` (e.g. IsNew)? If I go with `enum`, what should I call this type and property name? (public NewOrUsed NewOrUsed {get; set;} <-- confusing)
Obviously, with `enum` I can have state that declares neither value (NONE, NEW, USED) and `enum` is more future-proof (although one can claim there is no chance other values will exist). Again, what is the appropriate name for such a type and property?
With `boolean` - it's pretty straight forward (either using IsNew or IsUsed)
I know it's silly, but I am curious what others think
Regards
Z..
Update
------
If you prefer `enum`, please comment on what should be appropriate name for type and property (e.g `public NewUsedType NewOrUsed {get; set;}`) | 2011/06/13 | [
"https://Stackoverflow.com/questions/6335408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/481904/"
] | For New I would use a boolean, an enum in this case would be overkill. | eBay has New, and New Other, to distinguish between merchandise sold in its original packaging and merchandise sold in different packaging or no packaging. I'd go for the enum for its extensibility, what you called "future proof". |
6,335,408 | I have a perhaps silly question... I am trying to determine what is the best approach for typing a property whose value will be either "New" or "Used". Do I use an `enum` or should I just go with a `boolean` (e.g. IsNew)? If I go with `enum`, what should I call this type and property name? (public NewOrUsed NewOrUsed {get; set;} <-- confusing)
Obviously, with `enum` I can have state that declares neither value (NONE, NEW, USED) and `enum` is more future-proof (although one can claim there is no chance other values will exist). Again, what is the appropriate name for such a type and property?
With `boolean` - it's pretty straight forward (either using IsNew or IsUsed)
I know it's silly, but I am curious what others think
Regards
Z..
Update
------
If you prefer `enum`, please comment on what should be appropriate name for type and property (e.g `public NewUsedType NewOrUsed {get; set;}`) | 2011/06/13 | [
"https://Stackoverflow.com/questions/6335408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/481904/"
] | >
> `enum` is more future proof
>
>
>
Not really. You have no idea what the future will bring. If you need to change it later, then change it. So, [KISS](http://en.wikipedia.org/wiki/KISS_principle). Go with:
```
public bool IsNew { get; set; }
```
Boom, done. Move on, add value elsewhere. | For New I would use a boolean, an enum in this case would be overkill. |
6,335,408 | I have a perhaps silly question... I am trying to determine what is the best approach for typing a property whose value will be either "New" or "Used". Do I use an `enum` or should I just go with a `boolean` (e.g. IsNew)? If I go with `enum`, what should I call this type and property name? (public NewOrUsed NewOrUsed {get; set;} <-- confusing)
Obviously, with `enum` I can have state that declares neither value (NONE, NEW, USED) and `enum` is more future-proof (although one can claim there is no chance other values will exist). Again, what is the appropriate name for such a type and property?
With `boolean` - it's pretty straight forward (either using IsNew or IsUsed)
I know it's silly, but I am curious what others think
Regards
Z..
Update
------
If you prefer `enum`, please comment on what should be appropriate name for type and property (e.g `public NewUsedType NewOrUsed {get; set;}`) | 2011/06/13 | [
"https://Stackoverflow.com/questions/6335408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/481904/"
] | >
> `enum` is more future proof
>
>
>
Not really. You have no idea what the future will bring. If you need to change it later, then change it. So, [KISS](http://en.wikipedia.org/wiki/KISS_principle). Go with:
```
public bool IsNew { get; set; }
```
Boom, done. Move on, add value elsewhere. | eBay has New, and New Other, to distinguish between merchandise sold in its original packaging and merchandise sold in different packaging or no packaging. I'd go for the enum for its extensibility, what you called "future proof". |
6,335,408 | I have a perhaps silly question... I am trying to determine what is the best approach for typing a property whose value will be either "New" or "Used". Do I use an `enum` or should I just go with a `boolean` (e.g. IsNew)? If I go with `enum`, what should I call this type and property name? (public NewOrUsed NewOrUsed {get; set;} <-- confusing)
Obviously, with `enum` I can have state that declares neither value (NONE, NEW, USED) and `enum` is more future-proof (although one can claim there is no chance other values will exist). Again, what is the appropriate name for such a type and property?
With `boolean` - it's pretty straight forward (either using IsNew or IsUsed)
I know it's silly, but I am curious what others think
Regards
Z..
Update
------
If you prefer `enum`, please comment on what should be appropriate name for type and property (e.g `public NewUsedType NewOrUsed {get; set;}`) | 2011/06/13 | [
"https://Stackoverflow.com/questions/6335408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/481904/"
] | You mentioned in a comment "I allready [sic] have a Condition - it refers to a condition when something is Y"Used" (e.g. used vehicle/book can be in "fair", "like new", "mint" condition) ;)"
So with that piece of information, I'd definitely go with a `bool`. You already have an extensible way of establishing the condition so this is more of a categorical thing. You may some time in the future you may want something whether more than one condition counts as "New" say:
```
public enum ConditionType {Fair, LikeNew, Mint, New}
public ConditionType Condition { get; set; }
public bool IsNew
{
get { return Condition == ConditionType.New || Condition == ConditionType.Mint; }
}
``` | For New I would use a boolean, an enum in this case would be overkill. |
6,335,408 | I have a perhaps silly question... I am trying to determine what is the best approach for typing a property whose value will be either "New" or "Used". Do I use an `enum` or should I just go with a `boolean` (e.g. IsNew)? If I go with `enum`, what should I call this type and property name? (public NewOrUsed NewOrUsed {get; set;} <-- confusing)
Obviously, with `enum` I can have state that declares neither value (NONE, NEW, USED) and `enum` is more future-proof (although one can claim there is no chance other values will exist). Again, what is the appropriate name for such a type and property?
With `boolean` - it's pretty straight forward (either using IsNew or IsUsed)
I know it's silly, but I am curious what others think
Regards
Z..
Update
------
If you prefer `enum`, please comment on what should be appropriate name for type and property (e.g `public NewUsedType NewOrUsed {get; set;}`) | 2011/06/13 | [
"https://Stackoverflow.com/questions/6335408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/481904/"
] | You mentioned in a comment "I allready [sic] have a Condition - it refers to a condition when something is Y"Used" (e.g. used vehicle/book can be in "fair", "like new", "mint" condition) ;)"
So with that piece of information, I'd definitely go with a `bool`. You already have an extensible way of establishing the condition so this is more of a categorical thing. You may some time in the future you may want something whether more than one condition counts as "New" say:
```
public enum ConditionType {Fair, LikeNew, Mint, New}
public ConditionType Condition { get; set; }
public bool IsNew
{
get { return Condition == ConditionType.New || Condition == ConditionType.Mint; }
}
``` | I would go with the enum, if I found myself constantly translating the boolean value into the value "new" or "used".
If I were more interested in this value as an indicator (such as doing `if(something.isNew)`), I'd use a boolean. |
6,335,408 | I have a perhaps silly question... I am trying to determine what is the best approach for typing a property whose value will be either "New" or "Used". Do I use an `enum` or should I just go with a `boolean` (e.g. IsNew)? If I go with `enum`, what should I call this type and property name? (public NewOrUsed NewOrUsed {get; set;} <-- confusing)
Obviously, with `enum` I can have state that declares neither value (NONE, NEW, USED) and `enum` is more future-proof (although one can claim there is no chance other values will exist). Again, what is the appropriate name for such a type and property?
With `boolean` - it's pretty straight forward (either using IsNew or IsUsed)
I know it's silly, but I am curious what others think
Regards
Z..
Update
------
If you prefer `enum`, please comment on what should be appropriate name for type and property (e.g `public NewUsedType NewOrUsed {get; set;}`) | 2011/06/13 | [
"https://Stackoverflow.com/questions/6335408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/481904/"
] | I would go with the enum, if I found myself constantly translating the boolean value into the value "new" or "used".
If I were more interested in this value as an indicator (such as doing `if(something.isNew)`), I'd use a boolean. | I'm generally opposed to over-engineering, so my first instinct was using a boolean.
But conceptually it doesn't feel like a logical boolean value. It feels like an enumeration which happens to have two values at the moment. I typically think about the conditions as `new` and `used` and not as `new` and `not new` in my head.
I expect other `Condition`s being added at a later point in time, such as `refurbished`. But of course refactoring from a single property won't be that hard thanks to IDE features like `Find All References`. And you'll need to retouch the logic using this property anyways once you add new values to the enumeration.
Future-proofing is the less important reason for me. That it doesn't feel conceptually clean is more important IMO. |
6,335,408 | I have a perhaps silly question... I am trying to determine what is the best approach for typing a property whose value will be either "New" or "Used". Do I use an `enum` or should I just go with a `boolean` (e.g. IsNew)? If I go with `enum`, what should I call this type and property name? (public NewOrUsed NewOrUsed {get; set;} <-- confusing)
Obviously, with `enum` I can have state that declares neither value (NONE, NEW, USED) and `enum` is more future-proof (although one can claim there is no chance other values will exist). Again, what is the appropriate name for such a type and property?
With `boolean` - it's pretty straight forward (either using IsNew or IsUsed)
I know it's silly, but I am curious what others think
Regards
Z..
Update
------
If you prefer `enum`, please comment on what should be appropriate name for type and property (e.g `public NewUsedType NewOrUsed {get; set;}`) | 2011/06/13 | [
"https://Stackoverflow.com/questions/6335408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/481904/"
] | >
> `enum` is more future proof
>
>
>
Not really. You have no idea what the future will bring. If you need to change it later, then change it. So, [KISS](http://en.wikipedia.org/wiki/KISS_principle). Go with:
```
public bool IsNew { get; set; }
```
Boom, done. Move on, add value elsewhere. | I would go with the enum, if I found myself constantly translating the boolean value into the value "new" or "used".
If I were more interested in this value as an indicator (such as doing `if(something.isNew)`), I'd use a boolean. |
6,335,408 | I have a perhaps silly question... I am trying to determine what is the best approach for typing a property whose value will be either "New" or "Used". Do I use an `enum` or should I just go with a `boolean` (e.g. IsNew)? If I go with `enum`, what should I call this type and property name? (public NewOrUsed NewOrUsed {get; set;} <-- confusing)
Obviously, with `enum` I can have state that declares neither value (NONE, NEW, USED) and `enum` is more future-proof (although one can claim there is no chance other values will exist). Again, what is the appropriate name for such a type and property?
With `boolean` - it's pretty straight forward (either using IsNew or IsUsed)
I know it's silly, but I am curious what others think
Regards
Z..
Update
------
If you prefer `enum`, please comment on what should be appropriate name for type and property (e.g `public NewUsedType NewOrUsed {get; set;}`) | 2011/06/13 | [
"https://Stackoverflow.com/questions/6335408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/481904/"
] | Use an enum. I would call it `Condition`. You don't need a `None` value. You can just make it nullable. | eBay has New, and New Other, to distinguish between merchandise sold in its original packaging and merchandise sold in different packaging or no packaging. I'd go for the enum for its extensibility, what you called "future proof". |
6,335,408 | I have a perhaps silly question... I am trying to determine what is the best approach for typing a property whose value will be either "New" or "Used". Do I use an `enum` or should I just go with a `boolean` (e.g. IsNew)? If I go with `enum`, what should I call this type and property name? (public NewOrUsed NewOrUsed {get; set;} <-- confusing)
Obviously, with `enum` I can have state that declares neither value (NONE, NEW, USED) and `enum` is more future-proof (although one can claim there is no chance other values will exist). Again, what is the appropriate name for such a type and property?
With `boolean` - it's pretty straight forward (either using IsNew or IsUsed)
I know it's silly, but I am curious what others think
Regards
Z..
Update
------
If you prefer `enum`, please comment on what should be appropriate name for type and property (e.g `public NewUsedType NewOrUsed {get; set;}`) | 2011/06/13 | [
"https://Stackoverflow.com/questions/6335408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/481904/"
] | For New I would use a boolean, an enum in this case would be overkill. | I'm generally opposed to over-engineering, so my first instinct was using a boolean.
But conceptually it doesn't feel like a logical boolean value. It feels like an enumeration which happens to have two values at the moment. I typically think about the conditions as `new` and `used` and not as `new` and `not new` in my head.
I expect other `Condition`s being added at a later point in time, such as `refurbished`. But of course refactoring from a single property won't be that hard thanks to IDE features like `Find All References`. And you'll need to retouch the logic using this property anyways once you add new values to the enumeration.
Future-proofing is the less important reason for me. That it doesn't feel conceptually clean is more important IMO. |
6,335,408 | I have a perhaps silly question... I am trying to determine what is the best approach for typing a property whose value will be either "New" or "Used". Do I use an `enum` or should I just go with a `boolean` (e.g. IsNew)? If I go with `enum`, what should I call this type and property name? (public NewOrUsed NewOrUsed {get; set;} <-- confusing)
Obviously, with `enum` I can have state that declares neither value (NONE, NEW, USED) and `enum` is more future-proof (although one can claim there is no chance other values will exist). Again, what is the appropriate name for such a type and property?
With `boolean` - it's pretty straight forward (either using IsNew or IsUsed)
I know it's silly, but I am curious what others think
Regards
Z..
Update
------
If you prefer `enum`, please comment on what should be appropriate name for type and property (e.g `public NewUsedType NewOrUsed {get; set;}`) | 2011/06/13 | [
"https://Stackoverflow.com/questions/6335408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/481904/"
] | I would go with the enum, if I found myself constantly translating the boolean value into the value "new" or "used".
If I were more interested in this value as an indicator (such as doing `if(something.isNew)`), I'd use a boolean. | eBay has New, and New Other, to distinguish between merchandise sold in its original packaging and merchandise sold in different packaging or no packaging. I'd go for the enum for its extensibility, what you called "future proof". |
64,589,801 | I'm trying to Filter the `id` of Connections by `name` e.g. return the `id` of connection, where the `name` is Equal to *12345678*.
I'm able to get all of records and also the values of `id` & `name` as well.
But, I Just want to Filer it e.g. How could I only get the record's `id`, where the `name` is equal to *12345678*? I wrote the code below (I know it's stupid) and it's returning the all records.
**CODE**
```
public class Alias
{
public string name { get; set; }
}
public class Connections
{
public Alias alias { get; set; }
public string id { get; set; }
}
public class RootObject
{
public List<Connections> connections { get; set; }
}
HttpClient hTTPClient = new HttpClient();
UserID = "12345678";
Uri getConnections = new Uri(string.Format("http://0.0.0.0:0000/getConnections"));
HttpResponseMessage restponseConnections = await hTTPClient.GetAsync(getConnections);
string contentConnections = await restponseConnections.Content.ReadAsStringAsync();
RootObject obj = JsonConvert.DeserializeObject<RootObject>(contentConnections);
foreach (Connections i in obj.connections)
{
if(!(i.alias.name == UserID))
{
Console.WriteLine(i.id);
}
}
```
**JSON**
```
{
"success": true,
"connections": [
{
"typeName": "AF.ConnectionRecord"
"alias": {
"name": "12345678",
"imageUrl": null
},
"endpoint": {
"did": null,
"verkey": [
"6KZYwhxzxWcrZnQravocia2XHyoK9V8pBVT7nBdAd5JX"
],
"uri": "http://0.0.0.0:0000"
},
"state": 2,
"id": "d0e4ccbf-5e2a-47bb-a218-78ea93a6066b",
"createdAtUtc": "2020-10-27T08:01:43.0724247",
"updatedAtUtc": "2020-10-27T08:01:45.7475196"
}
]
}
``` | 2020/10/29 | [
"https://Stackoverflow.com/questions/64589801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | use LINQ
```
using System.Linq;
...
var list = obj.connections.Where(c => c.alias.name == "xyz").ToList();
``` | In your case assuming you want to get 1 record, I'd suggest you use LINQ
```
using System.Linq;
//Rest of your code
var recId = obj.connections.Where(c => c.alias.name == "1234567").FirstOrDefault();
``` |
47,644,655 | Trying to do a few things ran into a snag. Trying to center the form where it asks for email and there is the 'lets talk' button. It should be centered right underneath the title "Lets get in touch"
I also want to give it a drop shadow however what i have is not working.
It should look like this in the end
[](https://i.stack.imgur.com/gyc8A.png)
here is a fiddle with my code: <https://jsfiddle.net/vcx4vm39/>
Here is all the css that is effecting the form.
```
form{
display: table;
margin: 0 auto;
}
#forth{
width: 100%
}
input[type=text], select {
width: 400px;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
/* border: 1px solid #ccc; */
border-radius: 30px;
box-sizing: border-box;
font-family: proxima nova;
font-size: 14px;
position: absolute;
-webkit-box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
-moz-box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
}
input[type=submit] {
width: 160px;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 30px;
cursor: pointer;
background-color: #0B315C;
font-family: proxima nova;
font-size: 14px;
font-weight: bold;
position: absolute;
margin: -10px 0px 0px 240px;
}
``` | 2017/12/05 | [
"https://Stackoverflow.com/questions/47644655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9041386/"
] | Check out this updated fiddle: <https://jsfiddle.net/vcx4vm39/2/>
Added the class `.email-form` to the form and added the following CSS:
```
.email-form {
width: 400px;
}
.email-form input {
border: 0;
box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.2);
}
``` | Removed, most of the not necessary code from the fiddle. And you can see it's in the center now.
**EDIT**: Credit for the box-shadow, goes to the second answer.
```css
@import url('https://fonts.googleapis.com/css?family=Roboto');
@import url('https://fonts.googleapis.com/css?family=Roboto:bold');
@import url('https://fonts.googleapis.com/css?family=Roboto:100');
@import url('https://fonts.googleapis.com/css?family=Roboto:600');
html,
body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
top: 0;
background-image: url('images/bg.png');
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
.logo {
width: 150px;
fill: white;
display: block;
position: relative;
padding: 23px 0px 0px 50px;
}
.logo svg {
position: absolute;
top: 0px;
right: 0px;
}
#hireus {
position: absolute;
top: 0;
right: 0;
padding: 3px;
font-family: proxima nova;
font-size: 12px;
text-decoration: none;
color: white;
margin: 27px 50px 0px 0px;
text-decoration: none;
z-index: 10;
}
.intro {
height: 100%;
width: 100%;
margin: auto;
display: table;
/*
top: 0;
background-image: url('images/bg.png');
background-size: cover;
background-position: center;
background-repeat: no-repeat;
*/
}
.intro .inner {
display: table-cell;
vertical-align: middle;
width: 100%;
max-width: none;
}
ul {
list-style-type: none;
overflow: hidden;
position: absolute;
top: 0;
left: 0;
opacity: 0.8;
display: table;
margin: 0;
width: 100%;
text-align: center;
padding: 0
}
li {
/*
width: 120px;
height: 40px;
*/
margin: 0px 0px;
display: inline-block;
padding: 0;
font-family: proxima nova;
font-size: 10px;
text-decoration: none;
}
.new a {
display: block;
/*
width: 120px;
height: 40px;
*/
/* line-height: 40px; */
text-decoration: none;
text-align: center;
color: white;
/* margin: 20px 20px; */
margin: 32px 20px 0px 20px;
}
.content {
max-width: 1200px;
margin: 0 auto;
text-align: center;
padding-bottom: 7%;
}
.content h1 {
font-family: proxima nova;
font-size: 520%;
font-weight: bold;
color: white;
margin: 0;
padding-bottom: 3px;
}
.content p {
font-family: proxima nova;
font-size: 12px;
font-weight: 100;
color: white;
margin: 0 auto;
max-width: 420px;
padding-bottom: 25px;
}
.btn {
font-family: proxima nova;
font-size: 14px;
font-weight: bold;
color: white;
text-decoration: none;
border: solid 1px white;
/* padding: 10px 100px; */
border-radius: 60px;
transition: all 0.5s;
width: 160px;
display: inline-block;
text-align: center;
padding-top: 13px;
padding-bottom: 13px;
}
.btn:hover {
color: #b0ccff;
border: solid 1px #b0ccff;
}
.btn2 {
font-family: proxima nova;
font-size: 14px;
font-weight: bold;
color: white;
text-decoration: none;
border: solid 1px #0B315C;
/* padding: 10px 100px; */
border-radius: 60px;
transition: all 0.5s;
width: 160px;
background-color: #0B315C;
display: inline-block;
text-align: center;
padding-top: 13px;
padding-bottom: 13px;
margin-left: 30px;
-webkit-box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
-moz-box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
}
.btn2:hover {
color: #b0ccff;
border: solid 1px #b0ccff;
}
#scroll {
color: green;
}
.title {
font-family: proxima nova;
font-size: 50px;
font-weight: 600;
color: black;
text-align: center;
margin-top: 60px;
padding-bottom: 2px;
}
.subtitle {
font-family: proxima nova;
font-size: 12px;
font-weight: 200;
color: #9D9D9D;
text-align: center;
margin-top: -45px;
padding-bottom: 2px;
}
#second {
border-bottom: 1px solid #E6E6E6;
width: 480px;
margin: auto;
}
#Layer_1 {
width: 100px;
height: 100px;
}
#group2 {}
.whatwedo {
text-align: center;
width: 100%;
margin-top: 100px;
}
.subject {
text-align: center;
width: 300px;
display: inline-block;
margin: 0px 50px;
}
.subject h2 {
font-family: proxima nova;
font-size: 20px;
font-weight: 600;
color: black;
margin-bottom: 12px;
}
.desc {
font-family: proxima nova;
font-size: 12px;
font-weight: 200;
color: #9D9D9D;
}
.group3 {
position: relative;
text-align: center;
color: white;
margin-top: 90px;
}
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-family: proxima nova;
font-size: 24px;
font-weight: 100;
color: white;
width: 550px;
}
form {
display: table;
margin: 0 auto;
}
#forth {
width: 100%
}
input[type=text],
select {
width: 400px;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
/* border: 1px solid #ccc; */
border-radius: 30px;
box-sizing: border-box;
font-family: proxima nova;
font-size: 14px;
-webkit-box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
-moz-box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
}
input[type=submit] {
width: 160px;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 30px;
cursor: pointer;
background-color: #0B315C;
font-family: proxima nova;
font-size: 14px;
font-weight: bold;
position: relative;
bottom: 42px;
margin: -10px 0px 0px 240px;
}
.email-form {
width: 400px;
}
.email-form input {
border: 0;
box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.2);
}
/*--- Media Queries --*/
@media screen and (max-width: 900px) {
.content {
padding-bottom: 10%;
}
.content h1 {
font-size: 400%
}
.btn {
font-size: 110%;
padding: 9px 43px;
}
}
@media screen and (max-width: 768px) {
.content {
padding-bottom: 12%;
}
.content h1 {
font-size: 300%
}
.btn {
font-size: 100%;
padding: 9px 43px;
}
}
@media screen and (max-width: 480px) {
.content {
padding-bottom: 14%;
}
.content h1 {
font-size: 300%
}
.btn {
font-size: 100%;
padding: 10px 44px;
}
}
```
```html
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<div id="forth">
<h2 class="title">Lets get in touch</h2>
<form action="mailto:contact@madebylaunchpad.com" method="post" enctype="text/plain" class="email-form">
<input type="text" name="mail" placeholder="Your email address"><br>
<input type="submit" value="Lets talk">
</form>
</div>
```
```
input[type=text], select {
//remove position:absolute;
}
input[type=submit] {
position:relative;
bottom:44px;
}
``` |
1,015,113 | I tried using dig and I got the error in the title.
My /etc/resolv.conf is this
```
nameserver 67.207.67.2
nameserver 67.207.67.3
nameserver ns1.name.com
nameserver ns2.name.com
nameserver ns3.name.com
nameserver ns4.name.com
```
The first two are the default digital ocean dns, the other are for my domain registrar.
So I tried to add two cloudflare dns, and the file is this:
```
nameserver 1.1.1.1
nameserver 1.0.0.1
nameserver 67.207.67.2
nameserver 67.207.67.3
nameserver ns1.name.com
nameserver ns2.name.com
nameserver ns3.name.com
nameserver ns4.name.com
```
After I did, dig still didn't work.
But if I comment the \*name.com nameservers, dig works:
```
nameserver 1.1.1.1
nameserver 1.0.0.1
nameserver 67.207.67.2
nameserver 67.207.67.3
#nameserver ns1.name.com
#nameserver ns2.name.com
#nameserver ns3.name.com
#nameserver ns4.name.com
```
The fact is that if I comment these \*name.com nameservers, my site went (**and still is, trying do fix**) down after some minutes.
So how can I leave these \*name.com nameservers and be able to use dig and nslookup and stuff like that?
EDIT:
users below noticed that I must have misconfigured something in my site. And it's true. I noticed that there is a "domain" setting in digitalocean panel, and I never configured that. Now I did it and also changed the nameservers of my registrar to the digitalocean nameserver. Now I should only wait for nameserver propagation I guess?
My `tcpdump -ni any port 53 | tee dns_problem.log` output as suggested by a user below:
```
08:27:34.721547 IP MYSERVERIP.55951 > 67.207.67.2.53: 20768+ AAAA? ams3.sonar.digitalocean.com. (45)
08:27:34.721634 IP MYSERVERIP.41382 > 67.207.67.2.53: 28628+ A? ams3.sonar.digitalocean.com. (45)
08:27:34.722304 IP 67.207.67.2.53 > MYSERVERIP.55951: 20768 0/1/0 (103)
08:27:34.722304 IP 67.207.67.2.53 > MYSERVERIP.41382: 28628 1/0/0 A 5.101.110.176 (61)
08:29:34.732206 IP MYSERVERIP.44766 > 67.207.67.2.53: 29521+ AAAA? ams3.sonar.digitalocean.com. (45)
08:29:34.732384 IP MYSERVERIP.45803 > 67.207.67.2.53: 49118+ A? ams3.sonar.digitalocean.com. (45)
08:29:34.734239 IP 67.207.67.2.53 > MYSERVERIP.44766: 29521 0/1/0 (103)
08:29:34.734239 IP 67.207.67.2.53 > MYSERVERIP.45803: 49118 1/0/0 A 5.101.110.176 (61)
08:29:34.844794 IP 54.91.82.218.54035 > MYSERVERIP.53: 23982+ ANY? www.example.com. (33)
08:31:34.740307 IP MYSERVERIP.54008 > 67.207.67.2.53: 47094+ AAAA? ams3.sonar.digitalocean.com. (45)
08:31:34.740643 IP MYSERVERIP.49591 > 67.207.67.2.53: 21439+ A? ams3.sonar.digitalocean.com. (45)
08:31:34.741079 IP 67.207.67.2.53 > MYSERVERIP.54008: 47094 0/1/0 (103)
08:31:34.741079 IP 67.207.67.2.53 > MYSERVERIP.49591: 21439 1/0/0 A 5.101.110.176 (61)
08:32:48.328903 IP 54.91.82.218.33095 > MYSERVERIP.53: 53251+ A? www.example.com. (33)
08:33:34.748240 IP MYSERVERIP.33811 > 67.207.67.2.53: 20882+ AAAA? ams3.sonar.digitalocean.com. (45)
08:33:34.748596 IP MYSERVERIP.40348 > 67.207.67.2.53: 63964+ A? ams3.sonar.digitalocean.com. (45)
08:33:34.749127 IP 67.207.67.2.53 > MYSERVERIP.33811: 20882 0/1/0 (103)
08:33:34.749127 IP 67.207.67.2.53 > MYSERVERIP.40348: 63964 1/0/0 A 5.101.110.176 (61)
08:35:34.762328 IP MYSERVERIP.46593 > 67.207.67.2.53: 52540+ AAAA? ams3.sonar.digitalocean.com. (45)
08:35:34.762875 IP MYSERVERIP.34757 > 67.207.67.2.53: 23545+ A? ams3.sonar.digitalocean.com. (45)
08:35:34.763153 IP 67.207.67.2.53 > MYSERVERIP.46593: 52540 0/1/0 (103)
08:35:34.763208 IP 67.207.67.2.53 > MYSERVERIP.34757: 23545 1/0/0 A 5.101.110.176 (61)
08:37:34.772318 IP MYSERVERIP.60307 > 67.207.67.2.53: 25440+ AAAA? ams3.sonar.digitalocean.com. (45)
08:37:34.772691 IP MYSERVERIP.35584 > 67.207.67.2.53: 14199+ A? ams3.sonar.digitalocean.com. (45)
08:37:34.773173 IP 67.207.67.2.53 > MYSERVERIP.60307: 25440 0/1/0 (103)
08:37:34.773225 IP 67.207.67.2.53 > MYSERVERIP.35584: 14199 1/0/0 A 5.101.110.176 (61)
08:39:34.782271 IP MYSERVERIP.35598 > 67.207.67.2.53: 17037+ AAAA? ams3.sonar.digitalocean.com. (45)
08:39:34.782652 IP MYSERVERIP.41388 > 67.207.67.2.53: 46756+ A? ams3.sonar.digitalocean.com. (45)
08:39:34.783076 IP 67.207.67.2.53 > MYSERVERIP.35598: 17037 0/1/0 (103)
08:39:34.783100 IP 67.207.67.2.53 > MYSERVERIP.41388: 46756 1/0/0 A 5.101.110.176 (61)
08:41:34.790595 IP MYSERVERIP.37914 > 67.207.67.2.53: 25940+ AAAA? ams3.sonar.digitalocean.com. (45)
08:41:34.790929 IP MYSERVERIP.42627 > 67.207.67.2.53: 1440+ A? ams3.sonar.digitalocean.com. (45)
08:41:34.791391 IP 67.207.67.2.53 > MYSERVERIP.37914: 25940 0/1/0 (103)
08:41:34.791493 IP 67.207.67.2.53 > MYSERVERIP.42627: 1440 1/0/0 A 5.101.110.176 (61)
08:41:49.641648 IP MYSERVERIP.53649 > 67.207.67.2.53: 5397+ [1au] A? google.com. (51)
08:41:49.642872 IP 67.207.67.2.53 > MYSERVERIP.53649: 5397 6/0/1 A 108.177.126.138, A 108.177.126.102, A 108.177.126.100, A 108.177.126.139, A 108.177.126.101, A 108.177.126.113 (135)
08:43:34.799037 IP MYSERVERIP.53977 > 67.207.67.2.53: 3711+ AAAA? ams3.sonar.digitalocean.com. (45)
08:43:34.799376 IP MYSERVERIP.37354 > 67.207.67.2.53: 64810+ A? ams3.sonar.digitalocean.com. (45)
08:43:34.799854 IP 67.207.67.2.53 > MYSERVERIP.53977: 3711 0/1/0 (103)
08:43:34.799869 IP 67.207.67.2.53 > MYSERVERIP.37354: 64810 1/0/0 A 5.101.110.176 (61)
08:45:34.810213 IP MYSERVERIP.37036 > 67.207.67.2.53: 49990+ AAAA? ams3.sonar.digitalocean.com. (45)
08:45:34.810328 IP MYSERVERIP.47914 > 67.207.67.2.53: 4935+ A? ams3.sonar.digitalocean.com. (45)
08:45:34.811003 IP 67.207.67.2.53 > MYSERVERIP.47914: 4935 1/0
``` | 2020/05/01 | [
"https://serverfault.com/questions/1015113",
"https://serverfault.com",
"https://serverfault.com/users/572649/"
] | Not sure why you are trying to do it, but putting your registrar's servers in your resolv.conf is almost certainly the wrong thing to do.
Likewise, putting in the DNS names into a resolv.conf is the wrong thing to do. The resolv.conf is used to define servers that translate names to IP. If you commented out the other servers, how are you expecting DNS to work at all? How would your dns client know what IP to connect to `ns1.name.com` to attempt to resolve a name?
The `nameserver` directive in the resolv.conf should have IP addresses. (see the man excerpt below).
>
> The fact is that if I comment these \*name.com nameservers, my site goes down after some minutes. So how can I leave these \*name.com nameservers.
>
>
>
You should not try to leave them. Having them there is wrong. Instead you should figure out the '**real**' problem and fix that.
Perhaps you need to run a local DNS server with a 'forward zone' for some reason, so that your domain is always redirected to your registrar. Perhaps you have improperly configured your DNS somewhere else. You need to find and fix that.
If it was me, I would probably remove those lines and then start a tcpdump session in screen/tmux and watch all DNS traffic. Wait for whatever failure you are seeing to happen. Then look at see what DNS requests are failing. Then fix them.
The command you might want to use to have a long-running dns capture with tcpdump command like this.
```
tcpdump -ni any port 53 | tee dns_problem.log
```
---
For your reference, see the man page of resolv.conf.
<http://man7.org/linux/man-pages/man5/resolv.conf.5.html>
```
RESOLV.CONF(5)
...
nameserver Name server **IP address**
Internet address of a name server that the resolver should
query, either an IPv4 address (in dot notation), or an IPv6
address in colon (and possibly dot) notation as per RFC 2373.
...
``` | You can't use domain names. Name servers need to be IP addresses.
You can convert the name servers into IP addresses and list those, but frankly I'm not sure what you are trying to do and expect that while this will not error it won't work as you expect. |
4,236,874 | After searching the API and no luck, mybe anyone know how could I retrieve the SIM ID of the device?
thanks,
ray. | 2010/11/21 | [
"https://Stackoverflow.com/questions/4236874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/260511/"
] | Here is the code to get International Mobile Subscriber Identity (IMSI No.) id and phone id (IMEI No.) and Sim No. programmatically
Before doing this also set the user permission in the manifest file "android.permission.READ\_PHONE\_STATE"
```
TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String imsi = mTelephonyMgr.getSubscriberId();
String imei = mTelephonyMgr.getDeviceId();
String simno = mTelephonyMgr.getSimSerialNumber();
Log.v("", ""+imsi);
Log.v("", ""+imei);
Log.v("", ""+simno);
``` | To retrieve the IMSI (subscriber ID in the SIM), Use the [getSubscriberId method in the TelephonyManager API](http://developer.android.com/reference/android/telephony/TelephonyManager.html#getSubscriberId%28%29). |
4,236,874 | After searching the API and no luck, mybe anyone know how could I retrieve the SIM ID of the device?
thanks,
ray. | 2010/11/21 | [
"https://Stackoverflow.com/questions/4236874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/260511/"
] | Here is the code to get International Mobile Subscriber Identity (IMSI No.) id and phone id (IMEI No.) and Sim No. programmatically
Before doing this also set the user permission in the manifest file "android.permission.READ\_PHONE\_STATE"
```
TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String imsi = mTelephonyMgr.getSubscriberId();
String imei = mTelephonyMgr.getDeviceId();
String simno = mTelephonyMgr.getSimSerialNumber();
Log.v("", ""+imsi);
Log.v("", ""+imei);
Log.v("", ""+simno);
``` | Frrom [wikiPedia](http://en.wikipedia.org/wiki/Subscriber_Identity_Module#Issuer_identification_number_.28IIN.29)
>
> The Id = **Issuer identification number**
> (IIN) Maximum of seven digits: Major
> industry identifier (MII), 2 digits,
> 89 for telecommunication purposes.
> Country code, 1-3 digits, as defined
> by ITU-T recommendation E.164. Issuer
> identifier, 1-4 digits.
>
>
>
so the API is :
```
public String getSimCountryIso ()
public String getSimSerialNumber ()
public String getSubscriberId ()
``` |
10,226 | I'm trying to get the cdf from a pdf, which, according to [this MIT open courseware video](https://www.youtube.com/watch?v=wQ6Q9W3Y1ZE), is as simple as getting integral from -$\infty$ to $\infty$. Like this:
$$
F\_z(z) = \int\_{-\infty}^\infty f\_z(z)dz\, = 1
$$
And that works for functions like this: $f\_x(X)$
But what about a function like this $f(X;\beta)$?
Yeah, this is a homework problem, so I don't expect an exact answer, but hopefully some general principles. I have a hard time googling to learn how to do this because I don't know what to call this kind of function $f(X;\beta)$, and I don't know how to type a $\beta$ into google.
The pdf I have is:
$$
f(X;\beta)=
\begin{cases}
\frac {e^{-X/\beta}}{\beta}, & \ X\geq0 \\
0, & \text{otherwise}
\end{cases}
$$
and the cdf it comes out to is:
$$
f(X;\theta)=1-e^{-X/\beta}
$$
Part of my question is also, why did the $f(X;\beta)$ become $f(X;\theta)$? | 2016/01/15 | [
"https://economics.stackexchange.com/questions/10226",
"https://economics.stackexchange.com",
"https://economics.stackexchange.com/users/-1/"
] | CDF = integral of PDF from $-\infty$ to $x$, or:
$F\left(x\right) = \int\_{-\infty}^{x} f\left(u\right) du$.
Functions like $f\left(x;\beta\right)$ take $\beta$ as the parameters, the $\beta$ index *different* probability density functions. You don't need to integrate over them to get the CDF.
$F\left(x;\beta\right) = \int\_{-\infty}^{x} f\left(u;\beta\right)du$. | In addition to what John said (I would have commented on his answer, but don't have enough reputation). And this is not conditional, conditional would be $f(X|\beta)$
$$ F\_X(x;\beta) = P(X \leq x; \beta=\theta) = \int\_{-\infty}^{x} f\_X(x;\beta) dx $$
We fix $x=u$ and $\beta=\theta$
$$ P(X \leq u; \theta)=\int\_{-\infty}^u f\_X(u;\theta) du $$
$$ = \int\_{- \infty}^0 f(u;\theta) du + \int\_0^x f(u; \theta) du $$
$$ = 0 + \int\_0^x \frac{e^{-u/\theta}}{\theta} du $$
$$ = 1 - e^{-x/\theta}$$
Then over the set $X$ and and at particular values $\beta=\theta$
$$ F\_X(X;\theta) = 1 - e^{-X/\beta}$$ |
61,144 | I'm a Stack Overflow n00b, but I believe it's an invaluable resource, and really has been so far to my deving on different projects.
Anyway, I have seen users write inline code.
In other words, they are in a comment or something like that, and they want to write some code such as $(document).ready(function(){});
Except, instead of having appear as plain text, it appears like this:
```
$(document).ready(function(){});
```
Except, inline.
Anyone want to inform me as to how I can get this to work? | 2010/08/16 | [
"https://meta.stackexchange.com/questions/61144",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/150095/"
] | What my somewhat pedantic friend meant to say was "use backticks" (~ key)
in line `this is my code this is my code` in line.
update: Since not everyone has an English keyboard layout and the backtick key may be missing, a good alternative is `ALT+96` (from numeric keypad) or just copy and paste this: ` | See <https://meta.stackoverflow.com/editing-help> , which is linked from …
* the little `[?]` icon above the edit area
* in the editing sidebar where it says `full reference »`
The specific section you want is the one that says **Code Spans** |
19,659,467 | What is the difference between a view and a volatile table in Teradata? As far as I know, a volatile table is removed with the end of the session. Also it is only me who can see the volatile table as opposed to the view. Are there any other significant differences? | 2013/10/29 | [
"https://Stackoverflow.com/questions/19659467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2917375/"
] | A volatile table stores the data physically. You can access that data multiple times during your session. With a View the data is collected every time you access it.
To help speed up queries on views, you can use Join Indexes on Teradata. They physically store the results of a certain select and maintain it when the underlying data is changed (insert, update, delete) automatically - like most of things on a Teradata. | Also the volatile table holds the data in it for the session. If the data in the source-table changes, it does not automatically change it in the volatile table. View would automatically include the changes as it simply re-runs the SQL on the source-tables. |
19,659,467 | What is the difference between a view and a volatile table in Teradata? As far as I know, a volatile table is removed with the end of the session. Also it is only me who can see the volatile table as opposed to the view. Are there any other significant differences? | 2013/10/29 | [
"https://Stackoverflow.com/questions/19659467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2917375/"
] | A volatile table is a temporary table that is only held until the end of session. This is created by default in your "personal schema" and consumes your spool space to maintain.
A view is an object that is permanent across sessions, generates from tables existing in the environment you are in, and does not consume spool space continuously.
Generally speaking I use volatile tables to upload from scripts so that I can process information and drop table easily at the end of a session. I use views to change the way a user sees information that resides in other tables or to restrict access to information to certain users without altering root tables. | Also the volatile table holds the data in it for the session. If the data in the source-table changes, it does not automatically change it in the volatile table. View would automatically include the changes as it simply re-runs the SQL on the source-tables. |
57,655,660 | I'm trying to get a chart from the [charts\_flutter package](https://pub.dev/packages/charts_flutter) to expand to fill available space, when it is inside a Row which is inside a Column. I've spent a couple of hours trying to do this but I must be missing something! This is visually what I'm trying to achieve:
[](https://i.stack.imgur.com/H5Kik.png)
Here's a minimal working example. I must have tried a hundred combinations of Expanded, Flexible, main axis size, cross axis alignment etc. but I just can't seem to find the correct one. Currently the bottom overflows by infinity pixels, with `object was given an infinite size during layout`. There is [this open issue](https://github.com/google/charts/issues/129), I don't know if it's related, and there is no answer. I just need help with the bit of code inside `runApp`:
```
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:flutter/material.dart';
void main() => runApp(
// HOW DO I LAY THIS OUT?
Column(
children: <Widget>[
Container(height: 200, color: Colors.orange),
Row(
textDirection: TextDirection.ltr,
children: <Widget>[
Container(width: 200,color: Colors.orange),
Expanded(child: SimpleTimeSeriesChart.withSampleData())
],
)
],
)
);
class SimpleTimeSeriesChart extends StatelessWidget {
final List<charts.Series> seriesList;
final bool animate;
SimpleTimeSeriesChart(this.seriesList, {this.animate});
factory SimpleTimeSeriesChart.withSampleData() {
return new SimpleTimeSeriesChart(
_createSampleData(),
animate: false,
);
}
@override
Widget build(BuildContext context) {
return new charts.TimeSeriesChart(
seriesList,
animate: animate,
dateTimeFactory: const charts.LocalDateTimeFactory(),
);
}
/// Create one series with sample hard coded data.
static List<charts.Series<TimeSeriesSales, DateTime>> _createSampleData() {
final data = [
new TimeSeriesSales(new DateTime(2017, 9, 19), 5),
new TimeSeriesSales(new DateTime(2017, 9, 26), 25),
new TimeSeriesSales(new DateTime(2017, 10, 3), 100),
new TimeSeriesSales(new DateTime(2017, 10, 10), 75),
];
return [
new charts.Series<TimeSeriesSales, DateTime>(
id: 'Sales',
colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
domainFn: (TimeSeriesSales sales, _) => sales.time,
measureFn: (TimeSeriesSales sales, _) => sales.sales,
data: data,
)
];
}
}
class TimeSeriesSales {
final DateTime time;
final int sales;
TimeSeriesSales(this.time, this.sales);
}
``` | 2019/08/26 | [
"https://Stackoverflow.com/questions/57655660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40952/"
] | \*\*see why at Step 8 - scroll down \*\*
Problem
-------
>
> I'm trying to get a chart from the charts\_flutter package to expand to fill available space
>
>
>
Error Evidence
--------------
>
> object was given an infinite size during layout
>
>
>
Solution
--------
Wrap the Row with Expanded
```
Column(children: <Widget>[Expanded(child: Row())])
```
Screenshot
----------
[](https://i.stack.imgur.com/2fh3S.png)
Note:
-----
* , thanks for provide minimal code
Full Working Code
-----------------
```
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:flutter/material.dart';
void main() => runApp(
// HOW DO I LAY THIS OUT?
Column(
children: <Widget>[
Container(height: 200, color: Colors.orange),
Expanded(
child: Row(
textDirection: TextDirection.ltr,
children: <Widget>[
Container(width: 200, color: Colors.green),
Expanded(child: SimpleTimeSeriesChart.withSampleData()),
],
),
)
],
));
class SimpleTimeSeriesChart extends StatelessWidget {
final List<charts.Series> seriesList;
final bool animate;
SimpleTimeSeriesChart(this.seriesList, {this.animate});
factory SimpleTimeSeriesChart.withSampleData() {
return new SimpleTimeSeriesChart(
_createSampleData(),
animate: false,
);
}
@override
Widget build(BuildContext context) {
return new charts.TimeSeriesChart(
seriesList,
animate: animate,
dateTimeFactory: const charts.LocalDateTimeFactory(),
);
}
/// Create one series with sample hard coded data.
static List<charts.Series<TimeSeriesSales, DateTime>> _createSampleData() {
final data = [
new TimeSeriesSales(new DateTime(2017, 9, 19), 5),
new TimeSeriesSales(new DateTime(2017, 9, 26), 25),
new TimeSeriesSales(new DateTime(2017, 10, 3), 100),
new TimeSeriesSales(new DateTime(2017, 10, 10), 75),
];
return [
new charts.Series<TimeSeriesSales, DateTime>(
id: 'Sales',
colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
domainFn: (TimeSeriesSales sales, _) => sales.time,
measureFn: (TimeSeriesSales sales, _) => sales.sales,
data: data,
)
];
}
}
class TimeSeriesSales {
final DateTime time;
final int sales;
TimeSeriesSales(this.time, this.sales);
}
```
Extra : how to read the error (Full Error Dump Attached in the end)
-------------------------------------------------------------------
Step 1 : Locate the start
-------------------------
```
I/flutter ( 4228): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
```
Step 2: Locate the end
----------------------
```
I/flutter ( 4228): ════════════════════════════════════════════════════════════════════════════════════════════════════
```
Step 3: read the error
----------------------
scan the error with your eyes you will see some phrases like
---
>
>
> ```
> I/flutter ( 4228): constraints: BoxConstraints(w=320.0, h=480.0)
>
> ```
>
>
---
>
>
> ```
> I/flutter ( 4228): The following assertion was thrown during performLayout():
>
> ```
>
>
---
```
I/flutter ( 4228): Summary 1: RenderCustomMultiChildLayoutBox object was given an infinite size during layout.
```
---
Step 4 :decide what is the type of the
--------------------------------------
this is a ***box constraints*** error
* read more :
+ [Dealing with box constraints - Flutter](https://flutter.dev/docs/development/ui/layout/box-constraints)
+ [BoxConstraints class - rendering library - Dart API](https://api.flutter.dev/flutter/rendering/BoxConstraints-class.html)
+ [dart - TextField inside of Row causes layout exception: Unable to calculate size - Stack Overflow](https://stackoverflow.com/questions/45986093/textfield-inside-of-row-causes-layout-exception-unable-to-calculate-size/45990477#45990477)
Step 5 :how to know what widget is throwing the error
-----------------------------------------------------
go near the end it will give you the source:
```
I/flutter ( 4228): creator: CustomMultiChildLayout ← TimeSeriesChart ← SimpleTimeSeriesChart ← Expanded ← Row ← Column
I/flutter ( 4228): ← [root]
```
* so it is inside the TimeSeriesChart
Step 6 : what is missing
------------------------
go near the end it will give you the missing constraint
```
I/flutter ( 4228): constraints: BoxConstraints(w=120.0, 0.0<=h<=Infinity)
```
* notice : ***0.0<=h<=Infinity***
* the ***height*** can't be Infinity
Step 7 :
--------
* warp the source with a **SizedBox** to make sure it' what throwing the error , to see if it solve it
* [SizedBox](https://api.flutter.dev/flutter/widgets/SizedBox-class.html)
>
> A box with a specified size.
>
>
> If given a child, this widget forces its child to have a specific width and/or height (assuming values are permitted by this widget's parent). If either the width or height is null, this widget will size itself to match the child's size in that dimension.
>
>
>
Step 8 :
--------
1. the TimeSeriesChart(child) asked Raw(parent) for height
2. the Raw(child) asked Column(parent) for height
3. the Column doesn't know
4. by why the Column doesn't know, because by default behavior is that it will leave it for the children to decide thir own height
5. but we can tell the Column that the children doesn't know so expand them to the available space
Error Dump
----------
```
I/flutter ( 4228): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 4228): The following assertion was thrown during performLayout():
I/flutter ( 4228): FlutterError contained multiple error summaries.
I/flutter ( 4228): All FlutterError objects should have only a single short (one line) summary description of the
I/flutter ( 4228): problem that was detected.
I/flutter ( 4228): Malformed FlutterError:
I/flutter ( 4228): RenderCustomMultiChildLayoutBox object was given an infinite size during layout.
I/flutter ( 4228): This probably means that it is a render object that tries to be as big as possible, but it was put
I/flutter ( 4228): inside another render object that allows its children to pick their own size.
I/flutter ( 4228): RenderCustomMultiChildLayoutBox object was given an infinite size during layout.
I/flutter ( 4228): This probably means that it is a render object that tries to be as big as possible, but it was put
I/flutter ( 4228): inside another render object that allows its children to pick their own size.
I/flutter ( 4228): The nearest ancestor providing an unbounded height constraint is: RenderFlex#d29e7 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE:
I/flutter ( 4228): creator: Column ← [root]
I/flutter ( 4228): parentData: <none>
I/flutter ( 4228): constraints: BoxConstraints(w=320.0, h=480.0)
I/flutter ( 4228): size: MISSING
I/flutter ( 4228): direction: vertical
I/flutter ( 4228): mainAxisAlignment: start
I/flutter ( 4228): mainAxisSize: max
I/flutter ( 4228): crossAxisAlignment: center
I/flutter ( 4228): verticalDirection: down
I/flutter ( 4228): The constraints that applied to the RenderCustomMultiChildLayoutBox were:
I/flutter ( 4228): BoxConstraints(w=120.0, 0.0<=h<=Infinity)
I/flutter ( 4228): The exact size it was given was:
I/flutter ( 4228): Size(120.0, Infinity)
I/flutter ( 4228): See https://flutter.dev/docs/development/ui/layout/box-constraints for more information.
I/flutter ( 4228):
I/flutter ( 4228): The malformed error has 2 summaries.
I/flutter ( 4228): Summary 1: RenderCustomMultiChildLayoutBox object was given an infinite size during layout.
I/flutter ( 4228): Summary 2: RenderCustomMultiChildLayoutBox object was given an infinite size during layout.
I/flutter ( 4228):
I/flutter ( 4228): This error should still help you solve your problem, however please also report this malformed error
I/flutter ( 4228): in the framework by filing a bug on GitHub:
I/flutter ( 4228): https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 4228):
I/flutter ( 4228): When the exception was thrown, this was the stack:
I/flutter ( 4228): #0 new FlutterError.fromParts.<anonymous closure> (package:flutter/src/foundation/assertions.dart:540:9)
I/flutter ( 4228): #1 new FlutterError.fromParts (package:flutter/src/foundation/assertions.dart:543:6)
I/flutter ( 4228): #2 RenderBox.debugAssertDoesMeetConstraints.<anonymous closure> (package:flutter/src/rendering/box.dart:1966:28)
I/flutter ( 4228): #3 RenderBox.debugAssertDoesMeetConstraints (package:flutter/src/rendering/box.dart:2029:6)
I/flutter ( 4228): #4 RenderBox.size=.<anonymous closure> (package:flutter/src/rendering/box.dart:1740:7)
I/flutter ( 4228): #5 RenderBox.size= (package:flutter/src/rendering/box.dart:1742:6)
I/flutter ( 4228): #6 RenderCustomMultiChildLayoutBox.performLayout (package:flutter/src/rendering/custom_layout.dart:355:5)
I/flutter ( 4228): #7 RenderObject.layout (package:flutter/src/rendering/object.dart:1619:7)
I/flutter ( 4228): #8 RenderFlex.performLayout (package:flutter/src/rendering/flex.dart:805:17)
I/flutter ( 4228): #9 RenderObject.layout (package:flutter/src/rendering/object.dart:1619:7)
I/flutter ( 4228): #10 RenderFlex.performLayout (package:flutter/src/rendering/flex.dart:743:15)
I/flutter ( 4228): #11 RenderObject.layout (package:flutter/src/rendering/object.dart:1619:7)
I/flutter ( 4228): #12 RenderView.performLayout (package:flutter/src/rendering/view.dart:151:13)
I/flutter ( 4228): #13 RenderObject._layoutWithoutResize (package:flutter/src/rendering/object.dart:1496:7)
I/flutter ( 4228): #14 PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:765:18)
I/flutter ( 4228): #15 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding.drawFrame (package:flutter/src/rendering/binding.dart:346:19)
I/flutter ( 4228): #16 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:701:13)
I/flutter ( 4228): #17 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:285:5)I/flutter ( 4228): #18 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1016:15)
I/flutter ( 4228): #19 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:958:9)
I/flutter ( 4228): #20 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.scheduleWarmUpFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:784:7)
I/flutter ( 4228): #29 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:382:19)
I/flutter ( 4228): #30 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:416:5)
I/flutter ( 4228): #31 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)
I/flutter ( 4228): (elided 8 frames from package dart:async and package dart:async-patch)
I/flutter ( 4228):
I/flutter ( 4228): The following RenderObject was being processed when the exception was fired: RenderCustomMultiChildLayoutBox#e4ae0 relayoutBoundary=up2 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE:
I/flutter ( 4228): creator: CustomMultiChildLayout ← TimeSeriesChart ← SimpleTimeSeriesChart ← Expanded ← Row ← Column
I/flutter ( 4228): ← [root]
I/flutter ( 4228): parentData: offset=Offset(0.0, 0.0); flex=1; fit=FlexFit.tight (can use size)
I/flutter ( 4228): constraints: BoxConstraints(w=120.0, 0.0<=h<=Infinity)
I/flutter ( 4228): size: Size(120.0, Infinity)
I/flutter ( 4228): This RenderObject had the following descendants (showing up to depth 5):
I/flutter ( 4228): child 1: RenderSemanticsGestureHandler#2034c NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
I/flutter ( 4228): child: RenderPointerListener#aef29 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
I/flutter ( 4228): child: ChartContainerRenderObject<DateTime>#b28fc NEEDS-LAYOUT NEEDS-PAINT
I/flutter ( 4228): ════════════════════════════════════════════════════════════════════════════════════════════════════
```
more on step 8
--------------
* now we know that the error is from the TimeSeriesChart widget because it needs height
* but if it does not have a height it will ask it's parent, the row
* but the row dosnt have a fixed height it will ask the children
* but the children don't have a fixed height it will ask the row parent
* but the parent doesn't have a fixed height for it children (the row) | Just wrap your `Row` in an `Expanded` widget and that's it.
```
Column(
children: <Widget>[
Container(height: 200, color: Colors.orange),
Expanded(
child: Row(
textDirection: TextDirection.ltr,
children: <Widget>[
Container(width: 200,color: Colors.orange),
Expanded(child: SimpleTimeSeriesChart.withSampleData())
],
)
)
],
)
```
Explanation is that the `Column` when created will provide *infinity constraints* to its children and when you wrap any child in a `Flexible` widget, it will act accordingly to the available space (and some of the properties, if any).
The `Row` acts exactly the same way, but horizontally. Here, you are properly adding the `Expanded` to the `Row` child, but then, it tries to find *how much* cant it expand to size itself, and the `Row` doesn't know because it still has an unbounded height from the parent (`Column`), that's why you should use the `Expanded` or even a `Flexible` if you don't need to fit the available space. |
54,801,132 | Why is the label not bold with this setting?
```
<form class="input-group">
<div class="btn-section-operation" id="btn-container-table">
<label for="radio-selection-range-rows" class="radio-custom-label"><input class="radio-custom input-group-field" id="radio-selection-range-rows" name="radio-selection" type="radio" checked="checked">Rows</label>
<label for="radio-selection-range-rel" class="radio-custom-label"><input class="radio-custom input-group-field" id="radio-selection-range-rel" name="radio-selection" type="radio">Rows with relations</label>
</div>
```
[Codepen](https://codepen.io/anon/pen/BMELrp?editors=1100) | 2019/02/21 | [
"https://Stackoverflow.com/questions/54801132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9425549/"
] | You should not use `label:checked`, but `input:checked` for a checked checkbox. Furthermore you use the sibling selector, but the element you want to style is the parent (label is the parent of input). There is no parent selector in CSS, so my solution would be to use a `span` around the text.
```
<label for="radio-selection-range-rows" class="radio-custom-label">
<input class="radio-custom input-group-field" id="radio-selection-range-rows" name="radio-selection" type="radio" checked="checked">
<span>Rows</span>
</label>
```
And then select like this:
```
input:checked ~ span {
border-color: black;
font-weight: bold;
}
```
You could also place the input `outside` the `label` and use other css, but you probably have reasons to do it like this. | Check updated snippet below...
```css
label input:checked + span {
border-color: red;
font-weight: bold;
}
.btn-section-operation {
display: grid;
}
```
```html
<form class="input-group">
<div class="btn-section-operation" id="btn-container-table">
<label for="radio-selection-range-rows" class="radio-custom-label"><input class="radio-custom input-group-field" id="radio-selection-range-rows" name="radio-selection" type="radio" checked="checked"><span>Rows</span></label>
<label for="radio-selection-range-rel" class="radio-custom-label"><input class="radio-custom input-group-field" id="radio-selection-range-rel" name="radio-selection" type="radio"><span>Rows with relations</span></label>
</div>
</form>
``` |
29,585,967 | I want to show program that 3 button in bottom that if we click red button, the panel change color become red, etc.
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LatihanEvent2 implements ActionListener {
private JButton buttonRed = new JButton ("Red");
private JButton buttonGreen = new JButton ("Green");
private JButton buttonBlue = new JButton ("Blue");
public LatihanEvent2() {
JFrame frame = new JFrame("Contoh Event");
frame.setSize(400,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(buttonRed, BorderLayout.WEST);
panel.add(buttonGreen, BorderLayout.CENTER);
panel.add(buttonBlue, BorderLayout.EAST);
//Inner Class
ListenerRed clickListener = new ListenerRed();
buttonRed.addActionListener(clickListener);
//Anonymous Class
buttonGreen.addActionListener(new ActionListener () {
public void actionPerformed (ActionEvent e) {
buttonGreen.setBackground(Color.GREEN);
}
});
//Derived Class
buttonBlue.addActionListener(this); //Step 2
frame.add(panel, BorderLayout.SOUTH);
frame.setVisible(true);
frame.show();
}
public static void main (String[] args) {
new LatihanEvent2();
}
//Inner Class
class ListenerRed implements ActionListener {
public void actionPerformed (ActionEvent e) {
buttonRed.setBackground(Color.RED);
}
}
//Derived Class
public void actionPerformed (ActionEvent e) {
buttonBlue.setBackground(Color.BLUE);
}
}
```
In my coding there was 3 method. Inner class, Anonymous Class, and Derived Class. How to make the panel change color background with this different method? Help me please | 2015/04/12 | [
"https://Stackoverflow.com/questions/29585967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3414583/"
] | This example adds a second panel (`ui`) to which each action sets the background. See comments in code for further tips.
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
public class LatihanEvent2 implements ActionListener {
private JButton buttonRed = new JButton("Red");
private JButton buttonGreen = new JButton("Green");
private JButton buttonBlue = new JButton("Blue");
JPanel ui = new JPanel(new BorderLayout(5, 5));
public LatihanEvent2() {
JFrame frame = new JFrame("Contoh Event");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// quick and dirty way to provide space in a GUI
ui.add(new JLabel(new ImageIcon(
new BufferedImage(300, 300, BufferedImage.TYPE_INT_ARGB))));
JPanel panel = new JPanel();
// border layout constraints are irrelevant to a flow layout!
//ui.add(buttonRed, BorderLayout.WEST);
panel.add(buttonRed);
panel.add(buttonGreen);
panel.add(buttonBlue);
//Inner Class
ListenerRed clickListener = new ListenerRed();
buttonRed.addActionListener(clickListener);
//Anonymous Class
buttonGreen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ui.setBackground(Color.GREEN);
}
});
//Derived Class
buttonBlue.addActionListener(this); //Step 2
ui.add(panel, BorderLayout.PAGE_END);
frame.setContentPane(ui);
frame.pack();
//frame.show(); // Deprecated!
frame.setVisible(true); // should be last..
}
public static void main(String[] args) {
// The GUI should be created and updated on the EDT. E.G.
Runnable r = new Runnable() {
@Override
public void run() {
new LatihanEvent2();
}
};
// Here is the iomportant part of actually
// starting that runnable on the EDT..
SwingUtilities.invokeLater(r);
}
//Inner Class
class ListenerRed implements ActionListener {
public void actionPerformed(ActionEvent e) {
ui.setBackground(Color.RED);
}
}
//Derived Class
public void actionPerformed(ActionEvent e) {
ui.setBackground(Color.BLUE);
}
}
``` | ```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LatihanEvent2 implements ActionListener {
private JButton buttonRed = new JButton("Red");
private JButton buttonGreen = new JButton("Green");
private JButton buttonBlue = new JButton("Blue");
JPanel panel = new JPanel();
public LatihanEvent2() {
JFrame frame = new JFrame("Contoh Event");
panel.add(buttonRed, BorderLayout.WEST);
panel.add(buttonGreen, BorderLayout.CENTER);
panel.add(buttonBlue, BorderLayout.EAST);
frame.add(panel, BorderLayout.SOUTH);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
buttonRed.addActionListener(this);
buttonGreen.addActionListener(this);
buttonBlue.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String btnName = e.getActionCommand();
if(btnName.equalsIgnoreCase("red")) {
panel.setBackground(Color.red);
}
else if(btnName.equalsIgnoreCase("green")) {
panel.setBackground(Color.green);
}
else {
panel.setBackground(Color.blue);
}
}
public static void main(String[] args) {
new LatihanEvent2();
}
}
``` |
29,585,967 | I want to show program that 3 button in bottom that if we click red button, the panel change color become red, etc.
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LatihanEvent2 implements ActionListener {
private JButton buttonRed = new JButton ("Red");
private JButton buttonGreen = new JButton ("Green");
private JButton buttonBlue = new JButton ("Blue");
public LatihanEvent2() {
JFrame frame = new JFrame("Contoh Event");
frame.setSize(400,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(buttonRed, BorderLayout.WEST);
panel.add(buttonGreen, BorderLayout.CENTER);
panel.add(buttonBlue, BorderLayout.EAST);
//Inner Class
ListenerRed clickListener = new ListenerRed();
buttonRed.addActionListener(clickListener);
//Anonymous Class
buttonGreen.addActionListener(new ActionListener () {
public void actionPerformed (ActionEvent e) {
buttonGreen.setBackground(Color.GREEN);
}
});
//Derived Class
buttonBlue.addActionListener(this); //Step 2
frame.add(panel, BorderLayout.SOUTH);
frame.setVisible(true);
frame.show();
}
public static void main (String[] args) {
new LatihanEvent2();
}
//Inner Class
class ListenerRed implements ActionListener {
public void actionPerformed (ActionEvent e) {
buttonRed.setBackground(Color.RED);
}
}
//Derived Class
public void actionPerformed (ActionEvent e) {
buttonBlue.setBackground(Color.BLUE);
}
}
```
In my coding there was 3 method. Inner class, Anonymous Class, and Derived Class. How to make the panel change color background with this different method? Help me please | 2015/04/12 | [
"https://Stackoverflow.com/questions/29585967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3414583/"
] | ```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LatihanEvent2 implements ActionListener {
private JButton buttonRed = new JButton("Red");
private JButton buttonGreen = new JButton("Green");
private JButton buttonBlue = new JButton("Blue");
JPanel panel = new JPanel();
public LatihanEvent2() {
JFrame frame = new JFrame("Contoh Event");
panel.add(buttonRed, BorderLayout.WEST);
panel.add(buttonGreen, BorderLayout.CENTER);
panel.add(buttonBlue, BorderLayout.EAST);
frame.add(panel, BorderLayout.SOUTH);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
buttonRed.addActionListener(this);
buttonGreen.addActionListener(this);
buttonBlue.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String btnName = e.getActionCommand();
if(btnName.equalsIgnoreCase("red")) {
panel.setBackground(Color.red);
}
else if(btnName.equalsIgnoreCase("green")) {
panel.setBackground(Color.green);
}
else {
panel.setBackground(Color.blue);
}
}
public static void main(String[] args) {
new LatihanEvent2();
}
}
``` | In more simple way, we can do it as:
(after seeing your requirements)
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LatihanEvent2 implements ActionListener {
private JButton buttonRed = new JButton("Red");
private JButton buttonGreen = new JButton("Green");
private JButton buttonBlue = new JButton("Blue");
JFrame frame = new JFrame("Contoh Event");
JPanel panelDown = new JPanel();
JPanel panelUp = new JPanel();
public LatihanEvent2() {
panelDown.add(buttonRed, BorderLayout.WEST);
panelDown.add(buttonGreen, BorderLayout.CENTER);
panelDown.add(buttonBlue, BorderLayout.EAST);
frame.add(panelDown, BorderLayout.SOUTH);
frame.add(panelUp, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
buttonRed.addActionListener(this);
buttonGreen.addActionListener(this);
buttonBlue.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String btnName = e.getActionCommand();
if(btnName.equalsIgnoreCase("red")) {
panelUp.setBackground(Color.red);
}
else if(btnName.equalsIgnoreCase("green")) {
panelUp.setBackground(Color.green);
}
else {
panelUp.setBackground(Color.blue);
}
}
public static void main(String[] args) {
new LatihanEvent2();
}
}
``` |
29,585,967 | I want to show program that 3 button in bottom that if we click red button, the panel change color become red, etc.
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LatihanEvent2 implements ActionListener {
private JButton buttonRed = new JButton ("Red");
private JButton buttonGreen = new JButton ("Green");
private JButton buttonBlue = new JButton ("Blue");
public LatihanEvent2() {
JFrame frame = new JFrame("Contoh Event");
frame.setSize(400,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(buttonRed, BorderLayout.WEST);
panel.add(buttonGreen, BorderLayout.CENTER);
panel.add(buttonBlue, BorderLayout.EAST);
//Inner Class
ListenerRed clickListener = new ListenerRed();
buttonRed.addActionListener(clickListener);
//Anonymous Class
buttonGreen.addActionListener(new ActionListener () {
public void actionPerformed (ActionEvent e) {
buttonGreen.setBackground(Color.GREEN);
}
});
//Derived Class
buttonBlue.addActionListener(this); //Step 2
frame.add(panel, BorderLayout.SOUTH);
frame.setVisible(true);
frame.show();
}
public static void main (String[] args) {
new LatihanEvent2();
}
//Inner Class
class ListenerRed implements ActionListener {
public void actionPerformed (ActionEvent e) {
buttonRed.setBackground(Color.RED);
}
}
//Derived Class
public void actionPerformed (ActionEvent e) {
buttonBlue.setBackground(Color.BLUE);
}
}
```
In my coding there was 3 method. Inner class, Anonymous Class, and Derived Class. How to make the panel change color background with this different method? Help me please | 2015/04/12 | [
"https://Stackoverflow.com/questions/29585967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3414583/"
] | This example adds a second panel (`ui`) to which each action sets the background. See comments in code for further tips.
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
public class LatihanEvent2 implements ActionListener {
private JButton buttonRed = new JButton("Red");
private JButton buttonGreen = new JButton("Green");
private JButton buttonBlue = new JButton("Blue");
JPanel ui = new JPanel(new BorderLayout(5, 5));
public LatihanEvent2() {
JFrame frame = new JFrame("Contoh Event");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// quick and dirty way to provide space in a GUI
ui.add(new JLabel(new ImageIcon(
new BufferedImage(300, 300, BufferedImage.TYPE_INT_ARGB))));
JPanel panel = new JPanel();
// border layout constraints are irrelevant to a flow layout!
//ui.add(buttonRed, BorderLayout.WEST);
panel.add(buttonRed);
panel.add(buttonGreen);
panel.add(buttonBlue);
//Inner Class
ListenerRed clickListener = new ListenerRed();
buttonRed.addActionListener(clickListener);
//Anonymous Class
buttonGreen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ui.setBackground(Color.GREEN);
}
});
//Derived Class
buttonBlue.addActionListener(this); //Step 2
ui.add(panel, BorderLayout.PAGE_END);
frame.setContentPane(ui);
frame.pack();
//frame.show(); // Deprecated!
frame.setVisible(true); // should be last..
}
public static void main(String[] args) {
// The GUI should be created and updated on the EDT. E.G.
Runnable r = new Runnable() {
@Override
public void run() {
new LatihanEvent2();
}
};
// Here is the iomportant part of actually
// starting that runnable on the EDT..
SwingUtilities.invokeLater(r);
}
//Inner Class
class ListenerRed implements ActionListener {
public void actionPerformed(ActionEvent e) {
ui.setBackground(Color.RED);
}
}
//Derived Class
public void actionPerformed(ActionEvent e) {
ui.setBackground(Color.BLUE);
}
}
``` | In more simple way, we can do it as:
(after seeing your requirements)
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LatihanEvent2 implements ActionListener {
private JButton buttonRed = new JButton("Red");
private JButton buttonGreen = new JButton("Green");
private JButton buttonBlue = new JButton("Blue");
JFrame frame = new JFrame("Contoh Event");
JPanel panelDown = new JPanel();
JPanel panelUp = new JPanel();
public LatihanEvent2() {
panelDown.add(buttonRed, BorderLayout.WEST);
panelDown.add(buttonGreen, BorderLayout.CENTER);
panelDown.add(buttonBlue, BorderLayout.EAST);
frame.add(panelDown, BorderLayout.SOUTH);
frame.add(panelUp, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
buttonRed.addActionListener(this);
buttonGreen.addActionListener(this);
buttonBlue.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String btnName = e.getActionCommand();
if(btnName.equalsIgnoreCase("red")) {
panelUp.setBackground(Color.red);
}
else if(btnName.equalsIgnoreCase("green")) {
panelUp.setBackground(Color.green);
}
else {
panelUp.setBackground(Color.blue);
}
}
public static void main(String[] args) {
new LatihanEvent2();
}
}
``` |
113,104 | Consider the sentence
>
> E-books are on the rise, but they haven't suppressed paper books though.
>
>
>
This usage seems to be quite common, but when I learned English I was taught to use "however" where I now read "though".
My questions on this use of "though" are:
Is this a new trend?
Is it restricted to American English?
Is "though" considered more colloquial than "however" ?
And on a syntactic level:
Do you put a comma before "though"? | 2013/05/03 | [
"https://english.stackexchange.com/questions/113104",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/8345/"
] | I thought it might be sensible to list the various acceptable alternatives:
>
> E-books are on the rise, but they haven't yet totally eliminated the
> demand for paper books.
>
>
> (Al)though E-books are on the rise, they haven't yet totally
> eliminated the demand for paper books.
>
>
> E-books are on the rise, (al)though they haven't yet totally
> eliminated the demand for paper books.
>
>
> E-books are on the rise; they haven't yet totally eliminated the
> demand for paper books, though.
>
>
> E-books are on the rise; however, they haven't yet totally eliminated
> the demand for paper books.
>
>
> E-books are on the rise; they haven't yet, however, totally eliminated the
> demand for paper books.
>
>
> E-books are on the rise; they haven't yet totally eliminated the
> demand for paper books, however.
>
>
> | The only reasonable answer to this question is that you must **DELETE** \**though*\* because it doesn't belong there: it duplicates the function of **but**. *However* would be equally ungrammatical in the sentence:
>
> E-books are on the rise, **but** they haven't suppressed paper books, **however**.
>
>
>
This sentence is grammatically incorrect.
It's not a new trend. EFL students have been doing it for eons. It's not just an American solecism. All native Anglophones have been infected by the Solecism iVirus (*"i"* for *ignorance*). It's endemic and epidemic wherever English speakers gather.
On a syntactic level:
>
> **Put a period before "though" and then erase "though"**.
>
>
>
*Common* = *vulgar, crude, rude, inferior, low-grade, mean, poor, second-class, second-rate, shoddy*. |
113,104 | Consider the sentence
>
> E-books are on the rise, but they haven't suppressed paper books though.
>
>
>
This usage seems to be quite common, but when I learned English I was taught to use "however" where I now read "though".
My questions on this use of "though" are:
Is this a new trend?
Is it restricted to American English?
Is "though" considered more colloquial than "however" ?
And on a syntactic level:
Do you put a comma before "though"? | 2013/05/03 | [
"https://english.stackexchange.com/questions/113104",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/8345/"
] | You probably shouldn't use both *but* and *though* together like that, because you're saying the same thing twice; both words mark the clause as antithetical to what came before. So you should **remove one or the other**.
If you decide to use *though*, you **need a comma** before it.
---
I don't know whether it is new; it's just incorrect.
I don't think it is related to American English; I would simply interpret it as a typo, not as a conscious choice.
Both *though* and *however* are a bit informal at the end; *though* is better.
The position of *however* in formal prose is rather at the beginning of a sentence, or after the first constituent. | The only reasonable answer to this question is that you must **DELETE** \**though*\* because it doesn't belong there: it duplicates the function of **but**. *However* would be equally ungrammatical in the sentence:
>
> E-books are on the rise, **but** they haven't suppressed paper books, **however**.
>
>
>
This sentence is grammatically incorrect.
It's not a new trend. EFL students have been doing it for eons. It's not just an American solecism. All native Anglophones have been infected by the Solecism iVirus (*"i"* for *ignorance*). It's endemic and epidemic wherever English speakers gather.
On a syntactic level:
>
> **Put a period before "though" and then erase "though"**.
>
>
>
*Common* = *vulgar, crude, rude, inferior, low-grade, mean, poor, second-class, second-rate, shoddy*. |
113,104 | Consider the sentence
>
> E-books are on the rise, but they haven't suppressed paper books though.
>
>
>
This usage seems to be quite common, but when I learned English I was taught to use "however" where I now read "though".
My questions on this use of "though" are:
Is this a new trend?
Is it restricted to American English?
Is "though" considered more colloquial than "however" ?
And on a syntactic level:
Do you put a comma before "though"? | 2013/05/03 | [
"https://english.stackexchange.com/questions/113104",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/8345/"
] | You probably shouldn't use both *but* and *though* together like that, because you're saying the same thing twice; both words mark the clause as antithetical to what came before. So you should **remove one or the other**.
If you decide to use *though*, you **need a comma** before it.
---
I don't know whether it is new; it's just incorrect.
I don't think it is related to American English; I would simply interpret it as a typo, not as a conscious choice.
Both *though* and *however* are a bit informal at the end; *though* is better.
The position of *however* in formal prose is rather at the beginning of a sentence, or after the first constituent. | I thought it might be sensible to list the various acceptable alternatives:
>
> E-books are on the rise, but they haven't yet totally eliminated the
> demand for paper books.
>
>
> (Al)though E-books are on the rise, they haven't yet totally
> eliminated the demand for paper books.
>
>
> E-books are on the rise, (al)though they haven't yet totally
> eliminated the demand for paper books.
>
>
> E-books are on the rise; they haven't yet totally eliminated the
> demand for paper books, though.
>
>
> E-books are on the rise; however, they haven't yet totally eliminated
> the demand for paper books.
>
>
> E-books are on the rise; they haven't yet, however, totally eliminated the
> demand for paper books.
>
>
> E-books are on the rise; they haven't yet totally eliminated the
> demand for paper books, however.
>
>
> |
49,849,266 | How to add background image on top layout the one who has back button . ive tried adding imageview on it using the drag and drop but image is hiding on the back. Anyone has an idea? Thanks
[](https://i.stack.imgur.com/xMNeP.png) | 2018/04/16 | [
"https://Stackoverflow.com/questions/49849266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If you cannot set the `editor.formatOnPaste` to `true`. Then use the following key combination to manually format/ indent `Alt+Shift+F` | I know you said this didnt worked for you, but it did work for me and it may help others i think it worth mentioning:
This worked for me: Go to VS Code Settings -> from the User Settings tab -> Text Editor -> Formatting -> Untick the first option 'Format On Paste' |
49,849,266 | How to add background image on top layout the one who has back button . ive tried adding imageview on it using the drag and drop but image is hiding on the back. Anyone has an idea? Thanks
[](https://i.stack.imgur.com/xMNeP.png) | 2018/04/16 | [
"https://Stackoverflow.com/questions/49849266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If you cannot set the `editor.formatOnPaste` to `true`. Then use the following key combination to manually format/ indent `Alt+Shift+F` | Since your settings aren't working as desired, one good way to handle this behavior is to highlight the text and press `tab`. This will increase indentation on all lines. You can repeat to get to your desired indentation level. |
49,849,266 | How to add background image on top layout the one who has back button . ive tried adding imageview on it using the drag and drop but image is hiding on the back. Anyone has an idea? Thanks
[](https://i.stack.imgur.com/xMNeP.png) | 2018/04/16 | [
"https://Stackoverflow.com/questions/49849266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I know you said this didnt worked for you, but it did work for me and it may help others i think it worth mentioning:
This worked for me: Go to VS Code Settings -> from the User Settings tab -> Text Editor -> Formatting -> Untick the first option 'Format On Paste' | Since your settings aren't working as desired, one good way to handle this behavior is to highlight the text and press `tab`. This will increase indentation on all lines. You can repeat to get to your desired indentation level. |
1,266,279 | So recently I've been tweaking my computer's registry for its Memory Management. I know its a bad thing to do to edit your registry without knowing what it may cause to your system but i've only touched a specific registry value which is the `SecondLevelDataCache` in `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management`
I've "accidentally" set its value to 512 Hexadecimal(1298 decimal) instead of 512 Decimal. My CPU's L2 Cache can only do 2x256 KB(Intel I3 2nd Gen 2330M).
So far I've seen faster responses from the system when I set it on 512 Hexa.
Not only that, I've also tried playing games and running applications and also observed better performance from them overall.
And now my question is, what might be a problem later on for this setting if I left it on? What might it cause to my hardware/OS if it were to be left like that that? | 2017/11/07 | [
"https://superuser.com/questions/1266279",
"https://superuser.com",
"https://superuser.com/users/812816/"
] | According to [canonical source](https://technet.microsoft.com/en-us/library/cc938581.aspx), the `SecondLevelDataCache` entry has no effect on performance. As a computer science bachelor I'm aware that modern CPU caches are invisible (transparent) to operating systems, optimizing RAM access automatically.
You may never know if you have really observed a performance "boost". Have you run any benchmarks and compared the result?
Nevertheless, keeping your modified value of `SecondLevelDataCache` probably does no harm to your hardware and user experience. | Windows will use the value here IF it cannot resolve the L2 cache size from the HAL (Hardware Abstraction Layer). Windows CAN get this value through HAL 99.9% of the time. If it can't, the default value of 0 will result in Windows thinking the L2 cache is only 256K. IF Task Manager (performance tab) shows L2 as "0", THEN this tweak is invalid. IF Windows didn't care about the L2 size, this registry entry wouldn't exist. |
86,694 | The Scottish Claim of Right makes clear that the people of Scotland are Sovereign, not Westminster.
However, under the rest of UK law, Westminster/Parliament is Sovereign.
Given the Supreme Court has ruled that the Scottish Parliament can't hold a referrendum on Scottish Independence without Westminster's permission, could the Scottish Government choose to overrule this (or at least attempt to) by asserting the Claim of Right?
I assume I'm misunderstanding something here, because this isn't a route I've heard anyone suggest and I don't expect something this obvious would have been missed.
So what am I missing here? | 2022/11/28 | [
"https://law.stackexchange.com/questions/86694",
"https://law.stackexchange.com",
"https://law.stackexchange.com/users/21707/"
] | >
> The Scottish Claim of Right makes clear that the people of Scotland are Sovereign, not Westminster.
>
>
>
Not so much. It establishes principles of parliamentary monarchy... (for example)
>
> That the chargeing of the leidges with lawborrowes at the Kings instance and the imposeing of bonds without the authority of Parliament and the suspending advocats from their Imployment for not Compearing when such bonds were offered were Contrary to Law
>
>
> That the putting of Garisones on privat mens houses in tyme of peace without their Consent or the authority of Parliament is Contrary to law
>
>
>
...while inviting William and Mary to accede to the Scottish throne:
>
> The said Estates of the Kingdome of Scotland Doe resolve that William and Mary King and Queen of England France and Ireland Be and be Declared King and Queen of Scotland To hold the Crowne and Royall Dignity of the said Kingdome of Scotland To them the said King and Queen dureing ther lives and the longest liver of them and that the sole and full exercise of the regall power be only in and Exercised by him the said King in the names of the said King and Queen Dureing ther joynt lives And after ther decease The said Croune and Royall Dignity of the said Kingdome to be to the heirs of the body of the said Queen which failing to the Princess Ann of Denmark and the airs of her body which also failing to the aires of the Body of the said William King of England
>
>
> And they do Pray the said King and Queen of England to accept the same accordingly
>
>
> ...
>
>
> That for redress of all greivances and for the amending strenthneing and preserveing of the lawes Parliaments ought to be frequently called and allowed to sit and the freedom of speech and debate secured to the members
>
>
>
In other words, it provides that the monarchy is not absolute, and that its power is circumscribed by parliament.
One thing it certainly does not do is circumscribe the power of the Westminster parliament, which had no power in Scotland before the Acts of Union of 1707. Before then, the Westminster parliament was only the Parliament of England. The Acts of Union provided, in part,
>
> That the United Kingdom of Great Britain be Represented by one and the same Parliament to be stiled the Parliament of Great Britain
>
>
>
With that act, the Parliament of Great Britain assumed the role of the Parliament of Scotland. As a consequence, the Claim of Right Act of 1689 *grants power to* the Westminster parliament rather than circumscribing its power. To the extent the people are sovereign, this sovereignty is vested in their representatives in Westminster.
On the other hand, if you're talking about [the 1989 claim](https://en.wikipedia.org/wiki/Claim_of_Right_1989), that document
>
> has never had or claimed any legal force.
>
>
> | The 1989 Claim of Right cannot be used by the Scottish Government to hold another referendum on independence for the same reasons that the Scottish Government cannot do so under the Scotland Act 1998: they (and by extension, the Scottish Parliament) lack the competence to do so.
This was decided by the UK Supreme Court in [*Devolution issues under the Scotland Act 1998, Reference by the Lord Advocate (Rev1)* [2022] UKSC 31](https://www.supremecourt.uk/cases/uksc-2022-0098.html) where the Court held (at 77-82) that a proposed referendum on independence would concern a reserved matter: namely, the Union of Scotland and England. A reserved matter is exclusively within the competence of the United Kingdom Parliament unless it chooses to devolve or delegate some or all of the matter to one of the devolved parliaments.
In this case, [Section 29 of the Scotland Act 1998](https://www.legislation.gov.uk/ukpga/1998/46/section/29) states:
>
> (1) An Act of the Scottish Parliament is not law so far as any
> provision of the Act is outside the legislative competence of the
> Parliament.
>
>
> (2) A provision is outside that competence so far as any of the
> following paragraphs apply—
>
>
> ...
>
>
> (b) it relates to reserved matters
>
>
>
where a reserved matter is defined in [Schedule 5, Part 1, Section 1 of the Scotland Act 1998](https://www.legislation.gov.uk/ukpga/1998/46/schedule/5) as including, amongst other things:
>
> The following aspects of the constitution are reserved matters, that
> is—
>
>
> ...
>
>
> (b) the Union of the Kingdoms of Scotland and England
>
>
>
In the *Devolution (Rev1)* case, the Supreme Court held (at 92) that the proposed independence referendum question related to a reserved matter and so was outwith the Scottish Parliament's competence.
The Supreme Court also considered the principle of self-determination as established in international law, which is relevant to the matter at the heart of the Claim of Right. Namely, that the people of Scotland are sovereign and have the right to determine their own independence and so on.
The Court held (at 88-89) that self-determination was expected to occur within the existing framework of the state, per the Supreme Court of Canada in *Reference re Secession of Quebec* [1998] 2 SCR 217 and UN opinion on the matter of Kosovo in Written Proceedings in relation to UN General Assembly Resolution 63/3 (A/RES/63/3) (8 October 2008).
>
> 88. In its judgment the Supreme Court explained (at paras 136-137) that Canada was a sovereign and independent state conducting itself in compliance with the principle of equal rights and self-determination of peoples and thus possessed of a government representing the whole people belonging to the territory without distinction. It considered that the then current constitutional arrangements within Canada did not place Quebecers in a disadvantaged position within the scope of the international law rule. It continued:
>
>
> “In summary, the international law right to self-determination only generates, at best, a right to external self-determination in situations of former colonies; where a people is oppressed, as for example under foreign military occupation; or where a definable group is denied meaningful access to government to pursue their political, economic, social and cultural development. In all three situations, the people in question are entitled to a right to external self-determination because they have been denied the ability to exert internally their right to self-determination. Such exceptional circumstances are manifestly inapplicable to Quebec under existing conditions.” (at para 138)
>
>
> It went on to say that in other circumstances peoples were expected to
> achieve self-determination within the framework of their existing
> state:
>
>
> “A state whose government represents the whole of the people or
> peoples resident within its territory, on a basis of equality and
> without discrimination, and respects the principles of
> self-determination in its internal arrangements, is entitled to
> maintain its territorial integrity under international law and to have
> that territorial integrity recognized by other states. Quebec does not
> meet the threshold of a colonial people or an oppressed people, nor
> can it be suggested that Quebecers have been denied
> meaningful access to government to pursue their political, economic,
> cultural and social development. In the circumstances, the National
> Assembly, the legislature or the government of Quebec do not enjoy a
> right at international law to effect the secession of Quebec from
> Canada unilaterally.” (at para 154)
>
>
> 89. In our view these observations apply with equal force to the position
> of Scotland and the people of Scotland within the United Kingdom. ... The submission went on to state that international law does not, in general, prohibit secession; but the relevant point, in relation to the intervener’s submission based on a right of self-determination under international law, is the absence of recognition of any such right outside the contexts described by the Supreme Court of Canada, none of which applies to Scotland.
>
>
>
On this basis, the Claim of Right 1989 is doomed to fail because any self-determination has to operate within the existing framework of the United Kingdom's political hiercharcy and constitution, and the Supreme Court has made it clear that the Union is a reserved matter, so the United Kingdom Parliament must give explicit permission for any proposed Bill or legal mechanism that affects that. |
14,492,225 | I wrote the following codes in order to make element which has id=sample grayscale(0.6) and blur(5px). But it turns out that the latter -webkit-filter property substitutes for the previous one instead of appending to it. I can only add one -webkit-filter property every time. Is it possible to append the blur to grayscale? Just make clear that I am using latest chrome, so -webkit-filter works on my navigator.
```
$('#grayscale').click(function() {
$('#sample').css({"-webkit-filter" : "grayscale(0.6)"})
});
$('#blur').click(function() {
$('#sample').css({"-webkit-filter" : "blur(5px)"})
});
``` | 2013/01/24 | [
"https://Stackoverflow.com/questions/14492225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1605763/"
] | `master`, like `origin` or `upstream`, is a convention, not a requirement. Since you have no commits in `master`, you have no refs for it either. `HEAD` is pointing to a ref that does not yet exist. When you run `git checkout -b branch`, you ask git to:
1. Duplicate the ref your `HEAD` points to.
2. Point your `HEAD` to the new ref.
Since your `HEAD` points to a nonexistent ref, you duplicate nothing and end up still pointing to nothing. As long as you continue to switch branches without committing, this will be the case.
Once you've made your first commit everything changes. Now that you've made a commit, you have a ref for your current `HEAD` to point to. The next time you create a branch, there's a ref to duplicate, so the branch won't disappear next time you switch.
Example(ish):
```
git init
touch test
git add test
# There are no refs at this point, but HEAD is pointing to the nonexistent refs/heads/master
git checkout -b new_branch
git checkout master # fails, no refs (for master)
git checkout -b new_branch2
git checkout new_branch # fails, no refs (for new_branch)
git commit -m "Initial commit."
# Now you have a ref for new_branch2, but not yet for any other branches.
git checkout -b new_branch3 # new_branch2's ref is duplicated
git checkout new_branch2 # success, you made a commit in this branch so it has a ref
git checkout new_branch3 # success, you made a commit in new_branch2 which this branch's ref is also pointing to.
git checkout master # failure, until you run with '-b' master doesn't have any refs yet.
``` | It didn't work for me initially...
```
durrantm.../play$ mkdir ggg
durrantm.../play$ cd ggg
durrantm.../ggg$ git init
Initialized empty Git repository in /home/durrantm/play/ggg/.git/
durrantm.../ggg$ git checkout -b newy
fatal: You are on a branch yet to be born
```
...until yes, I did an initial commit on master:
```
durrantm.../ggg$ vi x.x
durrantm.../ggg$ git add .
durrantm.../ggg$ git commit -m"Initial Commit"
[master (root-commit) 75bcf19] Initial Commit
0 files changed, 0 insertions(+), 0 deletions(-)
create mode 100644 x.x
durrantm.../ggg$ git checkout -b abc
Switched to a new branch 'abc'
durrantm.../ggg$
``` |
35,345,808 | Below command only gives channel list .
```
127.0.0.1:6379> PUBSUB CHANNELS
1) "mychannel"
2) "mychanne2"
```
**How to LIST subscribers subscribed on channel1 OR channel2 .?**
also
i din't found redis command to list all subscribers Of a particular channel | 2016/02/11 | [
"https://Stackoverflow.com/questions/35345808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3523101/"
] | You can use `PUBSUB NUMSUB channel1` OR `PUBSUB NUMSUB channel2` and get reply about the number of subscribers for the specified channel. | I can achieve this with something like:
```
redis_client.multi().client(['list']).exec(function(err, results) {
var pairs = results[0].split(' ');
pairs.forEach(function(pair){
var kv = pair.split('=');
if (kv[0] == 'name' && kv[1] == constants.REDIS_SUBSCRIBER_NAME)
found = true;
});
if (found) // some logic
else // some logic
});
``` |
40,136,198 | I am trying to make a heat map of the US, the code "works" but the data won't populate into a US map - only the names of the states show up - which I also want to populate, but the actual map of the US is most important.
Here's my code:
#read in my data
rawdata\_path <- c("~/R/heatdata.xlsx")
```
# Import the data into RStudio:
rawdata <- readxl::read_excel(rawdata_path, sheet = 1, col_names = TRUE)
#clean up the data
rawdata$Lattitude <- as.numeric(rawdata$Lattitude)
rawdata$Longitude <- as.numeric(rawdata$Longitude)
#plot the data
library(ggplot2)
library(maps)
ggplot(rawdata, aes(x=Longitude, y = Lattitude, group = rawdata$State))+
geom_polygon(aes(fill=FinalCount))+
geom_path()+
geom_text(data = rawdata, aes(x=Longitude, y = Lattitude, label = State))+
scale_fill_gradientn(colours = rev(heat.colors(10)), na.value = "grey90")+
coord_map()
```
---
This is what the head of data frame called, rawdata looks like, I want the states to populate by the Count column - 1 being lightest and 10 being dark red:
```
State Count Group Lattitude Longitude Rev
<chr> <dbl> <dbl> <dbl> <dbl> <dbl>
arizona 1.0 1 33.50000 -112.05000 0.0
arkansas 1.0 2 36.36000 -94.20000 0.0
georgia 1.0 3 33.82000 -84.32000 0.0
hawaii 1.0 4 21.30000 -157.85000 0.0
kansas 1.0 5 38.97167 -95.23525 0.0
maryland 1.0 6 38.98000 -77.08000 0.0
missouri 1.0 7 39.09000 -94.58000 0.0
oregon 1.0 8 45.51000 -122.68000 0.0
pennsylvania 1.0 9 40.43000 -79.97000 0.0
rhode island 1.0 10 41.82000 -71.41000 0.0
tennessee 1.0 11 35.10000 -90.00000 0.0
texas 1.0 12 29.76043 -95.36980 0.0
louisiana 2.1 13 30.44000 -91.12000 209250.0
indiana 2.3 14 38.30000 -85.72000 231605.9
oklahoma 2.7 15 35.22000 -97.34000 274377.9
michigan 3.8 16 42.73000 -84.48000 381528.5
florida 4.9 17 30.43826 -84.28073 498338.5
california 5.1 18 34.06000 -118.24000 511472.0
illinois 5.3 19 41.83000 -87.68000 537913.5
kentucky 5.7 20 38.22000 -85.74000 562077.0
new york 6.3 21 40.75000 -73.99000 630642.8
massachusetts 9.5 22 42.33038 -71.16619 908952.0
north carolina 10.0 23 36.07000 -79.82000 1571923.8
```
Can anyone help me on this? | 2016/10/19 | [
"https://Stackoverflow.com/questions/40136198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7043147/"
] | If you are trying to produce a choropleth map with this data, it is pretty easy with `choroplethr`. First you need to rename your states column as "region" and count column as "value"
So input data looks like:
```
df <- structure(list(region = structure(c(1L, 2L, 5L, 6L, 9L, 12L,
15L, 19L, 20L, 21L, 22L, 23L, 11L, 8L, 18L, 14L, 4L, 3L, 7L,
10L, 16L, 13L, 17L), .Label = c("arizona", "arkansas", "california",
"florida", "georgia", "hawaii", "illinois", "indiana", "kansas",
"kentucky", "louisiana", "maryland", "massachusetts", "michigan",
"missouri", "new york", "north carolina", "oklahoma", "oregon",
"pennsylvania", "rhode island", "tennessee", "texas"), class = "factor"),
value = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2.1, 2.3, 2.7,
3.8, 4.9, 5.1, 5.3, 5.7, 6.3, 9.5, 10), Group = 1:23), .Names = c("region",
"value", "Group"), class = "data.frame", row.names = c(NA, -23L
))
```
The script is pretty simple:
```
library(ggplot2)
library(choroplethr)
choro <- state_choropleth(df) + scale_fill_brewer(palette = "Reds")
choro
```
[](https://i.stack.imgur.com/xfbvw.png) | The following code will load and plot a map of the United States with the coordinates and text from 'rawdata':
```
# Load the data
rawdata_path <- 'C:/data.xlsx'
rawdata <- readxl::read_excel(rawdata_path, sheet = 1, col_names = TRUE)
#clean up the data
rawdata$Lattitude <- as.numeric(rawdata$Lattitude)
rawdata$Longitude <- as.numeric(rawdata$Longitude)
library(ggplot2)
library(maps)
# Load the map of the United State
all_states <- map_data("state")
ggplot() +
geom_polygon( data=all_states, aes(x=long, y=lat, group = group),
colour="white", fill="blue" ) +
geom_point(data=rawdata,
aes(x=Longitude, y=Lattitude, colour='red', size=Count),
alpha=I(0.5)) +
geom_text(data = rawdata, aes(x=Longitude, y = Lattitude, label = State)) +
scale_fill_gradientn(colours = rev(heat.colors(10)), na.value = "grey90")
```
Running it gives this map:
[](https://i.stack.imgur.com/QnAnt.png) |
700 | I was looking into the factorial function in an R package called gregmisc and came across the implementation of the gamma function, instead of a recursive or iterative process as I was expecting. The gamma function is defined as:
$$ \Gamma(z)=\int\_{0}^{\infty}e^{-t}t^{z-1}dt $$
A brief history of the function points to Euler's solution to the factorial problem for non-integers (although the equation above is not his). It has some application in physics and I was curious if it is useful to any quant models, apart from being a fancy factorial calculator. | 2011/03/12 | [
"https://quant.stackexchange.com/questions/700",
"https://quant.stackexchange.com",
"https://quant.stackexchange.com/users/291/"
] | In certain cases some stochastic differential equations(SDE's) have closed form(deterministic) solutions in the form of well known ordinary differential equations (ODE's), partial differential equations(PDE's), and special functions like the gamma function.
Here's an example from a paper where an SDE has a closed form solution in terms of the gamma function:
<http://www.siam.org/books/dc13/DC13samplechpt.pdf>
Solving SDE's (preferably quickly), like with a closed form solution (when one is available), is a core activity in quantitative finance. | Gamma distributions are being used to model the default rate of credit portfolios by CreditRisk. |
700 | I was looking into the factorial function in an R package called gregmisc and came across the implementation of the gamma function, instead of a recursive or iterative process as I was expecting. The gamma function is defined as:
$$ \Gamma(z)=\int\_{0}^{\infty}e^{-t}t^{z-1}dt $$
A brief history of the function points to Euler's solution to the factorial problem for non-integers (although the equation above is not his). It has some application in physics and I was curious if it is useful to any quant models, apart from being a fancy factorial calculator. | 2011/03/12 | [
"https://quant.stackexchange.com/questions/700",
"https://quant.stackexchange.com",
"https://quant.stackexchange.com/users/291/"
] | It shows up in Bayes Analysis where a binomial distribution is involved (integer values apply):
$$ \Gamma(k + 1) = k! $$
That allows the following integral to be evaluated in closed form:
$$ \int\_{0}^{1}p^{j-1}(1-p)^{k-1}dp = \frac{\Gamma(k)\Gamma(j)}{\Gamma(j+k)} $$
That integral can easily show up in the numerator and/or denominator of Bayes Equation. | In certain cases some stochastic differential equations(SDE's) have closed form(deterministic) solutions in the form of well known ordinary differential equations (ODE's), partial differential equations(PDE's), and special functions like the gamma function.
Here's an example from a paper where an SDE has a closed form solution in terms of the gamma function:
<http://www.siam.org/books/dc13/DC13samplechpt.pdf>
Solving SDE's (preferably quickly), like with a closed form solution (when one is available), is a core activity in quantitative finance. |
700 | I was looking into the factorial function in an R package called gregmisc and came across the implementation of the gamma function, instead of a recursive or iterative process as I was expecting. The gamma function is defined as:
$$ \Gamma(z)=\int\_{0}^{\infty}e^{-t}t^{z-1}dt $$
A brief history of the function points to Euler's solution to the factorial problem for non-integers (although the equation above is not his). It has some application in physics and I was curious if it is useful to any quant models, apart from being a fancy factorial calculator. | 2011/03/12 | [
"https://quant.stackexchange.com/questions/700",
"https://quant.stackexchange.com",
"https://quant.stackexchange.com/users/291/"
] | It shows up in Bayes Analysis where a binomial distribution is involved (integer values apply):
$$ \Gamma(k + 1) = k! $$
That allows the following integral to be evaluated in closed form:
$$ \int\_{0}^{1}p^{j-1}(1-p)^{k-1}dp = \frac{\Gamma(k)\Gamma(j)}{\Gamma(j+k)} $$
That integral can easily show up in the numerator and/or denominator of Bayes Equation. | Gamma distributions are being used to model the default rate of credit portfolios by CreditRisk. |
67,501,505 | I am trying this code provided and accepted here: <https://stackoverflow.com/a/55369170/14307622>
but I am getting this error. Any ideas why ? I am new here so if I am breaking some rules for this question, then please let me know but if possible, please suggest some solutions to the problem first.
```
import keyboard
import time
listedSongs = []
currentSong = "idk"
exit = False # make a loop control variable
def alt_k():
i = 1
paused = False
def alt_q():
global exit
exit = True
def alt_s():
if currentSong not in listedSongs:
listedSongs.append(currentSong)
print(listedSongs)
# assign hooks to the keyboard
keyboard.on_press_key("alt+k", alt_k) # on press alt+k, execute alt_k()
keyboard.on_press_key("alt+q", alt_q)
keyboard.on_press_key("alt+s", alt_s)
# main loop
while not exit:
keyboard.wait() # "block" for input (essentially, do nothing until a key is pressed and yield CPU resources to anything else that wants them)
```
The error I am getting is this:
```
Traceback (most recent call last):
File "D:\AJ\Coding\test.py", line 26, in <module>
keyboard.on_press_key("alt+k", alt_k) # on press alt+k, execute alt_k()
File "C:\Users\AJ\AppData\Local\Programs\Python\Python39\lib\site-packages\keyboard\__init__.py", line 510, in on_press_key
return hook_key(key, lambda e: e.event_type == KEY_UP or callback(e), suppress=suppress)
File "C:\Users\AJ\AppData\Local\Programs\Python\Python39\lib\site-packages\keyboard\__init__.py", line 493, in hook_key
scan_codes = key_to_scan_codes(key)
File "C:\Users\AJ\AppData\Local\Programs\Python\Python39\lib\site-packages\keyboard\__init__.py", line 324, in key_to_scan_codes
raise ValueError('Key {} is not mapped to any known key.'.format(repr(key)), e)
ValueError: ("Key 'alt+k' is not mapped to any known key.", ValueError("Key name 'alt+k' is not mapped to any known key."))
``` | 2021/05/12 | [
"https://Stackoverflow.com/questions/67501505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14307622/"
] | It seems `on_press_key()` works only with single key like `q` but not with combination `alt+q`. Or maybe it is problem only on some systems. At least it doesn't work on my Linux.
Or maybe they change code in module. Answer in [Checking for keyboard inputs uses too much cpu usage, Is there something wrong with my code?](https://stackoverflow.com/a/55369170/1832058) is 2 years old.
---
You can use `add_hotkey()` and it doesn't need `wait()`
```
import keyboard
import time
listedSongs = []
currentSong = "idk"
exit = False # make a loop control variable
def alt_k():
print('pressed: alt+k')
i = 1
paused = False
def alt_q():
global exit # need it to assign `True` to global/external variable instead of creating local variable
print('pressed: alt+q')
exit = True
def alt_s():
print('pressed: alt+s')
if currentSong not in listedSongs:
listedSongs.append(currentSong)
print(listedSongs)
keyboard.add_hotkey('alt+k', alt_k)
keyboard.add_hotkey('alt+q', alt_q)
keyboard.add_hotkey('alt+s', alt_s)
# main loop
while not exit:
time.sleep(1)
```
See examples in documentation: [Example](https://github.com/boppreh/keyboard#example)
---
Eventually you may use `hotkye = read_hotkey(...)` with `if/else` to execute correct function.
I'm not sure but sometimes it works for me also with `hotkey = keyboard.wait(suppress=False)` but sometimes it doesn't work.
```
while not exit:
hotkey = keyboard.read_hotkey(suppress=False)
#hotkey = keyboard.wait(suppress=False)
print('hotkey:', hotkey)
if hotkey == 'alt+k':
alt_k()
elif hotkey == 'alt+q':
alt_q()
``` | This is how I solved my issue.
I ditched the keyboard module since it was not working the way I wanted it to and then I used the [Python Global-Hotkeys Module](https://pypi.org/project/global-hotkeys/). The code was pretty much the same but now everything just clicked in place.
Hope this helps someone in the future. |
73,652,254 | have problem with IDEA?
I create new Spring Boot project, with dependency Spring Web, Spring Security, Spring JPA and others
Create two simple class
1. main class
2. Controller Class
@Controller
public class {
```
@GetMapping("")
public String Home() {
return "homes";
}
```
}
And simple templates "homes.html"
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Home Code Java</title>
</head>
<body>
<h1> Welcome to home JVM</h1>
</body>
</html>
```
WHY MY IDEA START THIS??? <https://drive.google.com/drive/folders/1dnn-IKkpaBeouyqnGU13YLf1GBPVd_jQ?usp=sharing>
WHAT IS IT ???? in this link different template, not my!
but port is my, localhost 9092/
this port is - localhost 9092/login? where did login come from with this templates ?
my link in @GetMapping (""), not (/login)
PLS HELP !
in properties port=9092 | 2022/09/08 | [
"https://Stackoverflow.com/questions/73652254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18583088/"
] | You have added spring security dependency in your pom.xml and that is the reason spring is securing all the endpoints by default.
Either remove the dependency or configure it to allow access to wanted endpoints. | I think this happens because of Adding the dependencies of Spring Security to you pom.xml, which automatically securing the endpoints by default.
try removing this dependency or configure it to allow access to the endpoint you want. |
17,171,967 | I'm new to vb.net. I'm used to do things the old school way (VB6).
Is there a way to manually populate a datagridview? In the old way (VB6) I populate a listview by adding columns manually and loop to a recordset to add the rows.
For example what if I have this command (storedproc).
`"Select OrderID, ProductName, Qty, SellingPrice, CustomerName FROM tblOrders".`
What if I only need to show `OrderID, ProductName and SellingPrice?`
Is there a way to manually add columns OrderID, ProductName, SellingPrice to the datagridview and loop to the result set to add the rows?
Thanks in advance. | 2013/06/18 | [
"https://Stackoverflow.com/questions/17171967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2059064/"
] | To add column to DataTable
```
Dim MyTable as New DataTable
Dim dc As DataColumn
dc = New DataColumn
dc.DataType = System.Type.GetType("System.String")
dc.ColumnName = "OrderID"
MyTable.Columns.Add(dc)
dc = New DataColumn
dc.DataType = System.Type.GetType("System.String")
dc.ColumnName = "ProductName"
MyTable.Columns.Add(dc)
dc = New DataColumn
dc.DataType = System.Type.GetType("System.String")
dc.ColumnName = "SellingPrice"
MyTable.Columns.Add(dc)
```
So, you can set MyTable as Datasource
```
DataGridview1.DataSource = MyTable
```
To add rows .. <http://msdn.microsoft.com/en-us/library/5ycd1034(v=vs.80).aspx> | I have the strange solution. If your query will never changes (i.e first column is forever "OrderID", second is "ProductName" etc.) you could hide unwanted columns.
```
DataGridView1.Columns(2).Visible = False 'hiding 3rd column
DataGridView1.Columns(4).Visible = False 'hiding 5th column
``` |
17,171,967 | I'm new to vb.net. I'm used to do things the old school way (VB6).
Is there a way to manually populate a datagridview? In the old way (VB6) I populate a listview by adding columns manually and loop to a recordset to add the rows.
For example what if I have this command (storedproc).
`"Select OrderID, ProductName, Qty, SellingPrice, CustomerName FROM tblOrders".`
What if I only need to show `OrderID, ProductName and SellingPrice?`
Is there a way to manually add columns OrderID, ProductName, SellingPrice to the datagridview and loop to the result set to add the rows?
Thanks in advance. | 2013/06/18 | [
"https://Stackoverflow.com/questions/17171967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2059064/"
] | To add column to DataTable
```
Dim MyTable as New DataTable
Dim dc As DataColumn
dc = New DataColumn
dc.DataType = System.Type.GetType("System.String")
dc.ColumnName = "OrderID"
MyTable.Columns.Add(dc)
dc = New DataColumn
dc.DataType = System.Type.GetType("System.String")
dc.ColumnName = "ProductName"
MyTable.Columns.Add(dc)
dc = New DataColumn
dc.DataType = System.Type.GetType("System.String")
dc.ColumnName = "SellingPrice"
MyTable.Columns.Add(dc)
```
So, you can set MyTable as Datasource
```
DataGridview1.DataSource = MyTable
```
To add rows .. <http://msdn.microsoft.com/en-us/library/5ycd1034(v=vs.80).aspx> | I got this code from a book. This code is close enough. At least I can configure the format and alignment of a Column.
```
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Public Class Form1
Dim objConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("MyDatabase").ConnectionString)
Dim objDataAdapter As New SqlDataAdapter()
Dim objDataSet As New DataSet()
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
objDataAdapter.SelectCommand = New SqlCommand()
objDataAdapter.SelectCommand.Connection = objConnection
objDataAdapter.SelectCommand.CommandText = "SELECT authors.au_lname, authors.au_fname, titles.title, titles.price FROM authors INNER JOIN titleauthor ON authors.au_id = titleauthor.au_id INNER JOIN titles ON titleauthor.title_id = titles.title_id ORDER BY authors.au_lname, authors.au_fname"
objDataAdapter.SelectCommand.CommandType = CommandType.Text
objConnection.Open()
objDataAdapter.Fill(objDataSet, "authors")
objConnection.Close()
grdAuthorsTitles.AutoGenerateColumns = True
grdAuthorsTitles.DataSource = objDataSet
grdAuthorsTitles.DataMember = "authors"
Dim objAlignRightCellStyle As New DataGridViewCellStyle
objAlignRightCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
Dim objAlernatingCellStyle As New DataGridViewCellStyle()
objAlernatingCellStyle.BackColor = Color.WhiteSmoke
grdAuthorsTitles.AlternatingRowsDefaultCellStyle = objAlernatingCellStyle
Dim objCurrencyCellStyle As New DataGridViewCellStyle()
objCurrencyCellStyle.Format = "c"
objCurrencyCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
grdAuthorsTitles.Columns(0).HeaderText = "Last Name"
grdAuthorsTitles.Columns(1).HeaderText = "First Name"
grdAuthorsTitles.Columns(2).HeaderText = "Book Title"
grdAuthorsTitles.Columns(2).Width = 225
grdAuthorsTitles.Columns("price").HeaderCell.Value = "Retail Price"
grdAuthorsTitles.Columns("price").HeaderCell.Style = objAlignRightCellStyle
grdAuthorsTitles.Columns("price").DefaultCellStyle = objCurrencyCellStyle
objDataAdapter = Nothing
objConnection = Nothing
objCurrencyCellStyle = Nothing
objAlignRightCellStyle = Nothing
objAlernatingCellStyle = Nothing
End Sub
End Class
``` |
6,015,172 | I'm trying to get this bit of code to work:
[Testing GPS in Android](https://stackoverflow.com/questions/1972895/testing-gps-in-android/3940877#3940877)
The problem is, when I run the test, onLocationChanged() is never called:
```
public class LocationTest0 extends AndroidTestCase implements LocationListener {
private Location received = null;
public void testExample() {
LocationManager lm = (LocationManager)this.getContext().getSystemService(Context.LOCATION_SERVICE);
String testProvider = "Test";
if (null == lm.getProvider(testProvider)){
lm.addTestProvider(testProvider, false, false, false, false, false, false, false, Criteria.POWER_LOW, Criteria.ACCURACY_FINE);
}
lm.setTestProviderEnabled(testProvider, true);
lm.requestLocationUpdates(testProvider, 0, 0, this);
lm.setTestProviderStatus(testProvider, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
Location location = new Location(testProvider);
location.setLatitude(1.0);
location.setLongitude(2.0);
location.setTime(System.currentTimeMillis());
lm.setTestProviderLocation(testProvider, location);
Assert.assertFalse("Received Location is null", received == null );
lm.removeTestProvider(testProvider);
}
@Override
public void onLocationChanged(Location location) {
received = location;
Log.d("LocationTest0", "onLocationChanged CALLED");
// Never gets called
}
``` | 2011/05/16 | [
"https://Stackoverflow.com/questions/6015172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708436/"
] | This is what worked for me
```
locationManager.addTestProvider(mocLocationProvider, false, false,
false, false, true, true, true, 0, 5);
locationManager.setTestProviderEnabled(mocLocationProvider, true);
```
.
```
Location mockLocation = new Location(mocLocationProvider); // a string
mockLocation.setLatitude(location.getLatitude()); // double
mockLocation.setLongitude(location.getLongitude());
mockLocation.setAltitude(location.getAltitude());
mockLocation.setTime(System.currentTimeMillis());
locationManager.setTestProviderLocation( mocLocationProvider, mockLocation);
```
.
```
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION">
```
Also in the android phone settings make sure you have the "Allow mock locations" checkbox ticked | I ran into a similar problem. Regardless of what I tried, I could never get onLocationChanged() to be automatically called. Eventually, I gave up and created a method that both set the location with setTestProviderLocation() and directly called onLocationChanged(). It's not a perfect solution, but it worked for my needs. |
6,015,172 | I'm trying to get this bit of code to work:
[Testing GPS in Android](https://stackoverflow.com/questions/1972895/testing-gps-in-android/3940877#3940877)
The problem is, when I run the test, onLocationChanged() is never called:
```
public class LocationTest0 extends AndroidTestCase implements LocationListener {
private Location received = null;
public void testExample() {
LocationManager lm = (LocationManager)this.getContext().getSystemService(Context.LOCATION_SERVICE);
String testProvider = "Test";
if (null == lm.getProvider(testProvider)){
lm.addTestProvider(testProvider, false, false, false, false, false, false, false, Criteria.POWER_LOW, Criteria.ACCURACY_FINE);
}
lm.setTestProviderEnabled(testProvider, true);
lm.requestLocationUpdates(testProvider, 0, 0, this);
lm.setTestProviderStatus(testProvider, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
Location location = new Location(testProvider);
location.setLatitude(1.0);
location.setLongitude(2.0);
location.setTime(System.currentTimeMillis());
lm.setTestProviderLocation(testProvider, location);
Assert.assertFalse("Received Location is null", received == null );
lm.removeTestProvider(testProvider);
}
@Override
public void onLocationChanged(Location location) {
received = location;
Log.d("LocationTest0", "onLocationChanged CALLED");
// Never gets called
}
``` | 2011/05/16 | [
"https://Stackoverflow.com/questions/6015172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708436/"
] | This is what worked for me
```
locationManager.addTestProvider(mocLocationProvider, false, false,
false, false, true, true, true, 0, 5);
locationManager.setTestProviderEnabled(mocLocationProvider, true);
```
.
```
Location mockLocation = new Location(mocLocationProvider); // a string
mockLocation.setLatitude(location.getLatitude()); // double
mockLocation.setLongitude(location.getLongitude());
mockLocation.setAltitude(location.getAltitude());
mockLocation.setTime(System.currentTimeMillis());
locationManager.setTestProviderLocation( mocLocationProvider, mockLocation);
```
.
```
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION">
```
Also in the android phone settings make sure you have the "Allow mock locations" checkbox ticked | I have the same problem with this issue, I think the problem is TestProvider, so I set
`String mocLocationProvider= LocationManager.NETWORK_PROVIDER;`
and then it can call `onLocationChanged()`. |
6,015,172 | I'm trying to get this bit of code to work:
[Testing GPS in Android](https://stackoverflow.com/questions/1972895/testing-gps-in-android/3940877#3940877)
The problem is, when I run the test, onLocationChanged() is never called:
```
public class LocationTest0 extends AndroidTestCase implements LocationListener {
private Location received = null;
public void testExample() {
LocationManager lm = (LocationManager)this.getContext().getSystemService(Context.LOCATION_SERVICE);
String testProvider = "Test";
if (null == lm.getProvider(testProvider)){
lm.addTestProvider(testProvider, false, false, false, false, false, false, false, Criteria.POWER_LOW, Criteria.ACCURACY_FINE);
}
lm.setTestProviderEnabled(testProvider, true);
lm.requestLocationUpdates(testProvider, 0, 0, this);
lm.setTestProviderStatus(testProvider, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
Location location = new Location(testProvider);
location.setLatitude(1.0);
location.setLongitude(2.0);
location.setTime(System.currentTimeMillis());
lm.setTestProviderLocation(testProvider, location);
Assert.assertFalse("Received Location is null", received == null );
lm.removeTestProvider(testProvider);
}
@Override
public void onLocationChanged(Location location) {
received = location;
Log.d("LocationTest0", "onLocationChanged CALLED");
// Never gets called
}
``` | 2011/05/16 | [
"https://Stackoverflow.com/questions/6015172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708436/"
] | I had the same problem. Couldn't resolve it and finally I gave up and added a call to `onLocationChanged( location)` after `locationManager.setTestProviderEnabled( PROVIDER, location)` manually. It's not pretty but works. | I ran into a similar problem. Regardless of what I tried, I could never get onLocationChanged() to be automatically called. Eventually, I gave up and created a method that both set the location with setTestProviderLocation() and directly called onLocationChanged(). It's not a perfect solution, but it worked for my needs. |
6,015,172 | I'm trying to get this bit of code to work:
[Testing GPS in Android](https://stackoverflow.com/questions/1972895/testing-gps-in-android/3940877#3940877)
The problem is, when I run the test, onLocationChanged() is never called:
```
public class LocationTest0 extends AndroidTestCase implements LocationListener {
private Location received = null;
public void testExample() {
LocationManager lm = (LocationManager)this.getContext().getSystemService(Context.LOCATION_SERVICE);
String testProvider = "Test";
if (null == lm.getProvider(testProvider)){
lm.addTestProvider(testProvider, false, false, false, false, false, false, false, Criteria.POWER_LOW, Criteria.ACCURACY_FINE);
}
lm.setTestProviderEnabled(testProvider, true);
lm.requestLocationUpdates(testProvider, 0, 0, this);
lm.setTestProviderStatus(testProvider, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
Location location = new Location(testProvider);
location.setLatitude(1.0);
location.setLongitude(2.0);
location.setTime(System.currentTimeMillis());
lm.setTestProviderLocation(testProvider, location);
Assert.assertFalse("Received Location is null", received == null );
lm.removeTestProvider(testProvider);
}
@Override
public void onLocationChanged(Location location) {
received = location;
Log.d("LocationTest0", "onLocationChanged CALLED");
// Never gets called
}
``` | 2011/05/16 | [
"https://Stackoverflow.com/questions/6015172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708436/"
] | After adding and enabling your Provider just use this line to get the updates :
`locationManager.requestLocationUpdates(MOCK_PROVIDER, 0, 0, this);`
I recommend to use a method like this on activity start-up :
```java
private void enableProvider() {
try {
locationManager.addTestProvider(
MOCK_PROVIDER,
false,
false,
false,
false,
true,
true,
true,
0,
5
);
} catch (IllegalArgumentException | SecurityException e) {
Log.w(TAG, "addTestProvider" + e.getMessage());
}
try {
locationManager.setTestProviderEnabled(MOCK_PROVIDER, true);
locationManager.requestLocationUpdates(MOCK_PROVIDER, 0, 0, this); <-- Update Request
} catch (IllegalArgumentException | SecurityException e) {
Log.w(TAG, "setTestProviderEnabled" + e.getMessage());
}
}
```
Handle the exceptions as well. | I have the same problem with this issue, I think the problem is TestProvider, so I set
`String mocLocationProvider= LocationManager.NETWORK_PROVIDER;`
and then it can call `onLocationChanged()`. |
6,015,172 | I'm trying to get this bit of code to work:
[Testing GPS in Android](https://stackoverflow.com/questions/1972895/testing-gps-in-android/3940877#3940877)
The problem is, when I run the test, onLocationChanged() is never called:
```
public class LocationTest0 extends AndroidTestCase implements LocationListener {
private Location received = null;
public void testExample() {
LocationManager lm = (LocationManager)this.getContext().getSystemService(Context.LOCATION_SERVICE);
String testProvider = "Test";
if (null == lm.getProvider(testProvider)){
lm.addTestProvider(testProvider, false, false, false, false, false, false, false, Criteria.POWER_LOW, Criteria.ACCURACY_FINE);
}
lm.setTestProviderEnabled(testProvider, true);
lm.requestLocationUpdates(testProvider, 0, 0, this);
lm.setTestProviderStatus(testProvider, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
Location location = new Location(testProvider);
location.setLatitude(1.0);
location.setLongitude(2.0);
location.setTime(System.currentTimeMillis());
lm.setTestProviderLocation(testProvider, location);
Assert.assertFalse("Received Location is null", received == null );
lm.removeTestProvider(testProvider);
}
@Override
public void onLocationChanged(Location location) {
received = location;
Log.d("LocationTest0", "onLocationChanged CALLED");
// Never gets called
}
``` | 2011/05/16 | [
"https://Stackoverflow.com/questions/6015172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708436/"
] | I had the same issue and could get it to work. I'll share it here in case it can help anyone else.
The thing to consider is that any call to `setTestProviderLocation` will invoke any listener registered on the mock providers at the time of the invocation. So if you call `setTestProviderLocation` and right after that call `requestLocationUpdates`, the `onLocationChanged` callback never gets called.
My problem was that I had these two (`setTestProviderLocation` and `requestLocationUpdates`) in two different threads and `requestLocationUpdates` was called after, so I never got a callback to `onLocationChanged`. If your program is multi-threaded (which very likely is) make sure `setTestProviderLocation` is called after `requestLocationUpdates`.
Also I noticed for any call to `setTestProviderLocation`, `onLocationChanged` will be called once (approximately). So you can put `setTestProviderLocation` in a loop to simulate a series of calls to `onLocationChanged`. This way you can simulate a path as well. | I had the same problem. Couldn't resolve it and finally I gave up and added a call to `onLocationChanged( location)` after `locationManager.setTestProviderEnabled( PROVIDER, location)` manually. It's not pretty but works. |
6,015,172 | I'm trying to get this bit of code to work:
[Testing GPS in Android](https://stackoverflow.com/questions/1972895/testing-gps-in-android/3940877#3940877)
The problem is, when I run the test, onLocationChanged() is never called:
```
public class LocationTest0 extends AndroidTestCase implements LocationListener {
private Location received = null;
public void testExample() {
LocationManager lm = (LocationManager)this.getContext().getSystemService(Context.LOCATION_SERVICE);
String testProvider = "Test";
if (null == lm.getProvider(testProvider)){
lm.addTestProvider(testProvider, false, false, false, false, false, false, false, Criteria.POWER_LOW, Criteria.ACCURACY_FINE);
}
lm.setTestProviderEnabled(testProvider, true);
lm.requestLocationUpdates(testProvider, 0, 0, this);
lm.setTestProviderStatus(testProvider, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
Location location = new Location(testProvider);
location.setLatitude(1.0);
location.setLongitude(2.0);
location.setTime(System.currentTimeMillis());
lm.setTestProviderLocation(testProvider, location);
Assert.assertFalse("Received Location is null", received == null );
lm.removeTestProvider(testProvider);
}
@Override
public void onLocationChanged(Location location) {
received = location;
Log.d("LocationTest0", "onLocationChanged CALLED");
// Never gets called
}
``` | 2011/05/16 | [
"https://Stackoverflow.com/questions/6015172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708436/"
] | This is what worked for me
```
locationManager.addTestProvider(mocLocationProvider, false, false,
false, false, true, true, true, 0, 5);
locationManager.setTestProviderEnabled(mocLocationProvider, true);
```
.
```
Location mockLocation = new Location(mocLocationProvider); // a string
mockLocation.setLatitude(location.getLatitude()); // double
mockLocation.setLongitude(location.getLongitude());
mockLocation.setAltitude(location.getAltitude());
mockLocation.setTime(System.currentTimeMillis());
locationManager.setTestProviderLocation( mocLocationProvider, mockLocation);
```
.
```
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION">
```
Also in the android phone settings make sure you have the "Allow mock locations" checkbox ticked | I had the same problem. Couldn't resolve it and finally I gave up and added a call to `onLocationChanged( location)` after `locationManager.setTestProviderEnabled( PROVIDER, location)` manually. It's not pretty but works. |
6,015,172 | I'm trying to get this bit of code to work:
[Testing GPS in Android](https://stackoverflow.com/questions/1972895/testing-gps-in-android/3940877#3940877)
The problem is, when I run the test, onLocationChanged() is never called:
```
public class LocationTest0 extends AndroidTestCase implements LocationListener {
private Location received = null;
public void testExample() {
LocationManager lm = (LocationManager)this.getContext().getSystemService(Context.LOCATION_SERVICE);
String testProvider = "Test";
if (null == lm.getProvider(testProvider)){
lm.addTestProvider(testProvider, false, false, false, false, false, false, false, Criteria.POWER_LOW, Criteria.ACCURACY_FINE);
}
lm.setTestProviderEnabled(testProvider, true);
lm.requestLocationUpdates(testProvider, 0, 0, this);
lm.setTestProviderStatus(testProvider, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
Location location = new Location(testProvider);
location.setLatitude(1.0);
location.setLongitude(2.0);
location.setTime(System.currentTimeMillis());
lm.setTestProviderLocation(testProvider, location);
Assert.assertFalse("Received Location is null", received == null );
lm.removeTestProvider(testProvider);
}
@Override
public void onLocationChanged(Location location) {
received = location;
Log.d("LocationTest0", "onLocationChanged CALLED");
// Never gets called
}
``` | 2011/05/16 | [
"https://Stackoverflow.com/questions/6015172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708436/"
] | I ran into a similar problem. Regardless of what I tried, I could never get onLocationChanged() to be automatically called. Eventually, I gave up and created a method that both set the location with setTestProviderLocation() and directly called onLocationChanged(). It's not a perfect solution, but it worked for my needs. | I have the same problem with this issue, I think the problem is TestProvider, so I set
`String mocLocationProvider= LocationManager.NETWORK_PROVIDER;`
and then it can call `onLocationChanged()`. |
6,015,172 | I'm trying to get this bit of code to work:
[Testing GPS in Android](https://stackoverflow.com/questions/1972895/testing-gps-in-android/3940877#3940877)
The problem is, when I run the test, onLocationChanged() is never called:
```
public class LocationTest0 extends AndroidTestCase implements LocationListener {
private Location received = null;
public void testExample() {
LocationManager lm = (LocationManager)this.getContext().getSystemService(Context.LOCATION_SERVICE);
String testProvider = "Test";
if (null == lm.getProvider(testProvider)){
lm.addTestProvider(testProvider, false, false, false, false, false, false, false, Criteria.POWER_LOW, Criteria.ACCURACY_FINE);
}
lm.setTestProviderEnabled(testProvider, true);
lm.requestLocationUpdates(testProvider, 0, 0, this);
lm.setTestProviderStatus(testProvider, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
Location location = new Location(testProvider);
location.setLatitude(1.0);
location.setLongitude(2.0);
location.setTime(System.currentTimeMillis());
lm.setTestProviderLocation(testProvider, location);
Assert.assertFalse("Received Location is null", received == null );
lm.removeTestProvider(testProvider);
}
@Override
public void onLocationChanged(Location location) {
received = location;
Log.d("LocationTest0", "onLocationChanged CALLED");
// Never gets called
}
``` | 2011/05/16 | [
"https://Stackoverflow.com/questions/6015172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708436/"
] | I had the same issue and could get it to work. I'll share it here in case it can help anyone else.
The thing to consider is that any call to `setTestProviderLocation` will invoke any listener registered on the mock providers at the time of the invocation. So if you call `setTestProviderLocation` and right after that call `requestLocationUpdates`, the `onLocationChanged` callback never gets called.
My problem was that I had these two (`setTestProviderLocation` and `requestLocationUpdates`) in two different threads and `requestLocationUpdates` was called after, so I never got a callback to `onLocationChanged`. If your program is multi-threaded (which very likely is) make sure `setTestProviderLocation` is called after `requestLocationUpdates`.
Also I noticed for any call to `setTestProviderLocation`, `onLocationChanged` will be called once (approximately). So you can put `setTestProviderLocation` in a loop to simulate a series of calls to `onLocationChanged`. This way you can simulate a path as well. | I have the same problem with this issue, I think the problem is TestProvider, so I set
`String mocLocationProvider= LocationManager.NETWORK_PROVIDER;`
and then it can call `onLocationChanged()`. |
6,015,172 | I'm trying to get this bit of code to work:
[Testing GPS in Android](https://stackoverflow.com/questions/1972895/testing-gps-in-android/3940877#3940877)
The problem is, when I run the test, onLocationChanged() is never called:
```
public class LocationTest0 extends AndroidTestCase implements LocationListener {
private Location received = null;
public void testExample() {
LocationManager lm = (LocationManager)this.getContext().getSystemService(Context.LOCATION_SERVICE);
String testProvider = "Test";
if (null == lm.getProvider(testProvider)){
lm.addTestProvider(testProvider, false, false, false, false, false, false, false, Criteria.POWER_LOW, Criteria.ACCURACY_FINE);
}
lm.setTestProviderEnabled(testProvider, true);
lm.requestLocationUpdates(testProvider, 0, 0, this);
lm.setTestProviderStatus(testProvider, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
Location location = new Location(testProvider);
location.setLatitude(1.0);
location.setLongitude(2.0);
location.setTime(System.currentTimeMillis());
lm.setTestProviderLocation(testProvider, location);
Assert.assertFalse("Received Location is null", received == null );
lm.removeTestProvider(testProvider);
}
@Override
public void onLocationChanged(Location location) {
received = location;
Log.d("LocationTest0", "onLocationChanged CALLED");
// Never gets called
}
``` | 2011/05/16 | [
"https://Stackoverflow.com/questions/6015172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708436/"
] | This is what worked for me
```
locationManager.addTestProvider(mocLocationProvider, false, false,
false, false, true, true, true, 0, 5);
locationManager.setTestProviderEnabled(mocLocationProvider, true);
```
.
```
Location mockLocation = new Location(mocLocationProvider); // a string
mockLocation.setLatitude(location.getLatitude()); // double
mockLocation.setLongitude(location.getLongitude());
mockLocation.setAltitude(location.getAltitude());
mockLocation.setTime(System.currentTimeMillis());
locationManager.setTestProviderLocation( mocLocationProvider, mockLocation);
```
.
```
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION">
```
Also in the android phone settings make sure you have the "Allow mock locations" checkbox ticked | I had the same issue and could get it to work. I'll share it here in case it can help anyone else.
The thing to consider is that any call to `setTestProviderLocation` will invoke any listener registered on the mock providers at the time of the invocation. So if you call `setTestProviderLocation` and right after that call `requestLocationUpdates`, the `onLocationChanged` callback never gets called.
My problem was that I had these two (`setTestProviderLocation` and `requestLocationUpdates`) in two different threads and `requestLocationUpdates` was called after, so I never got a callback to `onLocationChanged`. If your program is multi-threaded (which very likely is) make sure `setTestProviderLocation` is called after `requestLocationUpdates`.
Also I noticed for any call to `setTestProviderLocation`, `onLocationChanged` will be called once (approximately). So you can put `setTestProviderLocation` in a loop to simulate a series of calls to `onLocationChanged`. This way you can simulate a path as well. |
6,015,172 | I'm trying to get this bit of code to work:
[Testing GPS in Android](https://stackoverflow.com/questions/1972895/testing-gps-in-android/3940877#3940877)
The problem is, when I run the test, onLocationChanged() is never called:
```
public class LocationTest0 extends AndroidTestCase implements LocationListener {
private Location received = null;
public void testExample() {
LocationManager lm = (LocationManager)this.getContext().getSystemService(Context.LOCATION_SERVICE);
String testProvider = "Test";
if (null == lm.getProvider(testProvider)){
lm.addTestProvider(testProvider, false, false, false, false, false, false, false, Criteria.POWER_LOW, Criteria.ACCURACY_FINE);
}
lm.setTestProviderEnabled(testProvider, true);
lm.requestLocationUpdates(testProvider, 0, 0, this);
lm.setTestProviderStatus(testProvider, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
Location location = new Location(testProvider);
location.setLatitude(1.0);
location.setLongitude(2.0);
location.setTime(System.currentTimeMillis());
lm.setTestProviderLocation(testProvider, location);
Assert.assertFalse("Received Location is null", received == null );
lm.removeTestProvider(testProvider);
}
@Override
public void onLocationChanged(Location location) {
received = location;
Log.d("LocationTest0", "onLocationChanged CALLED");
// Never gets called
}
``` | 2011/05/16 | [
"https://Stackoverflow.com/questions/6015172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708436/"
] | I had the same problem. Couldn't resolve it and finally I gave up and added a call to `onLocationChanged( location)` after `locationManager.setTestProviderEnabled( PROVIDER, location)` manually. It's not pretty but works. | After adding and enabling your Provider just use this line to get the updates :
`locationManager.requestLocationUpdates(MOCK_PROVIDER, 0, 0, this);`
I recommend to use a method like this on activity start-up :
```java
private void enableProvider() {
try {
locationManager.addTestProvider(
MOCK_PROVIDER,
false,
false,
false,
false,
true,
true,
true,
0,
5
);
} catch (IllegalArgumentException | SecurityException e) {
Log.w(TAG, "addTestProvider" + e.getMessage());
}
try {
locationManager.setTestProviderEnabled(MOCK_PROVIDER, true);
locationManager.requestLocationUpdates(MOCK_PROVIDER, 0, 0, this); <-- Update Request
} catch (IllegalArgumentException | SecurityException e) {
Log.w(TAG, "setTestProviderEnabled" + e.getMessage());
}
}
```
Handle the exceptions as well. |
1,291,367 | Simplifying $$\Big[\dfrac{5-\sqrt{a}}{5+\sqrt a}-\dfrac{\sqrt a+5}{\sqrt a-5}+2\Big]^{-2}$$
When I try, the numerator cancels out to $0$, yet the answer sheet says $(25-a)^2/10000$. Where am I going wrong & how is getting $10 000$ there even possible? | 2015/05/20 | [
"https://math.stackexchange.com/questions/1291367",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/242166/"
] | Note that the expression in the brackets can be adapted by changing the sign of the second term and the signs in the denominator. Simplify to $$\frac {5-\sqrt a}{5+\sqrt a}+\frac {5+\sqrt a}{5-\sqrt a}+2=\frac {(5-\sqrt a)^2+(5+\sqrt a)^2+2(25-a)}{25-a}=\frac {100}{25-a}$$ | Let $s = \sqrt{a}$:
$$
\frac{5-s}{5+s}-\frac{s+5}{s-5}
= \frac{-(s-5)^2 - (s+5)^2}
{(5+s)(5-s)}
= \frac{(s-5)^2 + (s+5)^2}
{s^2-5^2}
= \frac{2s^2 + 2 \cdot 5^2}{s^2-5^2}
= \frac{2(a + 25)}{a-25}
$$
Can you finish the problem? |
1,291,367 | Simplifying $$\Big[\dfrac{5-\sqrt{a}}{5+\sqrt a}-\dfrac{\sqrt a+5}{\sqrt a-5}+2\Big]^{-2}$$
When I try, the numerator cancels out to $0$, yet the answer sheet says $(25-a)^2/10000$. Where am I going wrong & how is getting $10 000$ there even possible? | 2015/05/20 | [
"https://math.stackexchange.com/questions/1291367",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/242166/"
] | Let $s = \sqrt{a}$:
$$
\frac{5-s}{5+s}-\frac{s+5}{s-5}
= \frac{-(s-5)^2 - (s+5)^2}
{(5+s)(5-s)}
= \frac{(s-5)^2 + (s+5)^2}
{s^2-5^2}
= \frac{2s^2 + 2 \cdot 5^2}{s^2-5^2}
= \frac{2(a + 25)}{a-25}
$$
Can you finish the problem? | $$\dfrac{\bar w}w + \dfrac{w}{\bar w}+2\, =\, \dfrac{(\bar w+ w)^2}{\bar w w}\, =\, \dfrac{10^2}{25-a}\ \ \ {\rm for}\ \ \ \begin{align}w\, =\, 5+\sqrt a\\ \bar w \,=\, 5-\sqrt a\end{align}$$ |
1,291,367 | Simplifying $$\Big[\dfrac{5-\sqrt{a}}{5+\sqrt a}-\dfrac{\sqrt a+5}{\sqrt a-5}+2\Big]^{-2}$$
When I try, the numerator cancels out to $0$, yet the answer sheet says $(25-a)^2/10000$. Where am I going wrong & how is getting $10 000$ there even possible? | 2015/05/20 | [
"https://math.stackexchange.com/questions/1291367",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/242166/"
] | Note that the expression in the brackets can be adapted by changing the sign of the second term and the signs in the denominator. Simplify to $$\frac {5-\sqrt a}{5+\sqrt a}+\frac {5+\sqrt a}{5-\sqrt a}+2=\frac {(5-\sqrt a)^2+(5+\sqrt a)^2+2(25-a)}{25-a}=\frac {100}{25-a}$$ | $$\dfrac{\bar w}w + \dfrac{w}{\bar w}+2\, =\, \dfrac{(\bar w+ w)^2}{\bar w w}\, =\, \dfrac{10^2}{25-a}\ \ \ {\rm for}\ \ \ \begin{align}w\, =\, 5+\sqrt a\\ \bar w \,=\, 5-\sqrt a\end{align}$$ |
11,129,696 | I want to capitalize the first letter of sentences, and also the first letter after commas if possible. I want to add the code in here:
```css
.qcont {
width: 550px;
height: auto;
float: right;
overflow: hidden;
position: relative;
}
``` | 2012/06/20 | [
"https://Stackoverflow.com/questions/11129696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448744/"
] | This cannot be done in CSS. The `text-transform` property makes no distinction according to the placement of a word inside the content, and there is no pseudo-element for selecting the first word of a sentence. You would need to have real elements, in markup, for each sentence. But if you can do that, then you could probably just as well change the initial letters to uppercase in the content proper.
Capitalization at the start of a sentence is a matter of orthography and should be done when generating the content, not with optional stylistic suggestions (CSS) or with client-side scripting. The process of recognizing sentence boundaries is far from trivial and cannot in general be performed automatically without complex syntactic and semantic analysis (e.g., an abbreviation ending with a period may appear inside a sentence or at the end of a sentence). | `text-transform:capitalize;` ~~will capitalize the first letter of a sentence~~, but if you want to also do it for commas you will have to write some javascript. I agree with @BoltClock, though. Why on earth would you want to capitalize after a comma?
**Edit:** For the sake of readers: `text-transform:capitalize;` will **capitalize each word of a sentence**, not the first one only.
You must use the `:first-letter` CSS selector with the above. |
11,129,696 | I want to capitalize the first letter of sentences, and also the first letter after commas if possible. I want to add the code in here:
```css
.qcont {
width: 550px;
height: auto;
float: right;
overflow: hidden;
position: relative;
}
``` | 2012/06/20 | [
"https://Stackoverflow.com/questions/11129696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448744/"
] | You can capitalize the first letter of the `.qcont` element by using the pseudo-element `:first-letter`.
```
.qcont:first-letter{
text-transform: capitalize
}
```
This is the closest you're gonna get using only css. You could use javascript (in combination with jQuery) to wrap each letter which comes after a period (or comma, like you wish) in a `span`. You could add the same css as above to that `span`. Or do it in javascript all together.
Here's a snippet for the css approach:
```css
.qcont:first-letter {
text-transform: capitalize
}
```
```html
<p class="qcont">word, another word</p>
``` | `text-transform:capitalize;` ~~will capitalize the first letter of a sentence~~, but if you want to also do it for commas you will have to write some javascript. I agree with @BoltClock, though. Why on earth would you want to capitalize after a comma?
**Edit:** For the sake of readers: `text-transform:capitalize;` will **capitalize each word of a sentence**, not the first one only.
You must use the `:first-letter` CSS selector with the above. |
11,129,696 | I want to capitalize the first letter of sentences, and also the first letter after commas if possible. I want to add the code in here:
```css
.qcont {
width: 550px;
height: auto;
float: right;
overflow: hidden;
position: relative;
}
``` | 2012/06/20 | [
"https://Stackoverflow.com/questions/11129696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448744/"
] | If you need to capitalize the first letter in contenteditable container you can't use the css property
```
#myContentEditableDiv:first-letter {
text-transform: capitalize;
}
```
because when you try to delete a letter automatically you will delete all the text contained in the contenteditable.
Try instead the example provided by sakhunzai in <https://stackoverflow.com/a/7242079/6411398>
for a working solution. | `text-transform:capitalize;` ~~will capitalize the first letter of a sentence~~, but if you want to also do it for commas you will have to write some javascript. I agree with @BoltClock, though. Why on earth would you want to capitalize after a comma?
**Edit:** For the sake of readers: `text-transform:capitalize;` will **capitalize each word of a sentence**, not the first one only.
You must use the `:first-letter` CSS selector with the above. |
11,129,696 | I want to capitalize the first letter of sentences, and also the first letter after commas if possible. I want to add the code in here:
```css
.qcont {
width: 550px;
height: auto;
float: right;
overflow: hidden;
position: relative;
}
``` | 2012/06/20 | [
"https://Stackoverflow.com/questions/11129696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448744/"
] | You can capitalize the first letter of the `.qcont` element by using the pseudo-element `:first-letter`.
```
.qcont:first-letter{
text-transform: capitalize
}
```
This is the closest you're gonna get using only css. You could use javascript (in combination with jQuery) to wrap each letter which comes after a period (or comma, like you wish) in a `span`. You could add the same css as above to that `span`. Or do it in javascript all together.
Here's a snippet for the css approach:
```css
.qcont:first-letter {
text-transform: capitalize
}
```
```html
<p class="qcont">word, another word</p>
``` | This cannot be done in CSS. The `text-transform` property makes no distinction according to the placement of a word inside the content, and there is no pseudo-element for selecting the first word of a sentence. You would need to have real elements, in markup, for each sentence. But if you can do that, then you could probably just as well change the initial letters to uppercase in the content proper.
Capitalization at the start of a sentence is a matter of orthography and should be done when generating the content, not with optional stylistic suggestions (CSS) or with client-side scripting. The process of recognizing sentence boundaries is far from trivial and cannot in general be performed automatically without complex syntactic and semantic analysis (e.g., an abbreviation ending with a period may appear inside a sentence or at the end of a sentence). |
11,129,696 | I want to capitalize the first letter of sentences, and also the first letter after commas if possible. I want to add the code in here:
```css
.qcont {
width: 550px;
height: auto;
float: right;
overflow: hidden;
position: relative;
}
``` | 2012/06/20 | [
"https://Stackoverflow.com/questions/11129696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448744/"
] | You can capitalize the first letter of the `.qcont` element by using the pseudo-element `:first-letter`.
```
.qcont:first-letter{
text-transform: capitalize
}
```
This is the closest you're gonna get using only css. You could use javascript (in combination with jQuery) to wrap each letter which comes after a period (or comma, like you wish) in a `span`. You could add the same css as above to that `span`. Or do it in javascript all together.
Here's a snippet for the css approach:
```css
.qcont:first-letter {
text-transform: capitalize
}
```
```html
<p class="qcont">word, another word</p>
``` | If you need to capitalize the first letter in contenteditable container you can't use the css property
```
#myContentEditableDiv:first-letter {
text-transform: capitalize;
}
```
because when you try to delete a letter automatically you will delete all the text contained in the contenteditable.
Try instead the example provided by sakhunzai in <https://stackoverflow.com/a/7242079/6411398>
for a working solution. |
74,025,190 | My requirement is simple, I need to write my spark DataFrame to S3 as a single csv file of a specified name
Write now I am using .coalesce(1) which puts all the data in a single CSV but still creates a folder with some additional files and the name of the main csv file is some id.
[I'm using java/scala]
```
dataFrame.coalesce(1).write.mode(SaveMode.Overwrite).option("header", "true").csv("s3a://<mypath>")
```
[this is how the data is being saved](https://i.stack.imgur.com/jH5OZ.png) | 2022/10/11 | [
"https://Stackoverflow.com/questions/74025190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11907366/"
] | You are treating the paginator like the Resource client which it is not. You need to be more low level like this example:
<https://github.com/aws-samples/aws-dynamodb-examples/blob/master/DynamoDB-SDK-Examples/python/WorkingWithScans/scan_with_paginator.py> | Two possible solutions identified that I will leave here for anyone attempting to filter / search on paginated DynamoDB responses as the Boto3 documentation is frankly useless.
Option 1:
Drill down into the response object using JMES on the dynamodb specific response object:
```
response object = {
"Items":[
{
"Date":{
"N":"54675846"
},
"Message":{
"S":"Message02"
},
"_id":{
"S":"4567"
},
"Category":{
"S":"Validation Error"
},
"Email":{
"S":"Will@mail.com"
}
}
]}
filtered_iterator = response_iterator.search("Items[?Category.S == 'Validation Error'].{_id: _id, Category: Category, Date: Date, IsRead: IsRead, Message: Message, Email: Email}")
```
You can then iterate over the response object pages as usual with a standard for loop.
Option 2:
Use list comprehension on the paginated response object and filter at that point. Note that this will be the more expensive option as it will still scan and return the max items within your paginator configutration:
```
for page in response_iterator:
page["Items"] = [x for x in page["Items"] if '{search_term}' in x['Category']['S']]
```
Option 3:
By far the simplest solution is that identified by Lee Harrigan. |
46,974 | Is there a difference between [Google Keyboard](https://play.google.com/store/apps/details?id=com.google.android.inputmethod.latin), which was recently release on the Play Store, and the Android Keyboard (AOSP) in the open source project?
Update: I need the difference from a feature prospective | 2013/06/10 | [
"https://android.stackexchange.com/questions/46974",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/592/"
] | The Samsung Galaxy S2 does have dual microphones.
However, if using Gingerbread (2.3), the device only records mono audio.
Using Ice Cream Sandwich (4.0) though, the device can record stereo audio at about 130 Kbps with a sampling rate of 48KHz.
Source: [GSM Arena](http://www.gsmarena.com/samsung_galaxy_s_ii_ics_vs_gingerbread-review-737p3.php) | It does have a dedicated 2nd microphone for active noise cancellation according to [GSMArena](http://www.gsmarena.com/samsung_i9100_galaxy_s_ii-3621.php). |
129,041 | Amarok 2 can search through music collection using ID3v2 tag's 'bpm' field. That would be *very* nice to retag the entire music collection so I can find the 'mood' of the track I like.
However I've not found any beat-detection software that could have helped me. Have you ever used one? CLI, preferably. Also I'm interested if there's anything alike for tagging FLACs with the same 'bpm' field.
Thanks! :)
P.S. I'm aware there's a nice moodbar feature, however it's useless for searching. | 2010/04/09 | [
"https://superuser.com/questions/129041",
"https://superuser.com",
"https://superuser.com/users/8382/"
] | I don't know of a tool that does exactly what you are looking for, but I have played around with [MusicIP](http://www.amplifindmusicservices.com/what/downloads.php).
Used the linux / java version - it takes a long time to completely analyze a music library, but it really does work. You can find songs that are similar to other songs. You can right click on the playlist generated and select option to select more or fewer songs like the one selected. You can also choose to eliminate certain genre's. It's kind of cool, but after the wow factor wore off, I stopped using it.
The free version exports playlists up to 75 songs in (at least) m3u format.
It's currently unsupported, but I think they have tried to take it commercial as [Predexis](http://www.predixis.com/). | I found another tool for tagging MP3 files with the correct BPM value.
It's called [BPMDetect](http://sourceforge.net/projects/bpmdetect/). Open-source. QT libs so works fine under Gnome. Comes with a GUI but can be compiled as a console only version (run "scons console=1" as stated in the readme.txt).
Otherwise, in the end, i've too used the "bpmcount" from BpmDJ as i had difficulties to compile BPMDetect on a 64 bits Ubuntu host (due to the fmodex dependency). So i took the (very cool and well-written) shell script above (see below), the "bpmcount" binary extracted from the [x64 .rpm][3] available on the BpmDJ website (i've just extract the .rpm with
```
pm2cpio bpmdj-4.2.pl2-0.x86_64.rpm|cpio -idv
```
and it worked like a charm. I just had to modify the above script as, out of the box, it weren't working on my side (problem with stdout / stderr of the bpmcount binary). My modification is about file redirection :
```
local bpm=$(bpmcount "$file" 3>&1 1>/dev/null 2>&3 | grep '^[0-9]' | cut -f1)
``` |
129,041 | Amarok 2 can search through music collection using ID3v2 tag's 'bpm' field. That would be *very* nice to retag the entire music collection so I can find the 'mood' of the track I like.
However I've not found any beat-detection software that could have helped me. Have you ever used one? CLI, preferably. Also I'm interested if there's anything alike for tagging FLACs with the same 'bpm' field.
Thanks! :)
P.S. I'm aware there's a nice moodbar feature, however it's useless for searching. | 2010/04/09 | [
"https://superuser.com/questions/129041",
"https://superuser.com",
"https://superuser.com/users/8382/"
] | This is a command-line tool to detect the BPM and put it in the FLAC file tags:
<http://www.pogo.org.uk/~mark/bpm-tools/> | I don't know of a tool that does exactly what you are looking for, but I have played around with [MusicIP](http://www.amplifindmusicservices.com/what/downloads.php).
Used the linux / java version - it takes a long time to completely analyze a music library, but it really does work. You can find songs that are similar to other songs. You can right click on the playlist generated and select option to select more or fewer songs like the one selected. You can also choose to eliminate certain genre's. It's kind of cool, but after the wow factor wore off, I stopped using it.
The free version exports playlists up to 75 songs in (at least) m3u format.
It's currently unsupported, but I think they have tried to take it commercial as [Predexis](http://www.predixis.com/). |
129,041 | Amarok 2 can search through music collection using ID3v2 tag's 'bpm' field. That would be *very* nice to retag the entire music collection so I can find the 'mood' of the track I like.
However I've not found any beat-detection software that could have helped me. Have you ever used one? CLI, preferably. Also I'm interested if there's anything alike for tagging FLACs with the same 'bpm' field.
Thanks! :)
P.S. I'm aware there's a nice moodbar feature, however it's useless for searching. | 2010/04/09 | [
"https://superuser.com/questions/129041",
"https://superuser.com",
"https://superuser.com/users/8382/"
] | This is a command-line tool to detect the BPM and put it in the FLAC file tags:
<http://www.pogo.org.uk/~mark/bpm-tools/> | It's not Linux but may well work in Wine - I use [MixMeister BPM Analyzer](http://www.mixmeister.com/bpmanalyzer/bpmanalyzer.asp) |
129,041 | Amarok 2 can search through music collection using ID3v2 tag's 'bpm' field. That would be *very* nice to retag the entire music collection so I can find the 'mood' of the track I like.
However I've not found any beat-detection software that could have helped me. Have you ever used one? CLI, preferably. Also I'm interested if there's anything alike for tagging FLACs with the same 'bpm' field.
Thanks! :)
P.S. I'm aware there's a nice moodbar feature, however it's useless for searching. | 2010/04/09 | [
"https://superuser.com/questions/129041",
"https://superuser.com",
"https://superuser.com/users/8382/"
] | I used kolypto's original script using `bpmcount` and rewrote it for `bpm-tag` (utility of `bpm-tools`) which I had better luck with installing. I also made some improvements of my own.
You can find it on GitHub <https://github.com/meridius/bpmwrap> | There is another tool recommended in [this question](https://stackoverflow.com/questions/477944/bpm-audio-detection-library) on stackoverflow: [aubio](http://dev.aubio.org/wiki/Features), which comes along with python modules.
I haven't tried it because I was kinda busy taking care of compiling **BpmDj**. Just in case anybody else finds themselves struggling similar troubles while trying, I'd like to strongly recommend to make absolutely sure:
1. having downloaded the latest release of the BpmDj sources
2. having the appropriate boost libraries installed
With the latest g++ compiler upgrades, some issues seem to have arisen especially concerning recent debian and ubuntu releases. As soon as he became aware of these problems, the author had the kindness to fix the emerged incompatibilities and put together a new release which now compiles like a charm. So anybody who have been close to falling into despair over relentless compile errors lately: you are save now.
@**mmx**, your tools look good too, but they rely on `SoX`, which by default has no mp3 features. So they require compiling SoX with Lame/MAD support first, which unfortunately is too much effort for people as lazy as me. |
129,041 | Amarok 2 can search through music collection using ID3v2 tag's 'bpm' field. That would be *very* nice to retag the entire music collection so I can find the 'mood' of the track I like.
However I've not found any beat-detection software that could have helped me. Have you ever used one? CLI, preferably. Also I'm interested if there's anything alike for tagging FLACs with the same 'bpm' field.
Thanks! :)
P.S. I'm aware there's a nice moodbar feature, however it's useless for searching. | 2010/04/09 | [
"https://superuser.com/questions/129041",
"https://superuser.com",
"https://superuser.com/users/8382/"
] | At the site DaveParillo suggested I've found [BpmDj](http://bpmdj.yellowcouch.org/measuring-tempo.html) project. It has a `bpmcount` executable that calculates the bpm very nice: it handles mp3 as well as flac:
```
161.135 Metallica/2008 - Death Magnetic/01-That Was Just Your Life.flac
63.5645 Doom3.mp3
```
The only thing that's left is to retag the collection. I'll update this answer whenever I succeed.
Thanks! :)
---
**Step 1**
Run `bpmcount` against the entire collection and store the results into a textfile.
The problem is that `bpmcount` crashes from time to time and tries to eat up to 2GB of memory when it processes several files so we should feed it with filenames one by one. Like this:
```
musicdir='/home/ootync/music'
find "$musicdir" -iregex ".*\.\(mp3\|ogg\|flac\|ape\)" -exec bpmcount {} \; \
| fgrep "$musicdir" > "$musicdir/BPMs.txt"
```
---
**Step 2**
We'll need some additional packages: `apt-get install vorbis-tools flac python-mutagen`.
Now have a look at how the 'bpm' tag can be added:
```
mid3v2 --TBPM 100 doom3.mp3
vorbiscomment -a -t "BPM=100" mother.ogg
metaflac --set-tag="BPM=100" metallica.flac
```
Alas, I have no \*.ape tracks
Now we have the BPMs and the entire collection should be retagged. Here's the script:
```
cat "$musicdir/BPMs.txt" | while read bpm file ; do
bpm=`printf "%.0f" "$bpm"` ;
case "$file" in
*.mp3) mid3v2 --TBPM "$bpm" "$file" > /dev/null ;;
*.ogg) vorbiscomment -a -t "BPM=$bpm" "$file" ;;
*.flac) metaflac --set-tag="BPM=$bpm" "$file" ;;
esac
done
```
---
**Step 2.1 Revisited**
Here's a script that will add BPM tags to your collection.
It runs one process per CPU Core to make the process faster. Additionally, it uses no temporary files and it capable of detecting whether a file is already tagged.
Additionally, I've discovered that FLAC sometimes has both ID3 and VorbisComment inside. This script updates both.
```
#!/bin/bash
function display_help() {
cat <<-HELP
Recursive BPM-writer for multicore CPUs.
It analyzes BPMs of every media file and writes a correct tag there.
Usage: $(basename "$0") path [...]
HELP
exit 0
}
[ $# -lt 1 ] && display_help
#=== Requirements
requires="bpmcount mid3v2 vorbiscomment metaflac"
which $requires > /dev/null || { echo "E: These binaries are required: $requires" >&2 ; exit 1; }
#=== Functions
function bpm_read(){
local file="$1"
local ext="${file##*.}"
declare -l ext
# Detect
{ case "$ext" in
'mp3') mid3v2 -l "$file" ;;
'ogg') vorbiscomment -l "$file" ;;
'flac') metaflac --export-tags-to=- "$file" ;;
esac ; } | fgrep 'BPM=' | cut -d'=' -f2
}
function bpm_write(){
local file="$1"
local bpm="${2%%.*}"
local ext="${file##*.}"
declare -l ext
echo "BPM=$bpm @$file"
# Write
case "$ext" in
'mp3') mid3v2 --TBPM "$bpm" "$file" ;;
'ogg') vorbiscomment -a -t "BPM=$bpm" "$file" ;;
'flac') metaflac --set-tag="BPM=$bpm" "$file"
mid3v2 --TBPM "$bpm" "$file" # Need to store to ID3 as well :(
;;
esac
}
#=== Process
function oneThread(){
local file="$1"
#=== Check whether there's an existing BPM
local bpm=$(bpm_read "$file")
[ "$bpm" != '' ] && return 0 # there's a nonempty BPM tag
#=== Detect a new BPM
# Detect a new bpm
local bpm=$(bpmcount "$file" | grep '^[0-9]' | cut -f1)
[ "$bpm" == '' ] && { echo "W: Invalid BPM '$bpm' detected @ $file" >&2 ; return 0 ; } # problems
# Write it
bpm_write "$file" "${bpm%%.*}" >/dev/null
}
NUMCPU="$(grep ^processor /proc/cpuinfo | wc -l)"
find $@ -type f -regextype posix-awk -iregex '.*\.(mp3|ogg|flac)' \
| while read file ; do
[ `jobs -p | wc -l` -ge $NUMCPU ] && wait
echo "$file"
oneThread "$file" &
done
```
Enjoy! :) | I used kolypto's original script using `bpmcount` and rewrote it for `bpm-tag` (utility of `bpm-tools`) which I had better luck with installing. I also made some improvements of my own.
You can find it on GitHub <https://github.com/meridius/bpmwrap> |
129,041 | Amarok 2 can search through music collection using ID3v2 tag's 'bpm' field. That would be *very* nice to retag the entire music collection so I can find the 'mood' of the track I like.
However I've not found any beat-detection software that could have helped me. Have you ever used one? CLI, preferably. Also I'm interested if there's anything alike for tagging FLACs with the same 'bpm' field.
Thanks! :)
P.S. I'm aware there's a nice moodbar feature, however it's useless for searching. | 2010/04/09 | [
"https://superuser.com/questions/129041",
"https://superuser.com",
"https://superuser.com/users/8382/"
] | At the site DaveParillo suggested I've found [BpmDj](http://bpmdj.yellowcouch.org/measuring-tempo.html) project. It has a `bpmcount` executable that calculates the bpm very nice: it handles mp3 as well as flac:
```
161.135 Metallica/2008 - Death Magnetic/01-That Was Just Your Life.flac
63.5645 Doom3.mp3
```
The only thing that's left is to retag the collection. I'll update this answer whenever I succeed.
Thanks! :)
---
**Step 1**
Run `bpmcount` against the entire collection and store the results into a textfile.
The problem is that `bpmcount` crashes from time to time and tries to eat up to 2GB of memory when it processes several files so we should feed it with filenames one by one. Like this:
```
musicdir='/home/ootync/music'
find "$musicdir" -iregex ".*\.\(mp3\|ogg\|flac\|ape\)" -exec bpmcount {} \; \
| fgrep "$musicdir" > "$musicdir/BPMs.txt"
```
---
**Step 2**
We'll need some additional packages: `apt-get install vorbis-tools flac python-mutagen`.
Now have a look at how the 'bpm' tag can be added:
```
mid3v2 --TBPM 100 doom3.mp3
vorbiscomment -a -t "BPM=100" mother.ogg
metaflac --set-tag="BPM=100" metallica.flac
```
Alas, I have no \*.ape tracks
Now we have the BPMs and the entire collection should be retagged. Here's the script:
```
cat "$musicdir/BPMs.txt" | while read bpm file ; do
bpm=`printf "%.0f" "$bpm"` ;
case "$file" in
*.mp3) mid3v2 --TBPM "$bpm" "$file" > /dev/null ;;
*.ogg) vorbiscomment -a -t "BPM=$bpm" "$file" ;;
*.flac) metaflac --set-tag="BPM=$bpm" "$file" ;;
esac
done
```
---
**Step 2.1 Revisited**
Here's a script that will add BPM tags to your collection.
It runs one process per CPU Core to make the process faster. Additionally, it uses no temporary files and it capable of detecting whether a file is already tagged.
Additionally, I've discovered that FLAC sometimes has both ID3 and VorbisComment inside. This script updates both.
```
#!/bin/bash
function display_help() {
cat <<-HELP
Recursive BPM-writer for multicore CPUs.
It analyzes BPMs of every media file and writes a correct tag there.
Usage: $(basename "$0") path [...]
HELP
exit 0
}
[ $# -lt 1 ] && display_help
#=== Requirements
requires="bpmcount mid3v2 vorbiscomment metaflac"
which $requires > /dev/null || { echo "E: These binaries are required: $requires" >&2 ; exit 1; }
#=== Functions
function bpm_read(){
local file="$1"
local ext="${file##*.}"
declare -l ext
# Detect
{ case "$ext" in
'mp3') mid3v2 -l "$file" ;;
'ogg') vorbiscomment -l "$file" ;;
'flac') metaflac --export-tags-to=- "$file" ;;
esac ; } | fgrep 'BPM=' | cut -d'=' -f2
}
function bpm_write(){
local file="$1"
local bpm="${2%%.*}"
local ext="${file##*.}"
declare -l ext
echo "BPM=$bpm @$file"
# Write
case "$ext" in
'mp3') mid3v2 --TBPM "$bpm" "$file" ;;
'ogg') vorbiscomment -a -t "BPM=$bpm" "$file" ;;
'flac') metaflac --set-tag="BPM=$bpm" "$file"
mid3v2 --TBPM "$bpm" "$file" # Need to store to ID3 as well :(
;;
esac
}
#=== Process
function oneThread(){
local file="$1"
#=== Check whether there's an existing BPM
local bpm=$(bpm_read "$file")
[ "$bpm" != '' ] && return 0 # there's a nonempty BPM tag
#=== Detect a new BPM
# Detect a new bpm
local bpm=$(bpmcount "$file" | grep '^[0-9]' | cut -f1)
[ "$bpm" == '' ] && { echo "W: Invalid BPM '$bpm' detected @ $file" >&2 ; return 0 ; } # problems
# Write it
bpm_write "$file" "${bpm%%.*}" >/dev/null
}
NUMCPU="$(grep ^processor /proc/cpuinfo | wc -l)"
find $@ -type f -regextype posix-awk -iregex '.*\.(mp3|ogg|flac)' \
| while read file ; do
[ `jobs -p | wc -l` -ge $NUMCPU ] && wait
echo "$file"
oneThread "$file" &
done
```
Enjoy! :) | This is a command-line tool to detect the BPM and put it in the FLAC file tags:
<http://www.pogo.org.uk/~mark/bpm-tools/> |
129,041 | Amarok 2 can search through music collection using ID3v2 tag's 'bpm' field. That would be *very* nice to retag the entire music collection so I can find the 'mood' of the track I like.
However I've not found any beat-detection software that could have helped me. Have you ever used one? CLI, preferably. Also I'm interested if there's anything alike for tagging FLACs with the same 'bpm' field.
Thanks! :)
P.S. I'm aware there's a nice moodbar feature, however it's useless for searching. | 2010/04/09 | [
"https://superuser.com/questions/129041",
"https://superuser.com",
"https://superuser.com/users/8382/"
] | This is a command-line tool to detect the BPM and put it in the FLAC file tags:
<http://www.pogo.org.uk/~mark/bpm-tools/> | I found another tool for tagging MP3 files with the correct BPM value.
It's called [BPMDetect](http://sourceforge.net/projects/bpmdetect/). Open-source. QT libs so works fine under Gnome. Comes with a GUI but can be compiled as a console only version (run "scons console=1" as stated in the readme.txt).
Otherwise, in the end, i've too used the "bpmcount" from BpmDJ as i had difficulties to compile BPMDetect on a 64 bits Ubuntu host (due to the fmodex dependency). So i took the (very cool and well-written) shell script above (see below), the "bpmcount" binary extracted from the [x64 .rpm][3] available on the BpmDJ website (i've just extract the .rpm with
```
pm2cpio bpmdj-4.2.pl2-0.x86_64.rpm|cpio -idv
```
and it worked like a charm. I just had to modify the above script as, out of the box, it weren't working on my side (problem with stdout / stderr of the bpmcount binary). My modification is about file redirection :
```
local bpm=$(bpmcount "$file" 3>&1 1>/dev/null 2>&3 | grep '^[0-9]' | cut -f1)
``` |
129,041 | Amarok 2 can search through music collection using ID3v2 tag's 'bpm' field. That would be *very* nice to retag the entire music collection so I can find the 'mood' of the track I like.
However I've not found any beat-detection software that could have helped me. Have you ever used one? CLI, preferably. Also I'm interested if there's anything alike for tagging FLACs with the same 'bpm' field.
Thanks! :)
P.S. I'm aware there's a nice moodbar feature, however it's useless for searching. | 2010/04/09 | [
"https://superuser.com/questions/129041",
"https://superuser.com",
"https://superuser.com/users/8382/"
] | At the site DaveParillo suggested I've found [BpmDj](http://bpmdj.yellowcouch.org/measuring-tempo.html) project. It has a `bpmcount` executable that calculates the bpm very nice: it handles mp3 as well as flac:
```
161.135 Metallica/2008 - Death Magnetic/01-That Was Just Your Life.flac
63.5645 Doom3.mp3
```
The only thing that's left is to retag the collection. I'll update this answer whenever I succeed.
Thanks! :)
---
**Step 1**
Run `bpmcount` against the entire collection and store the results into a textfile.
The problem is that `bpmcount` crashes from time to time and tries to eat up to 2GB of memory when it processes several files so we should feed it with filenames one by one. Like this:
```
musicdir='/home/ootync/music'
find "$musicdir" -iregex ".*\.\(mp3\|ogg\|flac\|ape\)" -exec bpmcount {} \; \
| fgrep "$musicdir" > "$musicdir/BPMs.txt"
```
---
**Step 2**
We'll need some additional packages: `apt-get install vorbis-tools flac python-mutagen`.
Now have a look at how the 'bpm' tag can be added:
```
mid3v2 --TBPM 100 doom3.mp3
vorbiscomment -a -t "BPM=100" mother.ogg
metaflac --set-tag="BPM=100" metallica.flac
```
Alas, I have no \*.ape tracks
Now we have the BPMs and the entire collection should be retagged. Here's the script:
```
cat "$musicdir/BPMs.txt" | while read bpm file ; do
bpm=`printf "%.0f" "$bpm"` ;
case "$file" in
*.mp3) mid3v2 --TBPM "$bpm" "$file" > /dev/null ;;
*.ogg) vorbiscomment -a -t "BPM=$bpm" "$file" ;;
*.flac) metaflac --set-tag="BPM=$bpm" "$file" ;;
esac
done
```
---
**Step 2.1 Revisited**
Here's a script that will add BPM tags to your collection.
It runs one process per CPU Core to make the process faster. Additionally, it uses no temporary files and it capable of detecting whether a file is already tagged.
Additionally, I've discovered that FLAC sometimes has both ID3 and VorbisComment inside. This script updates both.
```
#!/bin/bash
function display_help() {
cat <<-HELP
Recursive BPM-writer for multicore CPUs.
It analyzes BPMs of every media file and writes a correct tag there.
Usage: $(basename "$0") path [...]
HELP
exit 0
}
[ $# -lt 1 ] && display_help
#=== Requirements
requires="bpmcount mid3v2 vorbiscomment metaflac"
which $requires > /dev/null || { echo "E: These binaries are required: $requires" >&2 ; exit 1; }
#=== Functions
function bpm_read(){
local file="$1"
local ext="${file##*.}"
declare -l ext
# Detect
{ case "$ext" in
'mp3') mid3v2 -l "$file" ;;
'ogg') vorbiscomment -l "$file" ;;
'flac') metaflac --export-tags-to=- "$file" ;;
esac ; } | fgrep 'BPM=' | cut -d'=' -f2
}
function bpm_write(){
local file="$1"
local bpm="${2%%.*}"
local ext="${file##*.}"
declare -l ext
echo "BPM=$bpm @$file"
# Write
case "$ext" in
'mp3') mid3v2 --TBPM "$bpm" "$file" ;;
'ogg') vorbiscomment -a -t "BPM=$bpm" "$file" ;;
'flac') metaflac --set-tag="BPM=$bpm" "$file"
mid3v2 --TBPM "$bpm" "$file" # Need to store to ID3 as well :(
;;
esac
}
#=== Process
function oneThread(){
local file="$1"
#=== Check whether there's an existing BPM
local bpm=$(bpm_read "$file")
[ "$bpm" != '' ] && return 0 # there's a nonempty BPM tag
#=== Detect a new BPM
# Detect a new bpm
local bpm=$(bpmcount "$file" | grep '^[0-9]' | cut -f1)
[ "$bpm" == '' ] && { echo "W: Invalid BPM '$bpm' detected @ $file" >&2 ; return 0 ; } # problems
# Write it
bpm_write "$file" "${bpm%%.*}" >/dev/null
}
NUMCPU="$(grep ^processor /proc/cpuinfo | wc -l)"
find $@ -type f -regextype posix-awk -iregex '.*\.(mp3|ogg|flac)' \
| while read file ; do
[ `jobs -p | wc -l` -ge $NUMCPU ] && wait
echo "$file"
oneThread "$file" &
done
```
Enjoy! :) | To get @meridius' solution working on my Mac I had to do a bit of extra legwork and modify the script a bit:
```
# Let's install bpm-tools
git clone http://www.pogo.org.uk/~mark/bpm-tools.git
cd bpm-tools
make && make install
# There will be errors, but they did not affect the result
# The following three lines could be replaced by including this directory in your $PATH
ln -s <absolute path to bpm-tools>/bpm /usr/local/bin/bpm
ln -s <absolute path to bpm-tools>/bpm-tag /usr/local/bin/bpm-tag
ln -s <absolute path to bpm-tools>/bpm-graph /usr/local/bin/bpm-graph
cd ..
# Time to install a bunch of GNU tools
# Not all of these packages are strictly necessary for this script, but I decided I wanted the whole GNU toolchain in order to avoid this song-and-dance in the future
brew install coreutils findutils gnu-tar gnu-sed gawk gnutls gnu-indent gnu-getopt bash flac vorbis-tools
brew tap homebrew/dupes; brew install grep
# Now for Mutagen (contains mid3v2)
git clone https://github.com/nex3/mutagen.git
cd mutagen
./setup.py build
sudo ./setup.py install
# There will be errors, but they did not affect the result
cd ..
```
Then I had to modify the script to point to the GNU versions of everything, and a few other tweaks:
```
#!/usr/local/bin/bash
# ================================= FUNCTIONS =================================
function help() {
less <<< 'BPMWRAP
Description:
This BASH script is a wrapper for bpm-tag utility of bpm-tools and several
audio tagging utilities. The purpose is to make BPM (beats per minute)
tagging as easy as possible.
Default behaviour is to look through working directory for *.mp3 files
and compute and print their BPM in the following manner:
[current (if any)] [computed] [filename]
Usage:
bpmwrap [options] [directory or filenames]
Options:
You can specify files to process by one of these ways:
1) state files and/or directories containing them after options
2) specify --import file
3) specify --input file
With either way you still can filter the resulting list using --type option(s).
Remember that the script will process only mp3 files by default, unless
specified otherwise!
-i, --import file
Use this option to set BPM tag for all files in given file instead of
computing it. Expected format of every row is BPM number and absolute path
to filename separated by semicolon like so:
145;/home/trinity/music/Apocalyptica/07 beyond time.mp3
Remember to use --write option too.
-n, --input file
Use this option to give the script list of FILES to process INSTEAD of paths
where to look for them. Each row whould have one absolute path.
This will bypass the searching part and is that way useful when you want
to process large number of files several times. Like when you are not yet
sure what BPM limits to set. Extension filtering will still work.
-o, --output file
Save output also to a file.
-l, --list-save file
Save list of files about to get processed. You can use this list later
as a file for --input option.
-t, --type filetype
Extension of file type to work with. Defaults to mp3. Can be specified
multiple times for more filetypes. Currently supported are mp3 ogg flac.
-e, --existing-only
Only show BPM for files that have it. Do NOT compute new one.
-w, --write
Write computed BPM to audio file but do NOT overwrite existing value.
-f, --force
Write computed BPM to audio file even if it already has one. Aplicable only
with --write option.
-m, --min minbpm
Set minimal BPM to look for when computing. Defaults to bpm-tag minimum 84.
-x, --max maxbpm
Set maximal BPM to look for when computing. Defaults to bpm-tag maximum 146.
-v, --verbose
Show "progress" messages.
-c, --csv-friendly
Use semicolon (;) instead of space to separate output columns.
-h, --help
Show this help.
Note:
Program bpm-tag (on whis is this script based) is looking only for lowercase
file extensions. If you get 0 (zero) BPM, this should be the case. So just
rename the file.
License:
GPL V2
Links:
bpm-tools (http://www.pogo.org.uk/~mark/bpm-tools/)
Dependencies:
bpm-tag mid3v2 vorbiscomment metaflac
Author:
Martin Lukeš (martin.meridius@gmail.com)
Based on work of kolypto (http://superuser.com/a/129157/137326)
'
}
# Usage: result=$(inArray $needle haystack[@])
# @param string needle
# @param array haystack
# @returns int (1 = NOT / 0 = IS) in array
function inArray() {
needle="$1"
haystack=("${!2}")
out=1
for e in "${haystack[@]}" ; do
if [[ "$e" = "$needle" ]] ; then
out=0
break
fi
done
echo $out
}
# Usage: result=$(implode $separator array[@])
# @param char separator
# @param array array to implode
# @returns string separated array elements
function implode() {
separator="$1"
array=("${!2}")
IFSORIG=$IFS
IFS="$separator"
echo "${array[*]}"
IFS=$IFSORIG
}
# @param string file
# @returns int BPM value
function getBpm() {
local file="$1"
local ext="${file##*.}"
declare -l ext # convert to lowercase
{ case "$ext" in
'mp3') mid3v2 -l "$file" ;;
'ogg') vorbiscomment -l "$file" ;;
'flac') metaflac --export-tags-to=- "$file" ;;
esac ; } | fgrep 'BPM=' -a | cut -d'=' -f2
}
# @param string file
# @param int BPM value
function setBpm() {
local file="$1"
local bpm="${2%%.*}"
local ext="${file##*.}"
declare -l ext # convert to lowercase
case "$ext" in
'mp3') mid3v2 --TBPM "$bpm" "$file" ;;
'ogg') vorbiscomment -a -t "BPM=$bpm" "$file" ;;
'flac') metaflac --set-tag="BPM=$bpm" "$file"
mid3v2 --TBPM "$bpm" "$file" # Need to store to ID3 as well :(
;;
esac
}
# # @param string file
# # @returns int BPM value
function computeBpm() {
local file="$1"
local m_opt=""
[ ! -z "$m" ] && m_opt="-m $m"
local x_opt=""
[ ! -z "$x" ] && x_opt="-x $x"
local row=$(bpm-tag -fn $m_opt $x_opt "$file" 2>&1 | fgrep "$file")
echo $(echo "$row" \
| gsed -r 's/.+ ([0-9]+\.[0-9]{3}) BPM/\1/' \
| gawk '{printf("%.0f\n", $1)}')
}
# @param string file
# @param int file number
# @param int BPM from file list given by --import option
function oneThread() {
local file="$1"
local filenumber="$2"
local bpm_hard="$3"
local bpm_old=$(getBpm "$file")
[ -z "$bpm_old" ] && bpm_old="NONE"
if [ "$e" ] ; then # only show existing
myEcho "$filenumber/$NUMFILES${SEP}$bpm_old${SEP}$file"
else # compute new one
if [ "$bpm_hard" ] ; then
local bpm_new="$bpm_hard"
else
local bpm_new=$(computeBpm "$file")
fi
[ "$w" ] && { # write new one
if [[ ! ( ("$bpm_old" != "NONE") && ( -z "$f" ) ) ]] ; then
setBpm "$file" "$bpm_new"
else
[ "$v" ] && myEcho "Non-empty old BPM value, skipping ..."
fi
}
myEcho "$filenumber/$NUMFILES${SEP}$bpm_old${SEP}$bpm_new${SEP}$file"
fi
}
function myEcho() {
[ "$o" ] && echo -e "$1" >> "$o"
echo -e "$1"
}
# ================================== OPTIONS ==================================
eval set -- $(/usr/local/Cellar/gnu-getopt/1.1.6/bin/getopt -n $0 -o "-i:n:o:l:t:ewfm:x:vch" \
-l "import:,input:,output:,list-save:,type:,existing-only,write,force,min:,max:,verbose,csv-friendly,help" -- "$@")
declare i n o l t e w f m x v c h
declare -a INPUTFILES
declare -a INPUTTYPES
while [ $# -gt 0 ] ; do
case "$1" in
-i|--import) shift ; i="$1" ; shift ;;
-n|--input) shift ; n="$1" ; shift ;;
-o|--output) shift ; o="$1" ; shift ;;
-l|--list-save) shift ; l="$1" ; shift ;;
-t|--type) shift ; INPUTTYPES=("${INPUTTYPES[@]}" "$1") ; shift ;;
-e|--existing-only) e=1 ; shift ;;
-w|--write) w=1 ; shift ;;
-f|--force) f=1 ; shift ;;
-m|--min) shift ; m="$1" ; shift ;;
-x|--max) shift ; x="$1" ; shift ;;
-v|--verbose) v=1 ; shift ;;
-c|--csv-friendly) c=1 ; shift ;;
-h|--help) h=1 ; shift ;;
--) shift ;;
-*) echo "bad option '$1'" ; exit 1 ;; #FIXME why this exit isn't fired?
*) INPUTFILES=("${INPUTFILES[@]}" "$1") ; shift ;;
esac
done
# ================================= DEFAULTS ==================================
#NOTE Remove what requisities you don't need but don't try to use them after!
# always mp3/flac ogg flac
REQUIRES="bpm-tag mid3v2 vorbiscomment metaflac"
which $REQUIRES > /dev/null || { myEcho "These binaries are required: $REQUIRES" >&2 ; exit 1; }
[ "$h" ] && {
help
exit 0
}
[[ $m && $x && ( $m -ge $x ) ]] && {
myEcho "Minimal BPM can't be bigger than NOR same as maximal BPM!"
exit 1
}
[[ "$i" && "$n" ]] && {
echo "You cannot specify both -i and -n options!"
exit 1
}
[[ "$i" && ( "$m" || "$x" ) ]] && {
echo "You cannot use -m nor -x option with -i option!"
exit 1
}
[ "$e" ] && {
[[ "$w" || "$f" ]] && {
echo "With -e option you don't have any value to write!"
exit 1
}
[[ "$m" || "$x" ]] && {
echo "With -e option you don't have any value to count!"
exit 1
}
}
for file in "$o" "$l" ; do
if [ -f "$file" ] ; then
while true ; do
read -n1 -p "Do you want to overwrite existing file ${file}? (Y/n): " key
case "$key" in
y|Y|"") echo "" > "$file" ; break ;;
n|N) exit 0 ;;
esac
echo ""
done
echo ""
fi
done
[ ${#INPUTTYPES} -eq 0 ] && INPUTTYPES=("mp3")
# NUMCPU="$(ggrep ^processor /proc/cpuinfo | wc -l)"
NUMCPU="$(sysctl -a | ggrep machdep.cpu.core_count | gsed -r 's/(.*)([0-9]+)(.*)/\2/')"
LASTPID=0
TYPESALLOWED=("mp3" "ogg" "flac")
# declare -A BPMIMPORT # array of BPMs from --import file, keys are file names
declare -A BPMIMPORT # array of BPMs from --import file, keys are file names
for type in "${INPUTTYPES[@]}" ; do
[[ $(inArray $type TYPESALLOWED[@]) -eq 1 ]] && {
myEcho "Filetype $type is not one of allowed types (${TYPESALLOWED[@]})!"
exit 1
}
done
### here are three ways how to pass files to the script...
if [ "$i" ] ; then # just parse given file list and set BPM to listed files
if [ -f "$i" ] ; then
# myEcho "Setting BPM tags from given file ..."
while read row ; do
bpm="${row%%;*}"
file="${row#*;}"
ext="${file##*.}"
ext="${ext,,}" # convert to lowercase
if [ -f "$file" ] ; then
if [ $(inArray $ext INPUTTYPES[@]) -eq 0 ] ; then
FILES=("${FILES[@]}" "$file")
BPMIMPORT["$file"]="$bpm"
else
myEcho "Skipping file on row $rownumber (unwanted filetype $ext) ... $file"
fi
else
myEcho "Skipping non-existing file $file"
fi
done < "$i"
else
myEcho "Given import file does not exists!"
exit 1
fi
elif [ "$n" ] ; then # get files from file list
if [ -f "$n" ] ; then
rownumber=1
while read file ; do
if [ -f "$file" ] ; then
ext="${file##*.}"
ext="${ext,,}" # convert to lowercase
if [ $(inArray $ext INPUTTYPES[@]) -eq 0 ] ; then
FILES=("${FILES[@]}" "$file")
else
myEcho "Skipping file on row $rownumber (unwanted filetype $ext) ... $file"
fi
else
myEcho "Skipping file on row $rownumber (non-existing) ... $file"
fi
let rownumber++
done < "$n"
unset rownumber
else
myEcho "Given input file $n does not exists!"
exit 1
fi
else # get files from given parameters
[ ${#INPUTFILES[@]} -eq 0 ] && INPUTFILES=`pwd`
for file in "${INPUTFILES[@]}" ; do
[ ! -e "$file" ] && {
myEcho "File or directory $file does not exist!"
exit 1
}
done
impl_types=`implode "|" INPUTTYPES[@]`
while read file ; do
echo -ne "Creating list of files ... (${#FILES[@]}) ${file}\033[0K"\\r
FILES=("${FILES[@]}" "$file")
done < <(gfind "${INPUTFILES[@]}" -type f -regextype posix-awk -iregex ".*\.($impl_types)")
echo -e "Counted ${#FILES[@]} files\033[0K"\\r
fi
[ "$l" ] && printf '%s\n' "${FILES[@]}" > "$l"
NUMFILES=${#FILES[@]}
FILENUMBER=1
[ $NUMFILES -eq 0 ] && {
myEcho "There are no ${INPUTTYPES[@]} files in given files/paths."
exit 1
}
declare SEP=" "
[ "$c" ] && SEP=";"
# =============================== MAIN SECTION ================================
if [ "$e" ] ; then # what heading to show
myEcho "num${SEP}old${SEP}filename"
else
myEcho "num${SEP}old${SEP}new${SEP}filename"
fi
for file in "${FILES[@]}" ; do
[ `jobs -p | wc -l` -ge $NUMCPU ] && wait
[ "$v" ] && myEcho "Parsing (${FILENUMBER}/${NUMFILES})\t$file ..."
oneThread "$file" "$FILENUMBER" "${BPMIMPORT[$file]}" &
LASTPID="$!"
let FILENUMBER++
done
[ "$v" ] && myEcho "Waiting for last process ..."
wait $LASTPID
[ "$v" ] && myEcho \\n"DONE"
```
Thank you for your hard work @kolypto and @meridius.
...the pain I go through to maintain a CLI workflow and pay no money for music tools... |
129,041 | Amarok 2 can search through music collection using ID3v2 tag's 'bpm' field. That would be *very* nice to retag the entire music collection so I can find the 'mood' of the track I like.
However I've not found any beat-detection software that could have helped me. Have you ever used one? CLI, preferably. Also I'm interested if there's anything alike for tagging FLACs with the same 'bpm' field.
Thanks! :)
P.S. I'm aware there's a nice moodbar feature, however it's useless for searching. | 2010/04/09 | [
"https://superuser.com/questions/129041",
"https://superuser.com",
"https://superuser.com/users/8382/"
] | At the site DaveParillo suggested I've found [BpmDj](http://bpmdj.yellowcouch.org/measuring-tempo.html) project. It has a `bpmcount` executable that calculates the bpm very nice: it handles mp3 as well as flac:
```
161.135 Metallica/2008 - Death Magnetic/01-That Was Just Your Life.flac
63.5645 Doom3.mp3
```
The only thing that's left is to retag the collection. I'll update this answer whenever I succeed.
Thanks! :)
---
**Step 1**
Run `bpmcount` against the entire collection and store the results into a textfile.
The problem is that `bpmcount` crashes from time to time and tries to eat up to 2GB of memory when it processes several files so we should feed it with filenames one by one. Like this:
```
musicdir='/home/ootync/music'
find "$musicdir" -iregex ".*\.\(mp3\|ogg\|flac\|ape\)" -exec bpmcount {} \; \
| fgrep "$musicdir" > "$musicdir/BPMs.txt"
```
---
**Step 2**
We'll need some additional packages: `apt-get install vorbis-tools flac python-mutagen`.
Now have a look at how the 'bpm' tag can be added:
```
mid3v2 --TBPM 100 doom3.mp3
vorbiscomment -a -t "BPM=100" mother.ogg
metaflac --set-tag="BPM=100" metallica.flac
```
Alas, I have no \*.ape tracks
Now we have the BPMs and the entire collection should be retagged. Here's the script:
```
cat "$musicdir/BPMs.txt" | while read bpm file ; do
bpm=`printf "%.0f" "$bpm"` ;
case "$file" in
*.mp3) mid3v2 --TBPM "$bpm" "$file" > /dev/null ;;
*.ogg) vorbiscomment -a -t "BPM=$bpm" "$file" ;;
*.flac) metaflac --set-tag="BPM=$bpm" "$file" ;;
esac
done
```
---
**Step 2.1 Revisited**
Here's a script that will add BPM tags to your collection.
It runs one process per CPU Core to make the process faster. Additionally, it uses no temporary files and it capable of detecting whether a file is already tagged.
Additionally, I've discovered that FLAC sometimes has both ID3 and VorbisComment inside. This script updates both.
```
#!/bin/bash
function display_help() {
cat <<-HELP
Recursive BPM-writer for multicore CPUs.
It analyzes BPMs of every media file and writes a correct tag there.
Usage: $(basename "$0") path [...]
HELP
exit 0
}
[ $# -lt 1 ] && display_help
#=== Requirements
requires="bpmcount mid3v2 vorbiscomment metaflac"
which $requires > /dev/null || { echo "E: These binaries are required: $requires" >&2 ; exit 1; }
#=== Functions
function bpm_read(){
local file="$1"
local ext="${file##*.}"
declare -l ext
# Detect
{ case "$ext" in
'mp3') mid3v2 -l "$file" ;;
'ogg') vorbiscomment -l "$file" ;;
'flac') metaflac --export-tags-to=- "$file" ;;
esac ; } | fgrep 'BPM=' | cut -d'=' -f2
}
function bpm_write(){
local file="$1"
local bpm="${2%%.*}"
local ext="${file##*.}"
declare -l ext
echo "BPM=$bpm @$file"
# Write
case "$ext" in
'mp3') mid3v2 --TBPM "$bpm" "$file" ;;
'ogg') vorbiscomment -a -t "BPM=$bpm" "$file" ;;
'flac') metaflac --set-tag="BPM=$bpm" "$file"
mid3v2 --TBPM "$bpm" "$file" # Need to store to ID3 as well :(
;;
esac
}
#=== Process
function oneThread(){
local file="$1"
#=== Check whether there's an existing BPM
local bpm=$(bpm_read "$file")
[ "$bpm" != '' ] && return 0 # there's a nonempty BPM tag
#=== Detect a new BPM
# Detect a new bpm
local bpm=$(bpmcount "$file" | grep '^[0-9]' | cut -f1)
[ "$bpm" == '' ] && { echo "W: Invalid BPM '$bpm' detected @ $file" >&2 ; return 0 ; } # problems
# Write it
bpm_write "$file" "${bpm%%.*}" >/dev/null
}
NUMCPU="$(grep ^processor /proc/cpuinfo | wc -l)"
find $@ -type f -regextype posix-awk -iregex '.*\.(mp3|ogg|flac)' \
| while read file ; do
[ `jobs -p | wc -l` -ge $NUMCPU ] && wait
echo "$file"
oneThread "$file" &
done
```
Enjoy! :) | It's not Linux but may well work in Wine - I use [MixMeister BPM Analyzer](http://www.mixmeister.com/bpmanalyzer/bpmanalyzer.asp) |
129,041 | Amarok 2 can search through music collection using ID3v2 tag's 'bpm' field. That would be *very* nice to retag the entire music collection so I can find the 'mood' of the track I like.
However I've not found any beat-detection software that could have helped me. Have you ever used one? CLI, preferably. Also I'm interested if there's anything alike for tagging FLACs with the same 'bpm' field.
Thanks! :)
P.S. I'm aware there's a nice moodbar feature, however it's useless for searching. | 2010/04/09 | [
"https://superuser.com/questions/129041",
"https://superuser.com",
"https://superuser.com/users/8382/"
] | At the site DaveParillo suggested I've found [BpmDj](http://bpmdj.yellowcouch.org/measuring-tempo.html) project. It has a `bpmcount` executable that calculates the bpm very nice: it handles mp3 as well as flac:
```
161.135 Metallica/2008 - Death Magnetic/01-That Was Just Your Life.flac
63.5645 Doom3.mp3
```
The only thing that's left is to retag the collection. I'll update this answer whenever I succeed.
Thanks! :)
---
**Step 1**
Run `bpmcount` against the entire collection and store the results into a textfile.
The problem is that `bpmcount` crashes from time to time and tries to eat up to 2GB of memory when it processes several files so we should feed it with filenames one by one. Like this:
```
musicdir='/home/ootync/music'
find "$musicdir" -iregex ".*\.\(mp3\|ogg\|flac\|ape\)" -exec bpmcount {} \; \
| fgrep "$musicdir" > "$musicdir/BPMs.txt"
```
---
**Step 2**
We'll need some additional packages: `apt-get install vorbis-tools flac python-mutagen`.
Now have a look at how the 'bpm' tag can be added:
```
mid3v2 --TBPM 100 doom3.mp3
vorbiscomment -a -t "BPM=100" mother.ogg
metaflac --set-tag="BPM=100" metallica.flac
```
Alas, I have no \*.ape tracks
Now we have the BPMs and the entire collection should be retagged. Here's the script:
```
cat "$musicdir/BPMs.txt" | while read bpm file ; do
bpm=`printf "%.0f" "$bpm"` ;
case "$file" in
*.mp3) mid3v2 --TBPM "$bpm" "$file" > /dev/null ;;
*.ogg) vorbiscomment -a -t "BPM=$bpm" "$file" ;;
*.flac) metaflac --set-tag="BPM=$bpm" "$file" ;;
esac
done
```
---
**Step 2.1 Revisited**
Here's a script that will add BPM tags to your collection.
It runs one process per CPU Core to make the process faster. Additionally, it uses no temporary files and it capable of detecting whether a file is already tagged.
Additionally, I've discovered that FLAC sometimes has both ID3 and VorbisComment inside. This script updates both.
```
#!/bin/bash
function display_help() {
cat <<-HELP
Recursive BPM-writer for multicore CPUs.
It analyzes BPMs of every media file and writes a correct tag there.
Usage: $(basename "$0") path [...]
HELP
exit 0
}
[ $# -lt 1 ] && display_help
#=== Requirements
requires="bpmcount mid3v2 vorbiscomment metaflac"
which $requires > /dev/null || { echo "E: These binaries are required: $requires" >&2 ; exit 1; }
#=== Functions
function bpm_read(){
local file="$1"
local ext="${file##*.}"
declare -l ext
# Detect
{ case "$ext" in
'mp3') mid3v2 -l "$file" ;;
'ogg') vorbiscomment -l "$file" ;;
'flac') metaflac --export-tags-to=- "$file" ;;
esac ; } | fgrep 'BPM=' | cut -d'=' -f2
}
function bpm_write(){
local file="$1"
local bpm="${2%%.*}"
local ext="${file##*.}"
declare -l ext
echo "BPM=$bpm @$file"
# Write
case "$ext" in
'mp3') mid3v2 --TBPM "$bpm" "$file" ;;
'ogg') vorbiscomment -a -t "BPM=$bpm" "$file" ;;
'flac') metaflac --set-tag="BPM=$bpm" "$file"
mid3v2 --TBPM "$bpm" "$file" # Need to store to ID3 as well :(
;;
esac
}
#=== Process
function oneThread(){
local file="$1"
#=== Check whether there's an existing BPM
local bpm=$(bpm_read "$file")
[ "$bpm" != '' ] && return 0 # there's a nonempty BPM tag
#=== Detect a new BPM
# Detect a new bpm
local bpm=$(bpmcount "$file" | grep '^[0-9]' | cut -f1)
[ "$bpm" == '' ] && { echo "W: Invalid BPM '$bpm' detected @ $file" >&2 ; return 0 ; } # problems
# Write it
bpm_write "$file" "${bpm%%.*}" >/dev/null
}
NUMCPU="$(grep ^processor /proc/cpuinfo | wc -l)"
find $@ -type f -regextype posix-awk -iregex '.*\.(mp3|ogg|flac)' \
| while read file ; do
[ `jobs -p | wc -l` -ge $NUMCPU ] && wait
echo "$file"
oneThread "$file" &
done
```
Enjoy! :) | While it is not just a tool like you say you are looking for, [Banshee media player](http://banshee-project.org/ "Banshee website") can detect bpm.
I use Banshee for all my music playing, organisation and synchronizing to portable players.
I'm not affiliated, but I like the program the best of all that I've tried.
It can also generate "smart playlists" based on all sorts of properties of the tracks, including bpm.
There is an extension which analyses all sorts of things about the song, and will find similar songs to the one you're playing. It's called [Mirage](http://hop.at/mirage/ "Mirage website"), and I used it for a while, but I don't any more, as I've created a number of playlists of ones that suit various moods (not necessarily similar according to Mirage).
I don't know if Banshee will save the bpm it detected back into the ID3v2 "bpm" tag of the file. If anyone knows how to easily check the bpm tag from outside the program I'll check. |
17,441,695 | I'm trying to send some data to a servlet and then to get back a `.xls` file from it. In order to do this, I'm using jquery, but I'm facing some strange issues. Let me explain.
Here is how I'm sending the data to the servlet and how I'm supposed to get the generated file back:
```
jQuery.download = function(url, data, method){
//url and data options required
if( url && data ){
//data can be string of parameters or array/object
data = typeof data == 'string' ? data : jQuery.param(data);
//split params into form inputs
var inputs = '';
jQuery.each(data.split('&'), function(){
var pair = this.split('=');
inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />';
});
//send request
jQuery('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
.appendTo('body').submit().remove();
};
};
download = function () {
var a = this.mainData();
var b = JSON.stringify(a);
console.log(b);
what = "test",
obj = $.extend({WrJOB: "xlsExport", mainData: b}, tJS.getCommonPostData());
var data = $.param(obj); //.replace(/\+/g, '%20'); its just a test
$.download('/myapp/AppProxy', data);
},
```
A button in my html is calling the `download` function wich is sending some JSON data to the servlet. In my case it is `var b`.
I'm pretty sure that there is an encoding issue, but I have no idea how to fix it.
Please, help me with this strange problem, I'm already working many hours on it and I can not find a solution. | 2013/07/03 | [
"https://Stackoverflow.com/questions/17441695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1773265/"
] | >
> Now i create dao of b, since b has all the data. But the table B has only created with data, A is never created. Kindly could some one help?
>
>
>
Right. You need to create the `A` items using:
```
for (A a : b.aees) {
aDao.create(a);
}
```
ORMLite does not automatically create those for you.
You might take a look a the source code of the [foreign-collection example program](https://github.com/j256/ormlite-jdbc/tree/master/src/test/java/com/j256/ormlite/examples/foreignCollection). | You have to override the DAO of the B class, so when an object B is created or updated, the objects in the collection to be also updated.
Take a look at this question: [Collections in ORMLite](https://stackoverflow.com/questions/5524503/collections-in-ormlite). |
17,441,695 | I'm trying to send some data to a servlet and then to get back a `.xls` file from it. In order to do this, I'm using jquery, but I'm facing some strange issues. Let me explain.
Here is how I'm sending the data to the servlet and how I'm supposed to get the generated file back:
```
jQuery.download = function(url, data, method){
//url and data options required
if( url && data ){
//data can be string of parameters or array/object
data = typeof data == 'string' ? data : jQuery.param(data);
//split params into form inputs
var inputs = '';
jQuery.each(data.split('&'), function(){
var pair = this.split('=');
inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />';
});
//send request
jQuery('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
.appendTo('body').submit().remove();
};
};
download = function () {
var a = this.mainData();
var b = JSON.stringify(a);
console.log(b);
what = "test",
obj = $.extend({WrJOB: "xlsExport", mainData: b}, tJS.getCommonPostData());
var data = $.param(obj); //.replace(/\+/g, '%20'); its just a test
$.download('/myapp/AppProxy', data);
},
```
A button in my html is calling the `download` function wich is sending some JSON data to the servlet. In my case it is `var b`.
I'm pretty sure that there is an encoding issue, but I have no idea how to fix it.
Please, help me with this strange problem, I'm already working many hours on it and I can not find a solution. | 2013/07/03 | [
"https://Stackoverflow.com/questions/17441695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1773265/"
] | You have to override the DAO of the B class, so when an object B is created or updated, the objects in the collection to be also updated.
Take a look at this question: [Collections in ORMLite](https://stackoverflow.com/questions/5524503/collections-in-ormlite). | i was facing the same problem. My json was like:
```
{
"parent":{
"name":"ABC",
"children":[
{"childName":"1"},
{"childName":"2"},
{"childName":"3"}
]
}
}
```
i resolved the issue like this:
```
Parent parent = new Parent();
parent.setName("ABC");
while(get children one by one from json data)
{
childrenArray.add(new Child(its Name));
}
parentDAO.create(parent);
for(Child child : childrenArray)
{
child.setParent(parent);
childDAO.create(child);
}
``` |
17,441,695 | I'm trying to send some data to a servlet and then to get back a `.xls` file from it. In order to do this, I'm using jquery, but I'm facing some strange issues. Let me explain.
Here is how I'm sending the data to the servlet and how I'm supposed to get the generated file back:
```
jQuery.download = function(url, data, method){
//url and data options required
if( url && data ){
//data can be string of parameters or array/object
data = typeof data == 'string' ? data : jQuery.param(data);
//split params into form inputs
var inputs = '';
jQuery.each(data.split('&'), function(){
var pair = this.split('=');
inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />';
});
//send request
jQuery('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
.appendTo('body').submit().remove();
};
};
download = function () {
var a = this.mainData();
var b = JSON.stringify(a);
console.log(b);
what = "test",
obj = $.extend({WrJOB: "xlsExport", mainData: b}, tJS.getCommonPostData());
var data = $.param(obj); //.replace(/\+/g, '%20'); its just a test
$.download('/myapp/AppProxy', data);
},
```
A button in my html is calling the `download` function wich is sending some JSON data to the servlet. In my case it is `var b`.
I'm pretty sure that there is an encoding issue, but I have no idea how to fix it.
Please, help me with this strange problem, I'm already working many hours on it and I can not find a solution. | 2013/07/03 | [
"https://Stackoverflow.com/questions/17441695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1773265/"
] | >
> Now i create dao of b, since b has all the data. But the table B has only created with data, A is never created. Kindly could some one help?
>
>
>
Right. You need to create the `A` items using:
```
for (A a : b.aees) {
aDao.create(a);
}
```
ORMLite does not automatically create those for you.
You might take a look a the source code of the [foreign-collection example program](https://github.com/j256/ormlite-jdbc/tree/master/src/test/java/com/j256/ormlite/examples/foreignCollection). | i was facing the same problem. My json was like:
```
{
"parent":{
"name":"ABC",
"children":[
{"childName":"1"},
{"childName":"2"},
{"childName":"3"}
]
}
}
```
i resolved the issue like this:
```
Parent parent = new Parent();
parent.setName("ABC");
while(get children one by one from json data)
{
childrenArray.add(new Child(its Name));
}
parentDAO.create(parent);
for(Child child : childrenArray)
{
child.setParent(parent);
childDAO.create(child);
}
``` |
48,680,733 | I created a for-loop to form a linear model with features and remove one feature every one cycle of the for-loop. Using this for loop, I want to take-out pvalues of each features.
Below is my fake data and the for loop.
```
#fake data
z <- c(0.91629, 1.32580, -1.09940, 0.33601, 0.28795, 1.59050, 0.68193, -1.5944, 0.32160, -1.30810, -3.8569)
x <- c(0.35391, -0.84966, 0.17623, 2.39960, -0.50007, 0.70983, 0.61825, -1.7655, -0.44426, 0.01343, 3.0556)
c <- c(1.32060, -0.29756, 0.60097, 1.91580, -0.13838, -1.77920, -0.625670, -0.30979, 0.86718, -0.27289, 2.9607)
v <- c(-0.49864, -0.61754, 0.17977, 1.17100, 0.77713, -0.50157, 0.021347, 1.32660, 0.11048, 0.79202, -1.3138)
b <- c(-0.39620, 1.30740, 1.09030, 0.45662, 0.48579, -0.17219, 0.387560, -0.98518, -0.47283, 0.27918, 8.7742)
n <- c(-0.79369, -0.050101, 0.89823, 0.80320, 0.32670, 0.39969, -0.547320, -0.23154, -0.46198, -0.25495, 1.1776)
L <- data.frame(rbind(z,x,c,v,b,n))
names(L) <- c("P1", "P2", "P3", "P4", "P5", "P6", "P7", "P8", "P9","P10", "SysResponse")
L
#my function
Remove <- c("P1", "P5", "P2", "P8", "P9", "P4", "P3", "P6", "P7", "P10")
for (i in 1:length(Remove)){
fit3 <- lm(as.formula(paste('SysResponse~',paste(Remove, collapse="+"))), data=L);
b <- summary(fit3)$coefficients[,4]; # p-value
print(b)
Remove = Remove[-1];
}
```
This will give you the pvalues of individual features in each steps.
(Ignore the Nans. I just failed to make a good fake data.)
What I am trying to do here is instead of throw the bunch of numbers as my output, I would like to create a table with the pvalues of each features in each step.
so my output should look like something like this:
```
D1 D2 D3 ..... D10
P1 1 . .
P2 2 6 22
P3 3 8 45
P4 4 15 64
P5 5 17 .
P6 6 15 353
P7 7 11 12
P8 8 4 45
P9 9 96 23
P10 10 12 12
```
because P1 and P5 will be removed.
Please help me here, I'm stuck | 2018/02/08 | [
"https://Stackoverflow.com/questions/48680733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7472392/"
] | Is this what you want?
```
Remove <- c("P1", "P5", "P2", "P8", "P9", "P4", "P3", "P6", "P7", "P10")
b <- matrix(rep(NA, 100), nrow = 10)
for (i in 1:length(Remove)){
fit3 <- lm(as.formula(paste('SysResponse~',paste(Remove, collapse="+"))), data=L)
b[i,] <- if(length(summary(fit3)$coefficients[,4]) == 10){summary(fit3)$coefficients[,4]}else{
c(rep(NA, 10-length(summary(fit3)$coefficients[,4])), summary(fit3)$coefficients[,4])
}
#print(b)
Remove = Remove[-1]
}
> b
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] NA NA NA NA NaN NaN NaN NaN NaN NaN
[2,] NA NA NA NA NaN NaN NaN NaN NaN NaN
[3,] NA NA NA NA NaN NaN NaN NaN NaN NaN
[4,] NA NA NA NA NaN NaN NaN NaN NaN NaN
[5,] NA NA NA NA NaN NaN NaN NaN NaN NaN
[6,] NA NA NA NA NaN NaN NaN NaN NaN NaN
[7,] NA NA NA NA NA 0.05965568 0.01732815 0.04548212 0.02498853 0.04486418
[8,] NA NA NA NA NA NA 0.53777567 0.65398542 0.73020052 0.77532750
[9,] NA NA NA NA NA NA NA 0.38472799 0.97510236 0.45831503
[10,] NA NA NA NA NA NA NA NA 0.30062420 0.37796597
``` | Try this code:
```
pvalue3d <- NULL
for (i in 1:length(Remove)){
fit3 <- lm(as.formula(paste('SysResponse~',paste(Remove, collapse="+"))), data=train2);
b <- summary(fit3)$coefficients[,4]; # p-value
pvalue3d <- rbind(pvalue3d, b);
Remove = Remove[-1];
}
```
PS: in your example train2 is not defined |
11,863 | When cooking spaghetti carbonara, I mix the pasta, bacon, cheese and egg yolks together with a scoop. This technique frequently results in mashed spaghetti as well as bacon clustering.
What could I do different? | 2011/02/06 | [
"https://cooking.stackexchange.com/questions/11863",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/-1/"
] | In addition to the tips from Joe's great grandmother, you might want to try and rinse the pasta thoroughly with some lukewarm water after cooking it al dente. That way you rinse off the remaining starch and you prevent the pasta from cooking any further. Rinsing results in firmer pasta that is silky smooth and doesn't clump together or get mashed up. Your scoop or tongs will slither right through without damaging the pasta. :) | Here's how I learned from my great grandmother:
* cook the bacon/salt pork/home/whatever 'til crispy
* beat the eggs (she used whole eggs) with a little black pepper
* drain the cooked pasta, and immediately mix the pasta with the eggs; if it's too dry, add some of the pasta water.
* Add fried pork product and mix a litle more.
* sprinkle cheese on top while serving.
...
But I've also been known to mix everything but the pasta together (maybe not the pork if it's still too hot), and then toss it all together while the pasta's still hot, kinda like if you were tossing to mix the dressing on a salad. (tongs work really well)
...
Either way, you do end up with the fried pork bits at the bottom of the pot you were mixing in. The easy way around this is to save 1/3 to 1/2 of it, and sprinkle it over the top when serving. |
11,863 | When cooking spaghetti carbonara, I mix the pasta, bacon, cheese and egg yolks together with a scoop. This technique frequently results in mashed spaghetti as well as bacon clustering.
What could I do different? | 2011/02/06 | [
"https://cooking.stackexchange.com/questions/11863",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/-1/"
] | Here's how I learned from my great grandmother:
* cook the bacon/salt pork/home/whatever 'til crispy
* beat the eggs (she used whole eggs) with a little black pepper
* drain the cooked pasta, and immediately mix the pasta with the eggs; if it's too dry, add some of the pasta water.
* Add fried pork product and mix a litle more.
* sprinkle cheese on top while serving.
...
But I've also been known to mix everything but the pasta together (maybe not the pork if it's still too hot), and then toss it all together while the pasta's still hot, kinda like if you were tossing to mix the dressing on a salad. (tongs work really well)
...
Either way, you do end up with the fried pork bits at the bottom of the pot you were mixing in. The easy way around this is to save 1/3 to 1/2 of it, and sprinkle it over the top when serving. | You could try replacing spaghetti with rigatoni pasta.
In this way it is a lot easier to mix and you'll end up with a dish much closer to the authentic Italian carbonara recipe. |
11,863 | When cooking spaghetti carbonara, I mix the pasta, bacon, cheese and egg yolks together with a scoop. This technique frequently results in mashed spaghetti as well as bacon clustering.
What could I do different? | 2011/02/06 | [
"https://cooking.stackexchange.com/questions/11863",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/-1/"
] | Here's how I learned from my great grandmother:
* cook the bacon/salt pork/home/whatever 'til crispy
* beat the eggs (she used whole eggs) with a little black pepper
* drain the cooked pasta, and immediately mix the pasta with the eggs; if it's too dry, add some of the pasta water.
* Add fried pork product and mix a litle more.
* sprinkle cheese on top while serving.
...
But I've also been known to mix everything but the pasta together (maybe not the pork if it's still too hot), and then toss it all together while the pasta's still hot, kinda like if you were tossing to mix the dressing on a salad. (tongs work really well)
...
Either way, you do end up with the fried pork bits at the bottom of the pot you were mixing in. The easy way around this is to save 1/3 to 1/2 of it, and sprinkle it over the top when serving. | The key is water. Use the pasta water for the best flavor. This dish is mostly about timing. Do not ever rinse the pasta with water!
Also, if you are making Carbonara with anything other than Guanciale (pork cheek)--Shame on you!
<http://www.italianfoodnet.com/eng/ricette/spaghetti-carbonara-spaghetti-alla-carbonara>
Also contained is the video of the recipe. The man is the real deal (with the real Roman accent to match the dish). Notice how often he uses the water. |
11,863 | When cooking spaghetti carbonara, I mix the pasta, bacon, cheese and egg yolks together with a scoop. This technique frequently results in mashed spaghetti as well as bacon clustering.
What could I do different? | 2011/02/06 | [
"https://cooking.stackexchange.com/questions/11863",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/-1/"
] | In addition to the tips from Joe's great grandmother, you might want to try and rinse the pasta thoroughly with some lukewarm water after cooking it al dente. That way you rinse off the remaining starch and you prevent the pasta from cooking any further. Rinsing results in firmer pasta that is silky smooth and doesn't clump together or get mashed up. Your scoop or tongs will slither right through without damaging the pasta. :) | You could try replacing spaghetti with rigatoni pasta.
In this way it is a lot easier to mix and you'll end up with a dish much closer to the authentic Italian carbonara recipe. |
11,863 | When cooking spaghetti carbonara, I mix the pasta, bacon, cheese and egg yolks together with a scoop. This technique frequently results in mashed spaghetti as well as bacon clustering.
What could I do different? | 2011/02/06 | [
"https://cooking.stackexchange.com/questions/11863",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/-1/"
] | In addition to the tips from Joe's great grandmother, you might want to try and rinse the pasta thoroughly with some lukewarm water after cooking it al dente. That way you rinse off the remaining starch and you prevent the pasta from cooking any further. Rinsing results in firmer pasta that is silky smooth and doesn't clump together or get mashed up. Your scoop or tongs will slither right through without damaging the pasta. :) | The key is water. Use the pasta water for the best flavor. This dish is mostly about timing. Do not ever rinse the pasta with water!
Also, if you are making Carbonara with anything other than Guanciale (pork cheek)--Shame on you!
<http://www.italianfoodnet.com/eng/ricette/spaghetti-carbonara-spaghetti-alla-carbonara>
Also contained is the video of the recipe. The man is the real deal (with the real Roman accent to match the dish). Notice how often he uses the water. |
11,863 | When cooking spaghetti carbonara, I mix the pasta, bacon, cheese and egg yolks together with a scoop. This technique frequently results in mashed spaghetti as well as bacon clustering.
What could I do different? | 2011/02/06 | [
"https://cooking.stackexchange.com/questions/11863",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/-1/"
] | The key is water. Use the pasta water for the best flavor. This dish is mostly about timing. Do not ever rinse the pasta with water!
Also, if you are making Carbonara with anything other than Guanciale (pork cheek)--Shame on you!
<http://www.italianfoodnet.com/eng/ricette/spaghetti-carbonara-spaghetti-alla-carbonara>
Also contained is the video of the recipe. The man is the real deal (with the real Roman accent to match the dish). Notice how often he uses the water. | You could try replacing spaghetti with rigatoni pasta.
In this way it is a lot easier to mix and you'll end up with a dish much closer to the authentic Italian carbonara recipe. |
26,205,066 | I have a large JSON formatted file (254MB) which I am trying to import into MongoDB in Cloud9 IDE using mongoimport. Json file consists of mongodb documents each on its own row using newline character. The file looks like this:
```
...
{"t":"1358836264","p":"1.33470"}
{"t":"1358836265","p":"1.33475"}
{"t":"1358836271","p":"1.33477"}
{"t":"1358836272","p":"1.33481"}
{"t":"1358836274","p":"1.33475"}
{"t":"1358836275","p":"1.33478"}
{"t":"1358836288","p":"1.33480"}
{"t":"1358836291","p":"1.33481"}
{"t":"1358836294","p":"1.33481"}
{"t":"1358836295","p":"1.33478"}
...
```
I have tried:
```
mongoimport -d woption -c eurusd eurusddata.json
```
This gave me the following output with error:
```
connected to: 127.0.0.1
Sun Oct 5 16:51:15.094 Progress: 1636800/26345472 6%
Sun Oct 5 16:51:15.094 49600 16533/second
Sun Oct 5 16:51:18.088 Progress: 3375900/26345472 12%
Sun Oct 5 16:51:18.088 102300 17050/second
Sun Oct 5 16:51:21.089 Progress: 4867500/26345472 18%
Sun Oct 5 16:51:21.089 147500 16388/second
Sun Oct 5 16:51:24.103 Progress: 7728600/26345472 29%
Sun Oct 5 16:51:24.103 234200 19516/second
Sun Oct 5 16:51:27.093 Progress: 10467600/26345472 39%
Sun Oct 5 16:51:27.093 317200 21146/second
Sun Oct 5 16:51:30.094 Progress: 13312200/26345472 50%
Sun Oct 5 16:51:30.094 403400 22411/second
Sun Oct 5 16:51:33.302 Progress: 16038000/26345472 60%
Sun Oct 5 16:51:33.303 486000 23142/second
Sun Oct 5 16:51:36.088 Progress: 17341500/26345472 65%
Sun Oct 5 16:51:36.088 525500 21895/second
Sun Oct 5 16:51:39.004 Progress: 18526200/26345472 70%
Sun Oct 5 16:51:39.004 561400 20792/second
Sun Oct 5 16:51:42.032 Progress: 19067400/26345472 72%
Sun Oct 5 16:51:42.032 577800 19260/second
Sun Oct 5 16:51:45.088 Progress: 20829600/26345472 79%
Sun Oct 5 16:51:45.088 631200 19127/second
Sun Oct 5 16:51:48.071 Progress: 23007600/26345472 87%
Sun Oct 5 16:51:48.071 697200 19366/second
Sun Oct 5 16:51:51.914 Progress: 23443200/26345472 88%
Sun Oct 5 16:51:51.914 710400 18215/second
Sun Oct 5 16:51:54.103 Progress: 23611500/26345472 89%
Sun Oct 5 16:51:54.104 715500 17035/second
Sun Oct 5 16:51:57.709 Progress: 23967900/26345472 90%
Sun Oct 5 16:51:57.709 726300 16140/second
Sun Oct 5 16:52:00.096 Progress: 24538800/26345472 93%
Sun Oct 5 16:52:00.096 743600 15491/second
Sun Oct 5 16:52:03.088 Progress: 25548600/26345472 96%
Sun Oct 5 16:52:03.088 774200 15180/second
Sun Oct 5 16:52:04.644 exception:BSON representation of supplied JSON is too large: code FailedToParse: FailedToParse: Expecting ':': offset:21
Sun Oct 5 16:52:04.644
Sun Oct 5 16:52:04.644 check 9 798347
Sun Oct 5 16:52:05.061 imported 798347 objects
Sun Oct 5 16:52:05.061 ERROR: encountered 1 error(s)
```
Then I tried using --jsonArray at the end of previous command:
```
mongoimport -d woption -c eurusd eurusddata.json --jsonArray
```
This gave me the following output with error:
```
connected to: 127.0.0.1
Sun Oct 5 16:54:20.343 exception:JSONArray file too large
Sun Oct 5 16:54:20.444 warning: log line attempted (16384k) over max size(10k), printing beginning and end ... {"t":"1357070402","p":"1.32041"}
{"t":"1357070424","p":"1.32040"}
{"t":"1357070447","p":"1.32038"}
{"t":"1357070457","p":"1.32034"}
{"t":"1357070463","p":"1.32039"}
{"t":"1357070464","p":"1.32038"}
{"t":"1357070470","p":"1.32034"}
{"t":"1357070485","p":"1.32035"}
{"t":"1357070491","p":"1.32046"}
{"t":"1357070520","p":"1.32050"}
{"t":"1357070522","p":"1.32049"}
{"t":"1357070535","p":"1.32050"}
{"t":"1357070581","p":"1.32049"}
{"t":"1357070582","p":"1.32050"}
{"t":"1357070587","p":"1.32035"}
{"t":"1357070589","p":"1.32034"}
{"t":"1357070593","p":"1.32033"}
{"t":"1357070594","p":"1.32024"}
{"t":"1357070595","p":"1.32025"}
{"t":"1357070599","p":"1.32009"}
{"t":"1357070602","p":"1.32024"}
{"t":"1357070630","p":"1.32023"}
{"t":"1357070637","p":"1.32025"}
{"t":"1357070656","p":"1.32023"}
{"t":"1357070691","p":"1.32025"}
{"t":"1357070702","p":"1.32027"}
{"t":"1357070703","p":"1.32028"}
{"t":"1357070706","p":"1.32027"}
{"t":"1357070707","p":"1.32026"}
{"t":"1357070709","p":"1.32027"}
{"t":"1357070710","p":"1.32026"}
{"t":"1357070721","p":"1.32027"}
{"t":"1357070723","p":"1.32026"}
{"t":"1357070761","p":"1.32025"}
{"t":"1357070767","p":"1.32027"}
{"t":"1357070768","p":"1.32025"}
{"t":"1357070784","p":"1.32026"}
{"t":"1357070798","p":"1.32027"}
{"t":"1357070799","p":"1.32026"}
{"t":"1357070804","p":"1.32036"}
{"t":"1357070819","p":"1.32034"}
{"t":"1357070842","p":"1.32035"}
{"t":"1357070880","p":"1.32030"}
{"t":"1357070881","p":"1.32035"}
{"t":"1357070966","p":"1.32053"}
{"t":"1357070967","p":"1.32063"}
{"t":"1357070973","p":"1.32048"}
{"t":"1357070974","p":"1.32046"}
{"t":"1357070977","p":"1.32066"}
{"t":"1357070978","p":"1.32065"}
{"t":"1357070984","p":"1.32064"}
{"t":"1357070987","p":"1.32063"}
{"t":"1357070988","p":"1.32064"}
{"t":"1357070993","p":"1.32065"}
{"t":"1357070997","p":"1.32065"}
{"t":"1357070998","p":"1.32063"}
{"t":"1357071000","p":"1.32064"}
{"t":"1357071003","p":"1.32064"}
{"t":"1357071011","p":"1.32065"}
{"t":"1357071012","p":"1.32069"}
{"t":"1357071013","p":"1.32069"}
{"t":"1357071023","p":"1.32068"}
{"t":"1357071024","p":"1.32068"}
{"t":"1357071026","p":"1.32072"}
{"t":"1357071027","p":"1.32070"}
{"t":"1357071028","p":"1.32069"}
{"t":"1357071047","p":"1.32068"}
{"t":"1357071048","p":"1.32069"}
{"t":"1357071070","p":"1.32072"}
{"t":"1357071071","p":"1.32069"}
{"t":"1357071077","p":"1.32068"}
{"t":"1357071078","p":"1.32069"}
{"t":"1357071085","p":"1.32068"}
{"t":"1357071086","p":"1.32069"}
{"t":"1357071095","p":"1.32072"}
{"t":"1357071096","p":"1.32069"}
{"t":"1357071097","p":"1.32070"}
{"t":"1357071104","p":"1.32069"}
{"t":"1357071105","p":"1.32069"}
{"t":"1357071114","p":"1.32068"}
{"t":"1357071125","p":"1.32068"}
{"t":"1357071132","p":"1.32072"}
{"t":"1357071133","p":"1.32068"}
{"t":"1357071134","p":"1.32069"}
{"t":"1357071136","p":"1.32043"}
{"t":"1357071137","p":"1.32049"}
{"t":"1357071139","p":"1.32052"}
{"t":"1357071140","p":"1.32058"}
{"t":"1357071156","p":"1.32052"}
{"t":"1357071163","p":"1.32050"}
{"t":"1357071174","p":"1.32052"}
{"t":"1357071176","p":"1.32055"}
{"t":"1357071178","p":"1.32053"}
{"t":"1357071185","p":"1.32054"}
{"t":"1357071187","p":"1.32053"}
{"t":"1357071189","p":"1.32025"}
{"t":"1357071190","p":"1.32023"}
{"t":"1357071191","p":"1.32045"}
{"t":"1357071192","p":"1.32044"}
{"t":"1357071193","p":"1.32045"}
{"t":"1357071197","p":"1.32044"}
{"t":"1357071198","p":"1.32043"}
{"t":"1357071199","p":"1.32004"}
{"t":"13570712 .......... ":"1358836127","p":"1.33455"}
{"t":"1358836128","p":"1.33454"}
{"t":"1358836129","p":"1.33455"}
{"t":"1358836130","p":"1.33458"}
{"t":"1358836131","p":"1.33463"}
{"t":"1358836132","p":"1.33462"}
{"t":"1358836133","p":"1.33460"}
{"t":"1358836134","p":"1.33459"}
{"t":"1358836135","p":"1.33464"}
{"t":"1358836137","p":"1.33463"}
{"t":"1358836139","p":"1.33461"}
{"t":"1358836140","p":"1.33462"}
{"t":"1358836142","p":"1.33463"}
{"t":"1358836143","p":"1.33459"}
{"t":"1358836144","p":"1.33461"}
{"t":"1358836146","p":"1.33462"}
{"t":"1358836147","p":"1.33466"}
{"t":"1358836148","p":"1.33473"}
{"t":"1358836149","p":"1.33475"}
{"t":"1358836151","p":"1.33479"}
{"t":"1358836152","p":"1.33484"}
{"t":"1358836153","p":"1.33492"}
{"t":"1358836154","p":"1.33488"}
{"t":"1358836155","p":"1.33492"}
{"t":"1358836156","p":"1.33489"}
{"t":"1358836157","p":"1.33482"}
{"t":"1358836158","p":"1.33483"}
{"t":"1358836159","p":"1.33480"}
{"t":"1358836160","p":"1.33479"}
{"t":"1358836161","p":"1.33482"}
{"t":"1358836162","p":"1.33481"}
{"t":"1358836163","p":"1.33481"}
{"t":"1358836166","p":"1.33480"}
{"t":"1358836167","p":"1.33480"}
{"t":"1358836168","p":"1.33475"}
{"t":"1358836169","p":"1.33454"}
{"t":"1358836170","p":"1.33454"}
{"t":"1358836172","p":"1.33459"}
{"t":"1358836173","p":"1.33456"}
{"t":"1358836174","p":"1.33455"}
{"t":"1358836175","p":"1.33457"}
{"t":"1358836176","p":"1.33459"}
{"t":"1358836177","p":"1.33460"}
{"t":"1358836178","p":"1.33462"}
{"t":"1358836179","p":"1.33458"}
{"t":"1358836180","p":"1.33459"}
{"t":"1358836181","p":"1.33456"}
{"t":"1358836182","p":"1.33458"}
{"t":"1358836183","p":"1.33457"}
{"t":"1358836184","p":"1.33459"}
{"t":"1358836185","p":"1.33460"}
{"t":"1358836186","p":"1.33467"}
{"t":"1358836189","p":"1.33466"}
{"t":"1358836190","p":"1.33472"}
{"t":"1358836191","p":"1.33470"}
{"t":"1358836192","p":"1.33470"}
{"t":"1358836193","p":"1.33469"}
{"t":"1358836194","p":"1.33465"}
{"t":"1358836195","p":"1.33466"}
{"t":"1358836196","p":"1.33461"}
{"t":"1358836197","p":"1.33460"}
{"t":"1358836198","p":"1.33466"}
{"t":"1358836199","p":"1.33465"}
{"t":"1358836200","p":"1.33466"}
{"t":"1358836201","p":"1.33458"}
{"t":"1358836202","p":"1.33457"}
{"t":"1358836203","p":"1.33453"}
{"t":"1358836204","p":"1.33454"}
{"t":"1358836205","p":"1.33456"}
{"t":"1358836210","p":"1.33455"}
{"t":"1358836211","p":"1.33450"}
{"t":"1358836214","p":"1.33449"}
{"t":"1358836216","p":"1.33451"}
{"t":"1358836217","p":"1.33452"}
{"t":"1358836218","p":"1.33457"}
{"t":"1358836220","p":"1.33458"}
{"t":"1358836221","p":"1.33457"}
{"t":"1358836222","p":"1.33456"}
{"t":"1358836223","p":"1.33457"}
{"t":"1358836226","p":"1.33460"}
{"t":"1358836229","p":"1.33459"}
{"t":"1358836230","p":"1.33458"}
{"t":"1358836236","p":"1.33461"}
{"t":"1358836237","p":"1.33466"}
{"t":"1358836240","p":"1.33467"}
{"t":"1358836241","p":"1.33467"}
{"t":"1358836242","p":"1.33463"}
{"t":"1358836243","p":"1.33466"}
{"t":"1358836244","p":"1.33467"}
{"t":"1358836245","p":"1.33468"}
{"t":"1358836250","p":"1.33468"}
{"t":"1358836256","p":"1.33469"}
{"t":"1358836263","p":"1.33472"}
{"t":"1358836264","p":"1.33470"}
{"t":"1358836265","p":"1.33475"}
{"t":"1358836271","p":"1.33477"}
{"t":"1358836272","p":"1.33481"}
{"t":"1358836274","p":"1.33475"}
{"t":"1358836275","p":"1.33478"}
{"t":"1358836288","p":"1.33480"}
{"t":"1358836291","p":"1.33481"}
{"t":"1358836294","p":"1.33481"}
{"t":"1358836295","p":"1.33478"}
{"t":"1358836296
Sun Oct 5 16:54:20.445 check 0 0
Sun Oct 5 16:54:20.445 imported 0 objects
Sun Oct 5 16:54:20.445 ERROR: encountered 1 error(s)
```
I then tried using something like this:
```
mongoimport -d woption -c eurusd < /home/ubuntu/workspace/eurusddata.json
```
This gave me the following output with error:
```
connected to: 127.0.0.1
Sun Oct 5 16:58:08.107 77400 25800/second
Sun Oct 5 16:58:11.096 136300 22716/second
Sun Oct 5 16:58:14.107 177700 19744/second
Sun Oct 5 16:58:17.093 232900 19408/second
Sun Oct 5 16:58:20.125 280400 18693/second
Sun Oct 5 16:58:23.103 343500 19083/second
Sun Oct 5 16:58:26.091 424800 20228/second
Sun Oct 5 16:58:29.095 482800 20116/second
Sun Oct 5 16:58:32.097 517900 19181/second
Sun Oct 5 16:58:35.088 566700 18890/second
Sun Oct 5 16:58:38.091 608700 18445/second
Sun Oct 5 16:58:41.098 664700 18463/second
Sun Oct 5 16:58:44.088 718300 18417/second
Sun Oct 5 16:58:47.089 776800 18495/second
Sun Oct 5 16:58:47.848 exception:BSON representation of supplied JSON is too large: code FailedToParse: FailedToParse: Expecting ':': offset:21
Sun Oct 5 16:58:47.848
Sun Oct 5 16:58:47.848 check 9 798347
Sun Oct 5 16:58:48.852 imported 798347 objects
Sun Oct 5 16:58:48.852 ERROR: encountered 1 error(s)
```
Also tried using previous command with --jsonArray:
```
mongoimport -d woption -c eurusd < /home/ubuntu/workspace/eurusddata.json --jsonArray
```
This gave me the following output with error:
```
connected to: 127.0.0.1
Sun Oct 5 16:59:35.063 exception:JSONArray file too large
Sun Oct 5 16:59:35.101 warning: log line attempted (16384k) over max size(10k), printing beginning and end ... {"t":"1357070402","p":"1.32041"}
{"t":"1357070424","p":"1.32040"}
{"t":"1357070447","p":"1.32038"}
{"t":"1357070457","p":"1.32034"}
{"t":"1357070463","p":"1.32039"}
{"t":"1357070464","p":"1.32038"}
{"t":"1357070470","p":"1.32034"}
{"t":"1357070485","p":"1.32035"}
{"t":"1357070491","p":"1.32046"}
{"t":"1357070520","p":"1.32050"}
{"t":"1357070522","p":"1.32049"}
{"t":"1357070535","p":"1.32050"}
{"t":"1357070581","p":"1.32049"}
{"t":"1357070582","p":"1.32050"}
{"t":"1357070587","p":"1.32035"}
{"t":"1357070589","p":"1.32034"}
{"t":"1357070593","p":"1.32033"}
{"t":"1357070594","p":"1.32024"}
{"t":"1357070595","p":"1.32025"}
{"t":"1357070599","p":"1.32009"}
{"t":"1357070602","p":"1.32024"}
{"t":"1357070630","p":"1.32023"}
{"t":"1357070637","p":"1.32025"}
{"t":"1357070656","p":"1.32023"}
{"t":"1357070691","p":"1.32025"}
{"t":"1357070702","p":"1.32027"}
{"t":"1357070703","p":"1.32028"}
{"t":"1357070706","p":"1.32027"}
{"t":"1357070707","p":"1.32026"}
{"t":"1357070709","p":"1.32027"}
{"t":"1357070710","p":"1.32026"}
{"t":"1357070721","p":"1.32027"}
{"t":"1357070723","p":"1.32026"}
{"t":"1357070761","p":"1.32025"}
{"t":"1357070767","p":"1.32027"}
{"t":"1357070768","p":"1.32025"}
{"t":"1357070784","p":"1.32026"}
{"t":"1357070798","p":"1.32027"}
{"t":"1357070799","p":"1.32026"}
{"t":"1357070804","p":"1.32036"}
{"t":"1357070819","p":"1.32034"}
{"t":"1357070842","p":"1.32035"}
{"t":"1357070880","p":"1.32030"}
{"t":"1357070881","p":"1.32035"}
{"t":"1357070966","p":"1.32053"}
{"t":"1357070967","p":"1.32063"}
{"t":"1357070973","p":"1.32048"}
{"t":"1357070974","p":"1.32046"}
{"t":"1357070977","p":"1.32066"}
{"t":"1357070978","p":"1.32065"}
{"t":"1357070984","p":"1.32064"}
{"t":"1357070987","p":"1.32063"}
{"t":"1357070988","p":"1.32064"}
{"t":"1357070993","p":"1.32065"}
{"t":"1357070997","p":"1.32065"}
{"t":"1357070998","p":"1.32063"}
{"t":"1357071000","p":"1.32064"}
{"t":"1357071003","p":"1.32064"}
{"t":"1357071011","p":"1.32065"}
{"t":"1357071012","p":"1.32069"}
{"t":"1357071013","p":"1.32069"}
{"t":"1357071023","p":"1.32068"}
{"t":"1357071024","p":"1.32068"}
{"t":"1357071026","p":"1.32072"}
{"t":"1357071027","p":"1.32070"}
{"t":"1357071028","p":"1.32069"}
{"t":"1357071047","p":"1.32068"}
{"t":"1357071048","p":"1.32069"}
{"t":"1357071070","p":"1.32072"}
{"t":"1357071071","p":"1.32069"}
{"t":"1357071077","p":"1.32068"}
{"t":"1357071078","p":"1.32069"}
{"t":"1357071085","p":"1.32068"}
{"t":"1357071086","p":"1.32069"}
{"t":"1357071095","p":"1.32072"}
{"t":"1357071096","p":"1.32069"}
{"t":"1357071097","p":"1.32070"}
{"t":"1357071104","p":"1.32069"}
{"t":"1357071105","p":"1.32069"}
{"t":"1357071114","p":"1.32068"}
{"t":"1357071125","p":"1.32068"}
{"t":"1357071132","p":"1.32072"}
{"t":"1357071133","p":"1.32068"}
{"t":"1357071134","p":"1.32069"}
{"t":"1357071136","p":"1.32043"}
{"t":"1357071137","p":"1.32049"}
{"t":"1357071139","p":"1.32052"}
{"t":"1357071140","p":"1.32058"}
{"t":"1357071156","p":"1.32052"}
{"t":"1357071163","p":"1.32050"}
{"t":"1357071174","p":"1.32052"}
{"t":"1357071176","p":"1.32055"}
{"t":"1357071178","p":"1.32053"}
{"t":"1357071185","p":"1.32054"}
{"t":"1357071187","p":"1.32053"}
{"t":"1357071189","p":"1.32025"}
{"t":"1357071190","p":"1.32023"}
{"t":"1357071191","p":"1.32045"}
{"t":"1357071192","p":"1.32044"}
{"t":"1357071193","p":"1.32045"}
{"t":"1357071197","p":"1.32044"}
{"t":"1357071198","p":"1.32043"}
{"t":"1357071199","p":"1.32004"}
{"t":"13570712 .......... ":"1358836127","p":"1.33455"}
{"t":"1358836128","p":"1.33454"}
{"t":"1358836129","p":"1.33455"}
{"t":"1358836130","p":"1.33458"}
{"t":"1358836131","p":"1.33463"}
{"t":"1358836132","p":"1.33462"}
{"t":"1358836133","p":"1.33460"}
{"t":"1358836134","p":"1.33459"}
{"t":"1358836135","p":"1.33464"}
{"t":"1358836137","p":"1.33463"}
{"t":"1358836139","p":"1.33461"}
{"t":"1358836140","p":"1.33462"}
{"t":"1358836142","p":"1.33463"}
{"t":"1358836143","p":"1.33459"}
{"t":"1358836144","p":"1.33461"}
{"t":"1358836146","p":"1.33462"}
{"t":"1358836147","p":"1.33466"}
{"t":"1358836148","p":"1.33473"}
{"t":"1358836149","p":"1.33475"}
{"t":"1358836151","p":"1.33479"}
{"t":"1358836152","p":"1.33484"}
{"t":"1358836153","p":"1.33492"}
{"t":"1358836154","p":"1.33488"}
{"t":"1358836155","p":"1.33492"}
{"t":"1358836156","p":"1.33489"}
{"t":"1358836157","p":"1.33482"}
{"t":"1358836158","p":"1.33483"}
{"t":"1358836159","p":"1.33480"}
{"t":"1358836160","p":"1.33479"}
{"t":"1358836161","p":"1.33482"}
{"t":"1358836162","p":"1.33481"}
{"t":"1358836163","p":"1.33481"}
{"t":"1358836166","p":"1.33480"}
{"t":"1358836167","p":"1.33480"}
{"t":"1358836168","p":"1.33475"}
{"t":"1358836169","p":"1.33454"}
{"t":"1358836170","p":"1.33454"}
{"t":"1358836172","p":"1.33459"}
{"t":"1358836173","p":"1.33456"}
{"t":"1358836174","p":"1.33455"}
{"t":"1358836175","p":"1.33457"}
{"t":"1358836176","p":"1.33459"}
{"t":"1358836177","p":"1.33460"}
{"t":"1358836178","p":"1.33462"}
{"t":"1358836179","p":"1.33458"}
{"t":"1358836180","p":"1.33459"}
{"t":"1358836181","p":"1.33456"}
{"t":"1358836182","p":"1.33458"}
{"t":"1358836183","p":"1.33457"}
{"t":"1358836184","p":"1.33459"}
{"t":"1358836185","p":"1.33460"}
{"t":"1358836186","p":"1.33467"}
{"t":"1358836189","p":"1.33466"}
{"t":"1358836190","p":"1.33472"}
{"t":"1358836191","p":"1.33470"}
{"t":"1358836192","p":"1.33470"}
{"t":"1358836193","p":"1.33469"}
{"t":"1358836194","p":"1.33465"}
{"t":"1358836195","p":"1.33466"}
{"t":"1358836196","p":"1.33461"}
{"t":"1358836197","p":"1.33460"}
{"t":"1358836198","p":"1.33466"}
{"t":"1358836199","p":"1.33465"}
{"t":"1358836200","p":"1.33466"}
{"t":"1358836201","p":"1.33458"}
{"t":"1358836202","p":"1.33457"}
{"t":"1358836203","p":"1.33453"}
{"t":"1358836204","p":"1.33454"}
{"t":"1358836205","p":"1.33456"}
{"t":"1358836210","p":"1.33455"}
{"t":"1358836211","p":"1.33450"}
{"t":"1358836214","p":"1.33449"}
{"t":"1358836216","p":"1.33451"}
{"t":"1358836217","p":"1.33452"}
{"t":"1358836218","p":"1.33457"}
{"t":"1358836220","p":"1.33458"}
{"t":"1358836221","p":"1.33457"}
{"t":"1358836222","p":"1.33456"}
{"t":"1358836223","p":"1.33457"}
{"t":"1358836226","p":"1.33460"}
{"t":"1358836229","p":"1.33459"}
{"t":"1358836230","p":"1.33458"}
{"t":"1358836236","p":"1.33461"}
{"t":"1358836237","p":"1.33466"}
{"t":"1358836240","p":"1.33467"}
{"t":"1358836241","p":"1.33467"}
{"t":"1358836242","p":"1.33463"}
{"t":"1358836243","p":"1.33466"}
{"t":"1358836244","p":"1.33467"}
{"t":"1358836245","p":"1.33468"}
{"t":"1358836250","p":"1.33468"}
{"t":"1358836256","p":"1.33469"}
{"t":"1358836263","p":"1.33472"}
{"t":"1358836264","p":"1.33470"}
{"t":"1358836265","p":"1.33475"}
{"t":"1358836271","p":"1.33477"}
{"t":"1358836272","p":"1.33481"}
{"t":"1358836274","p":"1.33475"}
{"t":"1358836275","p":"1.33478"}
{"t":"1358836288","p":"1.33480"}
{"t":"1358836291","p":"1.33481"}
{"t":"1358836294","p":"1.33481"}
{"t":"1358836295","p":"1.33478"}
{"t":"1358836296
Sun Oct 5 16:59:35.101 check 0 0
Sun Oct 5 16:59:35.102 imported 0 objects
Sun Oct 5 16:59:35.102 ERROR: encountered 1 error(s)
```
What am I doing wrong or what am I missing here? How can I import large json files to MongoDB? | 2014/10/05 | [
"https://Stackoverflow.com/questions/26205066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1312286/"
] | According to the message:
```
Sun Oct 5 16:52:03.088 Progress: 25548600/26345472 96%
Sun Oct 5 16:52:03.088 774200 15180/second
Sun Oct 5 16:52:04.644 exception:BSON representation of supplied JSON is too large: code FailedToParse: FailedToParse: Expecting ':': offset:21
```
**I think there are some mistakes near the end of your imported file.**
For `{"t":"1358836291","p":"1.33481"}`, the offset of second `:` is 21. So, please check syntax of documents near the end (96% ~ 100%) of imported file.
By the way, `--jsonArray` is improper to use here because it has a limit of 16MB. | Change your command from `mongoimport -d woption -c eurusd eurusddata.json --jsonArray` to `mongoimport -d woption -c eurusd --file eurusddata.json --jsonArray` and this will work. Hope this helps. Update if this doesn't work. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.