qid
int64 1
74.7M
| question
stringlengths 17
39.2k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
41.1k
| response_k
stringlengths 2
47.9k
|
---|---|---|---|---|---|
478,095 | I use a 60GB SSD for the `C:` partition where Windows and other essential programs are installed, using a larger mechanical HDD for `D:`, and I repeatedly find myself short of disk space on `C:`, with the main culprits being folders within `%LocalAppData%` [Picasa & Outlook files].
How can I move these folders to `D:`, recovering space on `C:`? | 2012/09/21 | [
"https://superuser.com/questions/478095",
"https://superuser.com",
"https://superuser.com/users/9814/"
] | Microsoft [does not](https://support.microsoft.com/kb/949977?wa=wsignin1.0) recommend moving `%AppData%` off the system partition.
* Use [TreeSize Free](http://www.jam-software.com/treesize_free/) to see if there other ways to remove files, as sometimes `C:\hiberfile.sys` and `C:\pagefile.sys` are candidates
* `%LocalAppData%\Temp` could be redirected to a mechanical HDD
You should really consider getting a bigger SSD, as you want to run with at least 30% free so the SSD has vacant blocks to write to; running at 99% full on an SSD increases wear level, with the performance you come to expect from SSD being greatly diminished. | Login using *Safe mode*:
1. Press `F8` at boot and select *Safe Mode* from the menu
2. Navigate to `%AppData%` → Right-click `LocalLow` and/or `Roaming` → *Properties*
* *You can't safely move `%LocalAppData%` since it's also being used in Safe Mode, but the `Roaming` and `LocalLow` folders hold great potential for space recovery.*
3. Tab: *Location* → Move |
478,095 | I use a 60GB SSD for the `C:` partition where Windows and other essential programs are installed, using a larger mechanical HDD for `D:`, and I repeatedly find myself short of disk space on `C:`, with the main culprits being folders within `%LocalAppData%` [Picasa & Outlook files].
How can I move these folders to `D:`, recovering space on `C:`? | 2012/09/21 | [
"https://superuser.com/questions/478095",
"https://superuser.com",
"https://superuser.com/users/9814/"
] | Using the registry method within [Shell Folder/User Shell Folder](http://www.tweaklibrary.com/System/Application-Path/71/Change-default-location-of-the-%E2%80%9CApplication-Data%E2%80%9D-folder/10471/), folder redirection for all subsequent data will be saved at the new location by default:
* Microsoft's [Deploy Folder Redirection with Offline Files](http://support.microsoft.com/kb/242557) article shows how to change the location of the `Desktop` folder by using folder redirection. *(replace `Desktop` with `AppData`, `Start Menu`, etc.)* | Over a period of time, I mysteriously lost 100gb HD space within Win 7 Home Premium, with *Space Monger* reporting it was from subfolders within `%UserProfile%\AppData`, which I think are hidden files.
* Research online suggested that since these are temporary user files, I could delete them, which I did via Space Monger, recovering 100GB with no noticeable ill effects. |
23,875,589 | I'm using the `random_number` subroutine from Fortran, but in different runs of program the number which is being produced doesn't change. What should I include in my code so every time I compile and run the program the numbers change? | 2014/05/26 | [
"https://Stackoverflow.com/questions/23875589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3646979/"
] | The random number generator produces pseudo-random numbers. To get different numbers each run, you need to initialise the [random seed](https://gcc.gnu.org/onlinedocs/gfortran/RANDOM_005fSEED.html) at the start of your program. This picks a different starting position in the pseudo-random stream. | The sequence of pseudorandom numbers coming from call(s) to `random_number` depends on the algorithm used by the processor and the value of the seed.
The initial value of the seed is processor dependent. For some processors this seed value will be the same each time the program runs, and for some it will be different. The first case gives a repeatable pseudorandom sequence and the second a non-repeatable sequence.
gfortran (before version 7) falls into this first category. You will need to explicitly change the random seed if you wish to get non-repeatable sequences.
As stated in [another answer](https://stackoverflow.com/a/23875704) the intrinsic `random_seed` can be used to set the value of the seed and restart the pseudorandom generator. Again, it is processor dependent what happens when the call is `call random_seed()` (that is, without a `put=` argument). Some processors will restart the generator with a repeatable sequence, some won't. gfortran (again, before version 7) is in the first category.
For processors where `call random_seed()` gives rise to a repeatable sequence an explicit run-time varying seed will be required to generate distinct sequences. An example for those older gfortran versions can be found in [the documentation](https://gcc.gnu.org/onlinedocs/gcc-6.4.0/gfortran/RANDOM_005fSEED.html).
It should be noted that choosing a seed can be a complicated thing. Not only will there be portability issues, but care may be required in ensuring that the generator is not restarted in a low entropy region. For multi-image programs the user will have to work to have varying sequences across these images.
On a final note, Fortran 2018 introduced the standard intrinsic procedure `random_init`. This handles both cases of selecting repeatability across invocations and distinctness over (coarray) images. |
42,424,290 | So i am joking around with jquery (imma nub). now i found something interesting: why i cant hide the text in the section tag. it works fine when its like `<section><p>blabla text text</p></section>`
I didnt find anything on google. I would like to fix it with the jquery execution code!
Problem code:
```js
$(document).ready(function() {
$("button").click(function() {
$("p section").hide();
});
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<h2>This is a heading</h2>
<p>
<section>This is a paragraph.</section>
</p>
<p>This is another paragraph.</p>
<button>Click me to hide paragraphs</button>
```
Thanks in advance | 2017/02/23 | [
"https://Stackoverflow.com/questions/42424290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7388672/"
] | Section cannot be nested inside any other element.Section stands on its own
**From HTML5 Doctor
The section element represents a generic document or application section…The section element is not a generic container element. When an element is needed only for styling purposes or as a convenience for scripting, authors are encouraged to use the div element instead. A general rule is that the section element is appropriate only if the element’s contents would be listed explicitly in the document’s outline.
section is a blob of content that you could store as an individual record in a database. It generally looks like this (and note that the heading goes inside the section element, not immediately before it):**
change your snippet as the following should work
```js
$(document).ready(function() {
$("button").click(function() {
$("section").hide();
});
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<h2>This is a heading</h2>
<section><p>This is a paragraph.</p></section>
<p>This is another paragraph.</p>
<button>Click me to hide paragraphs</button>
``` | The problem is that `<section>` **cannot** reside within a `<p>` tag. Think about it, a 'section' shouldn't reside within a 'paragraph'. What you may be looking for is `<span>`. This way, you can style **part** of a paragraph:
```
$("p > span").hide();
<p>
<span>This is a paragraph.</span>
</p>
```
I've created a working fiddle demonstrating this [here](https://jsfiddle.net/Obsidian_Age/vn4got2y/).
Hope this helps! :) |
42,424,290 | So i am joking around with jquery (imma nub). now i found something interesting: why i cant hide the text in the section tag. it works fine when its like `<section><p>blabla text text</p></section>`
I didnt find anything on google. I would like to fix it with the jquery execution code!
Problem code:
```js
$(document).ready(function() {
$("button").click(function() {
$("p section").hide();
});
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<h2>This is a heading</h2>
<p>
<section>This is a paragraph.</section>
</p>
<p>This is another paragraph.</p>
<button>Click me to hide paragraphs</button>
```
Thanks in advance | 2017/02/23 | [
"https://Stackoverflow.com/questions/42424290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7388672/"
] | Section cannot be nested inside any other element.Section stands on its own
**From HTML5 Doctor
The section element represents a generic document or application section…The section element is not a generic container element. When an element is needed only for styling purposes or as a convenience for scripting, authors are encouraged to use the div element instead. A general rule is that the section element is appropriate only if the element’s contents would be listed explicitly in the document’s outline.
section is a blob of content that you could store as an individual record in a database. It generally looks like this (and note that the heading goes inside the section element, not immediately before it):**
change your snippet as the following should work
```js
$(document).ready(function() {
$("button").click(function() {
$("section").hide();
});
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<h2>This is a heading</h2>
<section><p>This is a paragraph.</p></section>
<p>This is another paragraph.</p>
<button>Click me to hide paragraphs</button>
``` | The HTML5 spec tells us that the `<p>` element's content model is phrasing content.
so only the following tags can be inside the `<p>` tag. Not a jquery bug ;)
>
> a (if it contains only phrasing content), abbr area (if it is a
> descendant of a map element) audio b bdi bdo br button canvas cite
> code command datalist del (if it contains only phrasing content) dfn
> em embed i iframe img input ins (if it contains only phrasing content)
> kbd keygen label map (if it contains only phrasing content) mark math
> meter noscript object output progress q ruby s samp script select
> small span strong sub sup svg textarea time u var video wbr text
>
>
> |
22,453,509 | I have a menu that the user can open at any stage. I would like the menu to autohide if the user starts to type anything or executes some action.
The menu is applicable to many pages in my app. Ideally I'd like to execute the code to test if the menu should close whenever the user changes anything in the app. e.g.
```
if(appController.get('showMenu'){
appController.set('showMenu', false);
}
```
Any thoughts on a good DRY solution for this? | 2014/03/17 | [
"https://Stackoverflow.com/questions/22453509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3091013/"
] | Passing the iterator and operating on the iterator in the same pass (like increment of the iterator) leads to undefined behavior. There are certain concepts such as [sequence points](http://msdn.microsoft.com/en-us/library/d45c7a5d.aspx), which you should be aware of when you are performing such operations.
Further, you can check [this](http://c-faq.com/expr/seqpoints.html) link also. I suggest you to move the increment of the operator after the pass to function. Then it should work fine. | you are increasing the iterator twice, first in the head of the for-loop:
```
std::advance(it,2)
```
then in the loop-body, where you do a:
```
++it
```
Is this really what you want? It looks pretty confusing to me.
If you want the element next to it, but dont want to increase it, better use:
```
auto nextIt = std::next(it);
```
Also: What does the match-function do? Are you sure its implemented right and not the source of the bug?
Hope this helps
Alexander |
22,453,509 | I have a menu that the user can open at any stage. I would like the menu to autohide if the user starts to type anything or executes some action.
The menu is applicable to many pages in my app. Ideally I'd like to execute the code to test if the menu should close whenever the user changes anything in the app. e.g.
```
if(appController.get('showMenu'){
appController.set('showMenu', false);
}
```
Any thoughts on a good DRY solution for this? | 2014/03/17 | [
"https://Stackoverflow.com/questions/22453509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3091013/"
] | You could avoid increasing the iterator at increment part of the loop and dot it in the body:
```
std::list<Team*> teamlist = league.GetTeamMembers();
for (std::list<Team*> ::iterator it = teamlist.begin();
it != teamlist.end(); /*Nothing here*/)
{
match(*(*it), *(*(++it))); //Which parameter expression is evaluated first isn't determined
++it;
...
...
```
**EDIT:**
As FredOverflow has pointed out, match parameter expressions evaluations are not guaranteed to run in the left to right order. To avoid this hazardous situation:
```
std::list<Team*> teamlist = league.GetTeamMembers();
for (std::list<Team*> ::iterator it = teamlist.begin();
it != teamlist.end(); /*Nothing here*/)
{
Team *pa = *it;
Team *pb = *(++it);
match(*pa, *pb);
++it;
...
...
``` | you are increasing the iterator twice, first in the head of the for-loop:
```
std::advance(it,2)
```
then in the loop-body, where you do a:
```
++it
```
Is this really what you want? It looks pretty confusing to me.
If you want the element next to it, but dont want to increase it, better use:
```
auto nextIt = std::next(it);
```
Also: What does the match-function do? Are you sure its implemented right and not the source of the bug?
Hope this helps
Alexander |
67,968,730 | I am very new to swift. So TLDR I have a collection view which I want to update after I click a button. I have seen various solutions and everyone suggesting to put collectionView.reloadData but I am not understanding where to put this line in my code. Any help will be appreciated.
This is the view controller:
```
class myViewController: UIViewController {
@IBOutlet weak var myCollectionView: UICollectionView!
var charList: Array<String> = []
var data: String = ""
var songTiles = [
"teri meri": ["D", "A", "G", "A", "F", "G", "A", "F", "G", "A", "G", "F", "E", "D", "E", "D", "C", "D", "E", "F", "E", "F", "E", "G", "A", "G", "F", "E", "D", "D"],
"faded": ["B", "A", "B", "A"],
"darmiyan": ["A", "B", "B", "A"],
"hangover": ["B", "A", "B", "A"],
"dna": ["A", "A", "A", "A"],
"fire": ["A", "B", "B", "A"],
"springday": ["C", "A", "A", "A"],
"gotcha": ["C", "A", "A", "A"],
"aurora": ["C", "A", "A", "A"],
"fadedremix": ["A", "B", "A", "B"]
]
@IBOutlet weak var chosenSong: UILabel!
@IBAction func keyNote(_ sender: UIButton) {
if (sender.currentTitle == charList[0]) {
charList.removeFirst()
print("Correct!")
playSound(sound: sender.currentTitle!)
}
}
func playSound(sound: String) {
guard let url = Bundle.main.url(forResource: sound, withExtension: "wav") else {
return
}
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
var player: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
charList = songTiles[data]!
chosenSong.text = data
// Do any additional setup after loading the view.
}
}
extension myViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return charList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
myCollectionView.reloadItems(at: [indexPath])
let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! myCollectionViewCell
cell.myImage.image = UIImage(named: charList[indexPath.row])
myCollectionView.reloadItems(at: [indexPath])
return cell
}
}
```
So the way this code works is it deletes the character from the start of the array that user has selected each time user presses the button correctly.
For eg if I choose Array Faded and I press A the Array in the UIControllerView should remove A and update collection view accordingly. Think of it as a tutorial of learning songs on xylophone.
Any help would be appreciated. Thanks. | 2021/06/14 | [
"https://Stackoverflow.com/questions/67968730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13289169/"
] | You can try like this
```
@IBAction func keyNote(_ sender: UIButton) {
if (sender.currentTitle == charList[0]) {
charList.removeFirst()
print("Correct!")
let theIndex = IndexPath(row: 0, section: 0)
myCollectionView.deleteItems(at: [theIndex])
playSound(sound: sender.currentTitle!)
}
}
``` | Don't call `reloadItems(at: [indexPath])` in `cellForItemAt:indexPath` - the collection view is in the middle of asking you for the cell there, reload items will make it ask you again.
You need to tell the collection view it needs to ask you again when your model charList changes: here: `charList.removeFirst()` |
52,555,254 | Can anyone advise me on how to code a sed script that can be used to update a text file as follows:
Each time a line in the file containing the character string 'Header\_one' is encountered:
- delete the lines that immediately follow the 'Header\_one' line until the next blank line is encountered.
- but dont delete the 'Header\_one' line itself
So as an example, a file containing this:
```
Header_one
dkrjng
djsje
Header_two
cklrgjsj
djrhg
Header_one
drgbyj
efgjjm
cddess
Header_three
sdfvgg
ddddfy
```
Would be changed to:
```
Header_one
Header_two
cklrgjsj
djrhg
Header_one
Header_three
sdfvgg
ddddfy
```
I would be grateful for any guidance or solution.
Thanks,
James. | 2018/09/28 | [
"https://Stackoverflow.com/questions/52555254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10429029/"
] | Try the below snip
`< InputFile sed -e '/Header_one/i Header_one' -e '/Header_one/,/s/d' > outputFile`
The idea here is to replace the content between 2 rows and replace it with a header (i.e. Header\_one). The second `-e` part of the codes does delete the data between Header\_one and space; while the first `-e` part replaces it with a new header `Header_one`.
InputFile and OutputFiles are simple redirections.
You can also look into: <https://askubuntu.com/questions/637003/delete-lines-between-2-strings>
Hope this helps :) | `sed` is a stream editor, and although one popular version of sed provides an option that appears to make it edit files, I strongly advise against its use. That said, you can produce the output you desire with:
```
sed -e '/Header_one/i\
Header_one\
\
' -e '/Header_one/,/^$/d' input
```
Note that it's a lot cleaner if you don't require keeping that blank line:
```
sed -e '/Header_one/p' -e '/Header_one/,/^$/d' input
```
Also: `awk '/Header_one/{printf "Header_one\n\n"; next } 1' RS= ORS='\n\n' input` |
52,555,254 | Can anyone advise me on how to code a sed script that can be used to update a text file as follows:
Each time a line in the file containing the character string 'Header\_one' is encountered:
- delete the lines that immediately follow the 'Header\_one' line until the next blank line is encountered.
- but dont delete the 'Header\_one' line itself
So as an example, a file containing this:
```
Header_one
dkrjng
djsje
Header_two
cklrgjsj
djrhg
Header_one
drgbyj
efgjjm
cddess
Header_three
sdfvgg
ddddfy
```
Would be changed to:
```
Header_one
Header_two
cklrgjsj
djrhg
Header_one
Header_three
sdfvgg
ddddfy
```
I would be grateful for any guidance or solution.
Thanks,
James. | 2018/09/28 | [
"https://Stackoverflow.com/questions/52555254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10429029/"
] | Try the below snip
`< InputFile sed -e '/Header_one/i Header_one' -e '/Header_one/,/s/d' > outputFile`
The idea here is to replace the content between 2 rows and replace it with a header (i.e. Header\_one). The second `-e` part of the codes does delete the data between Header\_one and space; while the first `-e` part replaces it with a new header `Header_one`.
InputFile and OutputFiles are simple redirections.
You can also look into: <https://askubuntu.com/questions/637003/delete-lines-between-2-strings>
Hope this helps :) | Using Perl
```
perl -ne ' { print "Header_one\n" if /Header_one/ ; print if not /Header_one/../^$/ } '
``` |
106,686 | I am quite amateur with a camera but I want to become good in fashion photography. A top model has agreed for a photo-shoot for free and in return she wants me to make a portfolio. We are planning to take the photos on a beach during day light. I have only used a Nikon D5600 and Nikkor AF-P 18-55mm kit lens.
I read in the internet that 50mm on a FX camera is close to what the human eye sees. Also I wanted to keep my distance between me and the model in the range of 3 and 10 meters. So I thought I should rent a 35mm instead as it would give almost 50mm view on a DX camera (35mm x 1.5 crop-factor = 52.5mm). However 35mm view on my kit lens appears zoomed in, its not what my eyes see. Instead the 24mm looks more natural. Is 35mm on a cropped sensor good for fashion photography considering the distance between me and the model ? or should I use 24mm ? | 2019/04/19 | [
"https://photo.stackexchange.com/questions/106686",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/83271/"
] | Photography is not (necessarily) about giving the viewer a "as you would see it"-perspective. Photography is about offering additional perspectives. If this was not true, the only good photos would be with roughly the same angle of view that the human eyes give us, shot at eye-height.
This, however, is not true. I would even go as far as to say: Those are the most boring photos that anyone can make.
**It is much more about whether you like the look that 24mm deliver or not.** You can make stunning photos with all focal lengths just as you can make boring ones. **It all depends on what you want to do.** And that still holds true in fashion.
---
My recommendation: **See which focal length(s) you like the most on your zoom lens for the look you want - and also see where it puts limitations on your work.** Buy accordingly - but always remember that a more expensive lens does not mean that your photos will automagically get better. I have seen stunning pictures taken with kit lenses - and I have seen pictures taken with five-digit $ lenses that are absolutely tedious.
Note that this also means that **you have to know your gear and its limitations well before the critical shooting**. It also means that going into the shooting, **you should have a concept of what look you want to achieve**. IMHO, routine means everything in professional work.
---
**Regarding equipment in fashion:** Direct sunlight and fashion photography do not get along well ;-) Bring diffusers, reflectors, and maybe even a fill flash. To get all of this working, see if you can find a friend to assist you with holding that stuff.
As mentioned first by [juhist](https://photo.stackexchange.com/a/106689/69369), bring some ND-filters (maybe 1EV and 2 EV) with you, as `sun + fast lens = many, many EVs`.
Also, as [Tetsujin mentions](https://photo.stackexchange.com/a/106690/69369): Primes are not everything. Zoom lenses like the 70-200 f/2.8 (and even f/4) offer incredible performance and don't force you to go with one perspective all the time as prime lenses would. E.g. most of my professional work, I do with my 24-105 f/4, because it works well in all conditions and the shots it offers well over-satisfy the needs of my clients. The below mentioned 100mm f/2.8 is my go-to-lens (ATM) for controlled situations where I *need* the tiny bit of extra performance that it offers.
---
**Anecdote**: A friend of mine is a semi-professional model. In the beginning of her "career", she asked me to help her with her portfolio. We mostly did medium long shots and medium close-ups - mostly "in movement", some more classic still portraits. What lenses did I use? Mostly the 100mm f/2.8L Macro. Was it the only lens that could do the job? No, absolutely not. But I already owned it, it offers a reasonable ability to separate the subject from the background (which I wanted), and I simply love its color rendition. And most importantly: I wanted that exact angle for my work - the photos I made would not have worked well with, say, a 50mm lens. | Some simple trigonometry can help here, but it's just an estimate... Let's say your model is 1.7m tall. In order to capture a pose at full height, assuming portrait orientation, you're going to need an angle of view on the long side of your sensor of between about 10 and 32 degrees (at 10 meters and 3 meters, respectively). For other poses, if you assume about half his/her full height, you would need between 5 and 16 degrees. On my 1.6X crop sensor Canon, those numbers correspond to about 38-250mm in focal length. Your 1.5X Nikon would be a little different than that (40-270mm or so), but that does tend to indicate the 35mm might be a bit short for keeping your expected distance. Of course, that doesn't include extra space for framing (you probably don't want the model to take up the entire image in every shot...), so you can probably reduce that estimate a bit, and maybe 35mm is right on the edge of what you are looking for. A 50mm, 85mm or 100mm might be a good idea to have along as well (or even just a zoom that covers a good portion of those in its range). |
106,686 | I am quite amateur with a camera but I want to become good in fashion photography. A top model has agreed for a photo-shoot for free and in return she wants me to make a portfolio. We are planning to take the photos on a beach during day light. I have only used a Nikon D5600 and Nikkor AF-P 18-55mm kit lens.
I read in the internet that 50mm on a FX camera is close to what the human eye sees. Also I wanted to keep my distance between me and the model in the range of 3 and 10 meters. So I thought I should rent a 35mm instead as it would give almost 50mm view on a DX camera (35mm x 1.5 crop-factor = 52.5mm). However 35mm view on my kit lens appears zoomed in, its not what my eyes see. Instead the 24mm looks more natural. Is 35mm on a cropped sensor good for fashion photography considering the distance between me and the model ? or should I use 24mm ? | 2019/04/19 | [
"https://photo.stackexchange.com/questions/106686",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/83271/"
] | Photography is not (necessarily) about giving the viewer a "as you would see it"-perspective. Photography is about offering additional perspectives. If this was not true, the only good photos would be with roughly the same angle of view that the human eyes give us, shot at eye-height.
This, however, is not true. I would even go as far as to say: Those are the most boring photos that anyone can make.
**It is much more about whether you like the look that 24mm deliver or not.** You can make stunning photos with all focal lengths just as you can make boring ones. **It all depends on what you want to do.** And that still holds true in fashion.
---
My recommendation: **See which focal length(s) you like the most on your zoom lens for the look you want - and also see where it puts limitations on your work.** Buy accordingly - but always remember that a more expensive lens does not mean that your photos will automagically get better. I have seen stunning pictures taken with kit lenses - and I have seen pictures taken with five-digit $ lenses that are absolutely tedious.
Note that this also means that **you have to know your gear and its limitations well before the critical shooting**. It also means that going into the shooting, **you should have a concept of what look you want to achieve**. IMHO, routine means everything in professional work.
---
**Regarding equipment in fashion:** Direct sunlight and fashion photography do not get along well ;-) Bring diffusers, reflectors, and maybe even a fill flash. To get all of this working, see if you can find a friend to assist you with holding that stuff.
As mentioned first by [juhist](https://photo.stackexchange.com/a/106689/69369), bring some ND-filters (maybe 1EV and 2 EV) with you, as `sun + fast lens = many, many EVs`.
Also, as [Tetsujin mentions](https://photo.stackexchange.com/a/106690/69369): Primes are not everything. Zoom lenses like the 70-200 f/2.8 (and even f/4) offer incredible performance and don't force you to go with one perspective all the time as prime lenses would. E.g. most of my professional work, I do with my 24-105 f/4, because it works well in all conditions and the shots it offers well over-satisfy the needs of my clients. The below mentioned 100mm f/2.8 is my go-to-lens (ATM) for controlled situations where I *need* the tiny bit of extra performance that it offers.
---
**Anecdote**: A friend of mine is a semi-professional model. In the beginning of her "career", she asked me to help her with her portfolio. We mostly did medium long shots and medium close-ups - mostly "in movement", some more classic still portraits. What lenses did I use? Mostly the 100mm f/2.8L Macro. Was it the only lens that could do the job? No, absolutely not. But I already owned it, it offers a reasonable ability to separate the subject from the background (which I wanted), and I simply love its color rendition. And most importantly: I wanted that exact angle for my work - the photos I made would not have worked well with, say, a 50mm lens. | It depends on what kind of look you want and how long is your possible working distance.
I would rent at least 35mm and 50mm primes. For shooting human subjects, you don't always want the field of view that human eye sees. Humans remember the looks of other humans as they appear from a quite long distance (sorry I don't now find a source which says what the distance is). At short distance, [the ears can look smaller than they appear from long distance](https://photo.stackexchange.com/a/76335/81735).
Also, you may want to throw the background out of focus with background blur. Now, to achieve background blur, you can either use a wide aperture (but this decreases depth of field), or a long focal length (this can create background blur without too shallow depth of field).
Additionally, if you want to emphasize the human subject, 50mm would be good. If you want to emphasize the environment the human subject is in, and capture as much of the environment as possible, 35mm or 24mm would be good. However, your kit lens already has the 24mm aperture and background blur with 24mm is low and depth of field deep, so a faster aperture than your kit lens doesn't buy you really anything.
If you have a model for free, now is not the time to save on equipment and use only one focal length.
My suggestion is therefore:
* Use your kit lens for 24mm and shorter, use it wide open (which is probably around f/4)
* Rent a fast 35mm prime
* Rent a fast 50mm prime, at 10 meter distance the field of view is 4.8 m x 3.2 m which seems large enough, and you can get some beautiful background blur at this focal length and fast aperture
If you really really want to save on lens rental costs, I would pick the 50mm and use the kit lens for 35mm too. The reasoning being that background blur at 35mm is more difficult than at 50mm, so the fast aperture of a fast prime is more beneficial for 50mm prime than it is for 35mm prime. Furthermore, the aperture of the kit lens is slower at 50mm than it is at 35mm, so that too favors renting the 50mm over 35mm.
If you have the money to throw at lens rentals, consider renting an 85mm lens too. It is a focal length you can't achieve with your kit lens. The pictures will have narrow field of view and therefore have to be taken from a really long distance, but you may find it useful in some cases. A 85mm can achieve really good background blur, **at the same time** as having a deep enough depth of field.
Oh, and you may need an ND filter to use f/1.8 in sunlight, because the lowest ISO of your camera is probably ISO 100, and the fastest shutter speed is 1/4000 s.
Consider also lighting: powerful enough fill flash, diffuser, etc. can alter the lighting in ways you can't achieve with only sunlight.
Useful:
* [Field of view calculator](https://www.scantips.com/lights/fieldofview.html)
* [Depth of field calculator](http://www.dofmaster.com/dofjs.html)
Some cost estimates at lensrentals.com:
* Nikon 50mm f/1.8 costs $13 for 2 days
* Nikon 50mm f/1.4 costs $19 for 2 days
* Nikon 35mm f/1.8 costs $25 for 2 days
* Nikon 85mm f/1.8 costs $20 for 2 days
To me, it's clear that you want to rent at least the 50mm f/1.8 based on these because it's so cheap, if not going for the 50mm f/1.4! |
106,686 | I am quite amateur with a camera but I want to become good in fashion photography. A top model has agreed for a photo-shoot for free and in return she wants me to make a portfolio. We are planning to take the photos on a beach during day light. I have only used a Nikon D5600 and Nikkor AF-P 18-55mm kit lens.
I read in the internet that 50mm on a FX camera is close to what the human eye sees. Also I wanted to keep my distance between me and the model in the range of 3 and 10 meters. So I thought I should rent a 35mm instead as it would give almost 50mm view on a DX camera (35mm x 1.5 crop-factor = 52.5mm). However 35mm view on my kit lens appears zoomed in, its not what my eyes see. Instead the 24mm looks more natural. Is 35mm on a cropped sensor good for fashion photography considering the distance between me and the model ? or should I use 24mm ? | 2019/04/19 | [
"https://photo.stackexchange.com/questions/106686",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/83271/"
] | Photography is not (necessarily) about giving the viewer a "as you would see it"-perspective. Photography is about offering additional perspectives. If this was not true, the only good photos would be with roughly the same angle of view that the human eyes give us, shot at eye-height.
This, however, is not true. I would even go as far as to say: Those are the most boring photos that anyone can make.
**It is much more about whether you like the look that 24mm deliver or not.** You can make stunning photos with all focal lengths just as you can make boring ones. **It all depends on what you want to do.** And that still holds true in fashion.
---
My recommendation: **See which focal length(s) you like the most on your zoom lens for the look you want - and also see where it puts limitations on your work.** Buy accordingly - but always remember that a more expensive lens does not mean that your photos will automagically get better. I have seen stunning pictures taken with kit lenses - and I have seen pictures taken with five-digit $ lenses that are absolutely tedious.
Note that this also means that **you have to know your gear and its limitations well before the critical shooting**. It also means that going into the shooting, **you should have a concept of what look you want to achieve**. IMHO, routine means everything in professional work.
---
**Regarding equipment in fashion:** Direct sunlight and fashion photography do not get along well ;-) Bring diffusers, reflectors, and maybe even a fill flash. To get all of this working, see if you can find a friend to assist you with holding that stuff.
As mentioned first by [juhist](https://photo.stackexchange.com/a/106689/69369), bring some ND-filters (maybe 1EV and 2 EV) with you, as `sun + fast lens = many, many EVs`.
Also, as [Tetsujin mentions](https://photo.stackexchange.com/a/106690/69369): Primes are not everything. Zoom lenses like the 70-200 f/2.8 (and even f/4) offer incredible performance and don't force you to go with one perspective all the time as prime lenses would. E.g. most of my professional work, I do with my 24-105 f/4, because it works well in all conditions and the shots it offers well over-satisfy the needs of my clients. The below mentioned 100mm f/2.8 is my go-to-lens (ATM) for controlled situations where I *need* the tiny bit of extra performance that it offers.
---
**Anecdote**: A friend of mine is a semi-professional model. In the beginning of her "career", she asked me to help her with her portfolio. We mostly did medium long shots and medium close-ups - mostly "in movement", some more classic still portraits. What lenses did I use? Mostly the 100mm f/2.8L Macro. Was it the only lens that could do the job? No, absolutely not. But I already owned it, it offers a reasonable ability to separate the subject from the background (which I wanted), and I simply love its color rendition. And most importantly: I wanted that exact angle for my work - the photos I made would not have worked well with, say, a 50mm lens. | There's nothing wrong with the existing answers - but my thought is that essentially you're going to be *learning on the job* which is going to bring its own set of issues anyway.
I'd say, yes, rent a lens, but don't rent one in the range you already have, unless you've got a fair amount of money to throw at it.
You are also going to need some soft reflectors &/or diffuse lighting to get rid of the hard shadows a sunny beach scene is going to put in your way, so don't spend all your money on lenses.
...and, as mentioned elsewhere, rent a good set of ND filters so you can shoot wide open in bright light.
I would go for Nikon's top-end 70-200mm zoom - the [Nikon 70-200 f/2.8E FL
FX VR ED N](https://kenrockwell.com/nikon/70-200mm-f28-fl.htm) (Link is to a Ken Rockwell review, who some people love & some people hate ;-). You'll be missing between 55 & 70 mm, but you can probably survive that.
70mm on a crop sensor is about 105mm FF - which some would argue is 'the best' portrait lens length.
I have the FF 50mm 1.4 on crop frame (D5500) & whilst it is definitely my 'best lens', as I don't own a 3 grand zoom like the Nikon, I often shoot portrait with an inferior 70-200 because of the additional depth compression & soft background that can be achieved with it.
I'd even go as far as to say shooting portrait on a longer lens is 'easier' than on a short one. Even when I was a newbie, my family loved to be "papped" at 200mm. They loved the fake intimacy of the paparazzi look over anything I did that they thought they could achieve on their phone.
If you have the money, rent the nifty fifty too, or get Nikon's 24-70 too... but I would really go for a good zoom rather than plumping for one prime. It will just give you flexibility even if you will sacrifice ultimate quality.
A late thought prompted by [xiota's comment](https://photo.stackexchange.com/questions/106686/#comment204837_106686), "sand + salt water + wind + camera + lens = ???"
You may not wish to change lenses at all on a beach.
You don't have a weather-proof camera & this is not a weather-proof lens, so you'll still have to be careful, but...
In that case, & even though it is a (relatively-speaking at £1,000) budget lens, I'd have a look at what I call my 'guilty pleasure' lens - the [Nikon 18-300mm VR
DX AF-S G ED NIKKOR](https://www.kenrockwell.com/nikon/18-300mm.htm) (again, a Rockwell link) as a "do anything" lens. It's not the sharpest in the knife drawer, but it does a fair job most of the way through its range. Your camera can automatically correct for its distortion at least out to 200mm, when it starts to get a bit uncorrectably soft compared to a 'good' lens, but it really doesn't do a bad job at all.
I'd call it a good "learning on the job" lens. |
106,686 | I am quite amateur with a camera but I want to become good in fashion photography. A top model has agreed for a photo-shoot for free and in return she wants me to make a portfolio. We are planning to take the photos on a beach during day light. I have only used a Nikon D5600 and Nikkor AF-P 18-55mm kit lens.
I read in the internet that 50mm on a FX camera is close to what the human eye sees. Also I wanted to keep my distance between me and the model in the range of 3 and 10 meters. So I thought I should rent a 35mm instead as it would give almost 50mm view on a DX camera (35mm x 1.5 crop-factor = 52.5mm). However 35mm view on my kit lens appears zoomed in, its not what my eyes see. Instead the 24mm looks more natural. Is 35mm on a cropped sensor good for fashion photography considering the distance between me and the model ? or should I use 24mm ? | 2019/04/19 | [
"https://photo.stackexchange.com/questions/106686",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/83271/"
] | Photography is not (necessarily) about giving the viewer a "as you would see it"-perspective. Photography is about offering additional perspectives. If this was not true, the only good photos would be with roughly the same angle of view that the human eyes give us, shot at eye-height.
This, however, is not true. I would even go as far as to say: Those are the most boring photos that anyone can make.
**It is much more about whether you like the look that 24mm deliver or not.** You can make stunning photos with all focal lengths just as you can make boring ones. **It all depends on what you want to do.** And that still holds true in fashion.
---
My recommendation: **See which focal length(s) you like the most on your zoom lens for the look you want - and also see where it puts limitations on your work.** Buy accordingly - but always remember that a more expensive lens does not mean that your photos will automagically get better. I have seen stunning pictures taken with kit lenses - and I have seen pictures taken with five-digit $ lenses that are absolutely tedious.
Note that this also means that **you have to know your gear and its limitations well before the critical shooting**. It also means that going into the shooting, **you should have a concept of what look you want to achieve**. IMHO, routine means everything in professional work.
---
**Regarding equipment in fashion:** Direct sunlight and fashion photography do not get along well ;-) Bring diffusers, reflectors, and maybe even a fill flash. To get all of this working, see if you can find a friend to assist you with holding that stuff.
As mentioned first by [juhist](https://photo.stackexchange.com/a/106689/69369), bring some ND-filters (maybe 1EV and 2 EV) with you, as `sun + fast lens = many, many EVs`.
Also, as [Tetsujin mentions](https://photo.stackexchange.com/a/106690/69369): Primes are not everything. Zoom lenses like the 70-200 f/2.8 (and even f/4) offer incredible performance and don't force you to go with one perspective all the time as prime lenses would. E.g. most of my professional work, I do with my 24-105 f/4, because it works well in all conditions and the shots it offers well over-satisfy the needs of my clients. The below mentioned 100mm f/2.8 is my go-to-lens (ATM) for controlled situations where I *need* the tiny bit of extra performance that it offers.
---
**Anecdote**: A friend of mine is a semi-professional model. In the beginning of her "career", she asked me to help her with her portfolio. We mostly did medium long shots and medium close-ups - mostly "in movement", some more classic still portraits. What lenses did I use? Mostly the 100mm f/2.8L Macro. Was it the only lens that could do the job? No, absolutely not. But I already owned it, it offers a reasonable ability to separate the subject from the background (which I wanted), and I simply love its color rendition. And most importantly: I wanted that exact angle for my work - the photos I made would not have worked well with, say, a 50mm lens. | **While 35mm *is* suitable for some shots, I wouldn't go into a shoot with *just* a 35mm.** Some suggestions, some of which depend on how much time you have with the model:
* **Pick up a** fashion magazine or **fashion photography book.** Consider the equipment that was used for the shots you like. Books about fashion illustration are also interesting to look at.
* **Shoot at a few closely related locations** – nearby park, boardwalk, harbor, on pier, under pier, on beach by interesting landmark, in the water, etc. I'd leave the beach for last because of the sand and water. Also, if you wait till the sun has gone down a bit, the lighting won't be as harsh.
* **Plan a couple different styles of dress.** Have interchangeable clothing items to provide different looks without having to change too much.
* **Try to include plenty of variety** in framing and distances.
* Consider 24-70/4 or 24-120/4 (for versatility). F2.8 and wider is fine, but you might end up stopping down anyway because you need DOF to cover clothing details, *not* "just a few mm for just the eyes".
* Consider 70-200/4 (to avoid jumping in the water with the model).
* *Buy* a nifty fifty (50/1.8). Don't rent it. If you don't like it, resell it. The 10-15% sales fee should be less than the cost to rent would have been.
* Agree with others: Diffusers, reflectors, flash, *assistant*, etc. |
106,686 | I am quite amateur with a camera but I want to become good in fashion photography. A top model has agreed for a photo-shoot for free and in return she wants me to make a portfolio. We are planning to take the photos on a beach during day light. I have only used a Nikon D5600 and Nikkor AF-P 18-55mm kit lens.
I read in the internet that 50mm on a FX camera is close to what the human eye sees. Also I wanted to keep my distance between me and the model in the range of 3 and 10 meters. So I thought I should rent a 35mm instead as it would give almost 50mm view on a DX camera (35mm x 1.5 crop-factor = 52.5mm). However 35mm view on my kit lens appears zoomed in, its not what my eyes see. Instead the 24mm looks more natural. Is 35mm on a cropped sensor good for fashion photography considering the distance between me and the model ? or should I use 24mm ? | 2019/04/19 | [
"https://photo.stackexchange.com/questions/106686",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/83271/"
] | There's nothing wrong with the existing answers - but my thought is that essentially you're going to be *learning on the job* which is going to bring its own set of issues anyway.
I'd say, yes, rent a lens, but don't rent one in the range you already have, unless you've got a fair amount of money to throw at it.
You are also going to need some soft reflectors &/or diffuse lighting to get rid of the hard shadows a sunny beach scene is going to put in your way, so don't spend all your money on lenses.
...and, as mentioned elsewhere, rent a good set of ND filters so you can shoot wide open in bright light.
I would go for Nikon's top-end 70-200mm zoom - the [Nikon 70-200 f/2.8E FL
FX VR ED N](https://kenrockwell.com/nikon/70-200mm-f28-fl.htm) (Link is to a Ken Rockwell review, who some people love & some people hate ;-). You'll be missing between 55 & 70 mm, but you can probably survive that.
70mm on a crop sensor is about 105mm FF - which some would argue is 'the best' portrait lens length.
I have the FF 50mm 1.4 on crop frame (D5500) & whilst it is definitely my 'best lens', as I don't own a 3 grand zoom like the Nikon, I often shoot portrait with an inferior 70-200 because of the additional depth compression & soft background that can be achieved with it.
I'd even go as far as to say shooting portrait on a longer lens is 'easier' than on a short one. Even when I was a newbie, my family loved to be "papped" at 200mm. They loved the fake intimacy of the paparazzi look over anything I did that they thought they could achieve on their phone.
If you have the money, rent the nifty fifty too, or get Nikon's 24-70 too... but I would really go for a good zoom rather than plumping for one prime. It will just give you flexibility even if you will sacrifice ultimate quality.
A late thought prompted by [xiota's comment](https://photo.stackexchange.com/questions/106686/#comment204837_106686), "sand + salt water + wind + camera + lens = ???"
You may not wish to change lenses at all on a beach.
You don't have a weather-proof camera & this is not a weather-proof lens, so you'll still have to be careful, but...
In that case, & even though it is a (relatively-speaking at £1,000) budget lens, I'd have a look at what I call my 'guilty pleasure' lens - the [Nikon 18-300mm VR
DX AF-S G ED NIKKOR](https://www.kenrockwell.com/nikon/18-300mm.htm) (again, a Rockwell link) as a "do anything" lens. It's not the sharpest in the knife drawer, but it does a fair job most of the way through its range. Your camera can automatically correct for its distortion at least out to 200mm, when it starts to get a bit uncorrectably soft compared to a 'good' lens, but it really doesn't do a bad job at all.
I'd call it a good "learning on the job" lens. | Some simple trigonometry can help here, but it's just an estimate... Let's say your model is 1.7m tall. In order to capture a pose at full height, assuming portrait orientation, you're going to need an angle of view on the long side of your sensor of between about 10 and 32 degrees (at 10 meters and 3 meters, respectively). For other poses, if you assume about half his/her full height, you would need between 5 and 16 degrees. On my 1.6X crop sensor Canon, those numbers correspond to about 38-250mm in focal length. Your 1.5X Nikon would be a little different than that (40-270mm or so), but that does tend to indicate the 35mm might be a bit short for keeping your expected distance. Of course, that doesn't include extra space for framing (you probably don't want the model to take up the entire image in every shot...), so you can probably reduce that estimate a bit, and maybe 35mm is right on the edge of what you are looking for. A 50mm, 85mm or 100mm might be a good idea to have along as well (or even just a zoom that covers a good portion of those in its range). |
106,686 | I am quite amateur with a camera but I want to become good in fashion photography. A top model has agreed for a photo-shoot for free and in return she wants me to make a portfolio. We are planning to take the photos on a beach during day light. I have only used a Nikon D5600 and Nikkor AF-P 18-55mm kit lens.
I read in the internet that 50mm on a FX camera is close to what the human eye sees. Also I wanted to keep my distance between me and the model in the range of 3 and 10 meters. So I thought I should rent a 35mm instead as it would give almost 50mm view on a DX camera (35mm x 1.5 crop-factor = 52.5mm). However 35mm view on my kit lens appears zoomed in, its not what my eyes see. Instead the 24mm looks more natural. Is 35mm on a cropped sensor good for fashion photography considering the distance between me and the model ? or should I use 24mm ? | 2019/04/19 | [
"https://photo.stackexchange.com/questions/106686",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/83271/"
] | There's nothing wrong with the existing answers - but my thought is that essentially you're going to be *learning on the job* which is going to bring its own set of issues anyway.
I'd say, yes, rent a lens, but don't rent one in the range you already have, unless you've got a fair amount of money to throw at it.
You are also going to need some soft reflectors &/or diffuse lighting to get rid of the hard shadows a sunny beach scene is going to put in your way, so don't spend all your money on lenses.
...and, as mentioned elsewhere, rent a good set of ND filters so you can shoot wide open in bright light.
I would go for Nikon's top-end 70-200mm zoom - the [Nikon 70-200 f/2.8E FL
FX VR ED N](https://kenrockwell.com/nikon/70-200mm-f28-fl.htm) (Link is to a Ken Rockwell review, who some people love & some people hate ;-). You'll be missing between 55 & 70 mm, but you can probably survive that.
70mm on a crop sensor is about 105mm FF - which some would argue is 'the best' portrait lens length.
I have the FF 50mm 1.4 on crop frame (D5500) & whilst it is definitely my 'best lens', as I don't own a 3 grand zoom like the Nikon, I often shoot portrait with an inferior 70-200 because of the additional depth compression & soft background that can be achieved with it.
I'd even go as far as to say shooting portrait on a longer lens is 'easier' than on a short one. Even when I was a newbie, my family loved to be "papped" at 200mm. They loved the fake intimacy of the paparazzi look over anything I did that they thought they could achieve on their phone.
If you have the money, rent the nifty fifty too, or get Nikon's 24-70 too... but I would really go for a good zoom rather than plumping for one prime. It will just give you flexibility even if you will sacrifice ultimate quality.
A late thought prompted by [xiota's comment](https://photo.stackexchange.com/questions/106686/#comment204837_106686), "sand + salt water + wind + camera + lens = ???"
You may not wish to change lenses at all on a beach.
You don't have a weather-proof camera & this is not a weather-proof lens, so you'll still have to be careful, but...
In that case, & even though it is a (relatively-speaking at £1,000) budget lens, I'd have a look at what I call my 'guilty pleasure' lens - the [Nikon 18-300mm VR
DX AF-S G ED NIKKOR](https://www.kenrockwell.com/nikon/18-300mm.htm) (again, a Rockwell link) as a "do anything" lens. It's not the sharpest in the knife drawer, but it does a fair job most of the way through its range. Your camera can automatically correct for its distortion at least out to 200mm, when it starts to get a bit uncorrectably soft compared to a 'good' lens, but it really doesn't do a bad job at all.
I'd call it a good "learning on the job" lens. | It depends on what kind of look you want and how long is your possible working distance.
I would rent at least 35mm and 50mm primes. For shooting human subjects, you don't always want the field of view that human eye sees. Humans remember the looks of other humans as they appear from a quite long distance (sorry I don't now find a source which says what the distance is). At short distance, [the ears can look smaller than they appear from long distance](https://photo.stackexchange.com/a/76335/81735).
Also, you may want to throw the background out of focus with background blur. Now, to achieve background blur, you can either use a wide aperture (but this decreases depth of field), or a long focal length (this can create background blur without too shallow depth of field).
Additionally, if you want to emphasize the human subject, 50mm would be good. If you want to emphasize the environment the human subject is in, and capture as much of the environment as possible, 35mm or 24mm would be good. However, your kit lens already has the 24mm aperture and background blur with 24mm is low and depth of field deep, so a faster aperture than your kit lens doesn't buy you really anything.
If you have a model for free, now is not the time to save on equipment and use only one focal length.
My suggestion is therefore:
* Use your kit lens for 24mm and shorter, use it wide open (which is probably around f/4)
* Rent a fast 35mm prime
* Rent a fast 50mm prime, at 10 meter distance the field of view is 4.8 m x 3.2 m which seems large enough, and you can get some beautiful background blur at this focal length and fast aperture
If you really really want to save on lens rental costs, I would pick the 50mm and use the kit lens for 35mm too. The reasoning being that background blur at 35mm is more difficult than at 50mm, so the fast aperture of a fast prime is more beneficial for 50mm prime than it is for 35mm prime. Furthermore, the aperture of the kit lens is slower at 50mm than it is at 35mm, so that too favors renting the 50mm over 35mm.
If you have the money to throw at lens rentals, consider renting an 85mm lens too. It is a focal length you can't achieve with your kit lens. The pictures will have narrow field of view and therefore have to be taken from a really long distance, but you may find it useful in some cases. A 85mm can achieve really good background blur, **at the same time** as having a deep enough depth of field.
Oh, and you may need an ND filter to use f/1.8 in sunlight, because the lowest ISO of your camera is probably ISO 100, and the fastest shutter speed is 1/4000 s.
Consider also lighting: powerful enough fill flash, diffuser, etc. can alter the lighting in ways you can't achieve with only sunlight.
Useful:
* [Field of view calculator](https://www.scantips.com/lights/fieldofview.html)
* [Depth of field calculator](http://www.dofmaster.com/dofjs.html)
Some cost estimates at lensrentals.com:
* Nikon 50mm f/1.8 costs $13 for 2 days
* Nikon 50mm f/1.4 costs $19 for 2 days
* Nikon 35mm f/1.8 costs $25 for 2 days
* Nikon 85mm f/1.8 costs $20 for 2 days
To me, it's clear that you want to rent at least the 50mm f/1.8 based on these because it's so cheap, if not going for the 50mm f/1.4! |
106,686 | I am quite amateur with a camera but I want to become good in fashion photography. A top model has agreed for a photo-shoot for free and in return she wants me to make a portfolio. We are planning to take the photos on a beach during day light. I have only used a Nikon D5600 and Nikkor AF-P 18-55mm kit lens.
I read in the internet that 50mm on a FX camera is close to what the human eye sees. Also I wanted to keep my distance between me and the model in the range of 3 and 10 meters. So I thought I should rent a 35mm instead as it would give almost 50mm view on a DX camera (35mm x 1.5 crop-factor = 52.5mm). However 35mm view on my kit lens appears zoomed in, its not what my eyes see. Instead the 24mm looks more natural. Is 35mm on a cropped sensor good for fashion photography considering the distance between me and the model ? or should I use 24mm ? | 2019/04/19 | [
"https://photo.stackexchange.com/questions/106686",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/83271/"
] | There's nothing wrong with the existing answers - but my thought is that essentially you're going to be *learning on the job* which is going to bring its own set of issues anyway.
I'd say, yes, rent a lens, but don't rent one in the range you already have, unless you've got a fair amount of money to throw at it.
You are also going to need some soft reflectors &/or diffuse lighting to get rid of the hard shadows a sunny beach scene is going to put in your way, so don't spend all your money on lenses.
...and, as mentioned elsewhere, rent a good set of ND filters so you can shoot wide open in bright light.
I would go for Nikon's top-end 70-200mm zoom - the [Nikon 70-200 f/2.8E FL
FX VR ED N](https://kenrockwell.com/nikon/70-200mm-f28-fl.htm) (Link is to a Ken Rockwell review, who some people love & some people hate ;-). You'll be missing between 55 & 70 mm, but you can probably survive that.
70mm on a crop sensor is about 105mm FF - which some would argue is 'the best' portrait lens length.
I have the FF 50mm 1.4 on crop frame (D5500) & whilst it is definitely my 'best lens', as I don't own a 3 grand zoom like the Nikon, I often shoot portrait with an inferior 70-200 because of the additional depth compression & soft background that can be achieved with it.
I'd even go as far as to say shooting portrait on a longer lens is 'easier' than on a short one. Even when I was a newbie, my family loved to be "papped" at 200mm. They loved the fake intimacy of the paparazzi look over anything I did that they thought they could achieve on their phone.
If you have the money, rent the nifty fifty too, or get Nikon's 24-70 too... but I would really go for a good zoom rather than plumping for one prime. It will just give you flexibility even if you will sacrifice ultimate quality.
A late thought prompted by [xiota's comment](https://photo.stackexchange.com/questions/106686/#comment204837_106686), "sand + salt water + wind + camera + lens = ???"
You may not wish to change lenses at all on a beach.
You don't have a weather-proof camera & this is not a weather-proof lens, so you'll still have to be careful, but...
In that case, & even though it is a (relatively-speaking at £1,000) budget lens, I'd have a look at what I call my 'guilty pleasure' lens - the [Nikon 18-300mm VR
DX AF-S G ED NIKKOR](https://www.kenrockwell.com/nikon/18-300mm.htm) (again, a Rockwell link) as a "do anything" lens. It's not the sharpest in the knife drawer, but it does a fair job most of the way through its range. Your camera can automatically correct for its distortion at least out to 200mm, when it starts to get a bit uncorrectably soft compared to a 'good' lens, but it really doesn't do a bad job at all.
I'd call it a good "learning on the job" lens. | **While 35mm *is* suitable for some shots, I wouldn't go into a shoot with *just* a 35mm.** Some suggestions, some of which depend on how much time you have with the model:
* **Pick up a** fashion magazine or **fashion photography book.** Consider the equipment that was used for the shots you like. Books about fashion illustration are also interesting to look at.
* **Shoot at a few closely related locations** – nearby park, boardwalk, harbor, on pier, under pier, on beach by interesting landmark, in the water, etc. I'd leave the beach for last because of the sand and water. Also, if you wait till the sun has gone down a bit, the lighting won't be as harsh.
* **Plan a couple different styles of dress.** Have interchangeable clothing items to provide different looks without having to change too much.
* **Try to include plenty of variety** in framing and distances.
* Consider 24-70/4 or 24-120/4 (for versatility). F2.8 and wider is fine, but you might end up stopping down anyway because you need DOF to cover clothing details, *not* "just a few mm for just the eyes".
* Consider 70-200/4 (to avoid jumping in the water with the model).
* *Buy* a nifty fifty (50/1.8). Don't rent it. If you don't like it, resell it. The 10-15% sales fee should be less than the cost to rent would have been.
* Agree with others: Diffusers, reflectors, flash, *assistant*, etc. |
10,885,365 | I've got a console application and I want to run it from another application. But when I invoke it from code--to call program I use ActiveXObject--it shows the console. How do I get it to not show the console? I mean, the program works but console is shown. | 2012/06/04 | [
"https://Stackoverflow.com/questions/10885365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1432980/"
] | If you make the application a *Windows Application* instead of a *Console Application* it will not show or open (or use) a Console. Your code can stay the same - and the application will still function (without ever creating a `Form` or `Window`).
That being said, if you control the "other" application, you may want to consider making a class library instead of a separate Application. This would allow you to just include and run code within the library without starting a separate process. | You can create it as a Windows Forms application with a hidden window. That's just one possibility like Reed Copsey pointed out, i used it once because i needed to process some specific Window Messages. |
20,405,949 | I have an image processing application that is CPU intensive and is developed in c++ (The images are sourced from webcam in realtime).This application should be run on **client side.**
I want to start, pause, transfer data, and exit the c++ application through a web browser.
So basically my UI will be HTML+Javascript on **client side again.**
I dont want to use NPAPI as my main target browser is G. Chrome which is phasing it out.
I cant use Native Client as it does not support access to webcam because of the sandbox issue.
Is there any way to communicate between c++ and js in the same machine?
I am happy with a windows solution ...
The ideal would be a multi browser solution (chrome,firefox,ie)
Many thanks in advance, | 2013/12/05 | [
"https://Stackoverflow.com/questions/20405949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3071145/"
] | ```
<Button
android:id="@+id/QuitMenu"
```
So change
```
Button exit = (Button) findViewById(R.id.QuitGame);// id is QuitMenu
```
to
```
Button exit = (Button) findViewById(R.id.QuitMenu);
```
Edit:
```
<activity
android:name=".MenuActivity"
android:launchMode="standard"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="@string/app_name">
</activity>
```
And Change
```
startActivity (newIntent("android.intent.action.MAIN"));
```
To
```
startActivity (new Intent(MenuActivity.this,MainActivity.class));
``` | `QuitGame` is text property of button not id. Id is `QuitMenu`. |
8,996,205 | I have a dropdown list that auto submits a form and performs a search that I use throughout a project via a partial view, but it only works the first time I use it, unless I refresh the page. It’s an MVC 4 with jQuery Mobile project.
Here is the code I have in my partial view,
```
<script type="text/javascript">
$(function () {
$("#CoastLineID").change(function () {
var actionUrl = $('#TheForm').attr('action') + '/' + $('#CoastLineID').val();
$('#TheForm').attr('action', actionUrl);
$('#TheForm').submit();
});
});
</script>
<p>
@using (Html.BeginForm("SearchCoast", "Home", FormMethod.Post, new { id = "TheForm" }))
{
@Html.DropDownList("CoastLineID", (SelectList)ViewBag.ArticleId, "Select a Coastline")
}
</p>
```
I guess I need to be able to refresh the page or the list each time a page/view that uses the partial view is loaded somehow. Is this a jQuery issue???
Any ideas, I can put the URL up for the site if I’m allowed to?
**Update/Edit**
Thanks guys,
I’ve come across a few issues mixing jQuery Mobile and MVC and mostly due to the way they both handle URL strings differently, all coming from 15 years of web development. All the jQuery Mobile docs deal with classic URL strings e.g.. about/us.html which is not the MVC way!
This is my controller code to populate the dropdown,
```
var coastlines = db.CoastLines.Select(c => new { c.CoastLineID, c.CoastLineName });
ViewBag.CoastLineId = new SelectList(coastlines.AsEnumerable(), "CoastLineID", "CoastLineName", 0);
```
And this is the web site,
<http://www.peninsulaguide.com.au/>
Click “Beach Search” and then “Select a Coastline” or “Select a Town” will work but nothing after that without a refresh.
There are two dropdowns but it doesn’t make a difference if I remove one.
Cheers,
Mike | 2012/01/25 | [
"https://Stackoverflow.com/questions/8996205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | you have to set two thingies
* disable grid showing
* zero row/column intercell spacing
In code:
```
table.setShowGrid(false);
table.setIntercellSpacing(new Dimension(0, 0));
```
Or use JXTable (from the [SwingX project](http://swingx.java.net)) which does it for you:
```
xTable.setShowGrid(false, false);
``` | just jTable1.setShowHorizontalLines(false); or jTable1.setShowVerticalLines(false); or you can use the 2 option
```
jTable1.setShowHorizontalLines(false);
jTable1.setShowVerticalLines(false);
``` |
10,822,717 | Kiva has an API available at <http://build.kiva.org>
We also have occasional snapshots of anonymized (to the best of our ability) data from the API. We're working now on making these snapshots update regularly, say once a week. They are big in total, 350MB compressed, > 1GB uncompressed. However, they are made up of hundreds of JSON files, and thus could benefit from git in terms of just pulling down changes.
We'd like to move our snapshots into Git and Github, to take advantage of their hosting as well as to make getting updates to the snapshots go a lot faster. Indeed, I've put up one commit of just the current snapshot here: <https://github.com/coderintherye/kivaloans>
However, we have a desire to not keep the git history, because we want to not make it easy to grab past history, so as to piece together data over time. The reasoning of course is that we have a legal responsibility to protect user privacy, and we have a realistic expectation that no matter how much we try to anonymize the data, if enough of it is put together, it's possible that user activity could be pinpointed to groups or individuals such as what happened with the Netflix contest: <http://www.wired.com/threatlevel/2010/03/netflix-cancels-contest/>
Is there a way we could use Git and provide the data, while not keeping the history? One option we're considering is using git, but using rebase -i to clobber previous commits. But in order to get any benefit from Git, I think we'd at least need to keep the previous commit, and of course anyone who didn't pull regularly wouldn't get much benefit at all, because they wouldn't have the old commit to reference (or so we think?)
Or is the expectation of attempting to be good citizens with data in this way an unreasonable expectation? If so, we can abandon the idea altogether. | 2012/05/30 | [
"https://Stackoverflow.com/questions/10822717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/293306/"
] | GitHub has the ability to upload static files for download outside of source control. This is often used by projects for providing pre-compiled binary installers or other large files.
You can use their [Repo Downloads](http://developer.github.com/v3/repos/downloads/) API to automate this. | Alternative idea: use a local git repository with full history, and employ a "build process" to publish particular snapshots up to GitHub. Example:
1. You make a series of commits and check them into your local repo
2. You decide to publish the local repo, so you start by tagging it (for good measure).
3. Your "build process" has access to a clone of the GitHub repo. In it's checkout, it deletes all the local files and preforms an export (*not* a checkout) of the local repo - specifically, of the last tagged version.
4. Exported files are committed and pushed up to GitHub.
5. GitHub repo has history, but only of snapshots.
You could employ some kind of tagging or commit message convention to make it easy to relate public commits to private commits, without exposing private history.
This "build process" would just be a script of some kind, nothing fancy. |
10,822,717 | Kiva has an API available at <http://build.kiva.org>
We also have occasional snapshots of anonymized (to the best of our ability) data from the API. We're working now on making these snapshots update regularly, say once a week. They are big in total, 350MB compressed, > 1GB uncompressed. However, they are made up of hundreds of JSON files, and thus could benefit from git in terms of just pulling down changes.
We'd like to move our snapshots into Git and Github, to take advantage of their hosting as well as to make getting updates to the snapshots go a lot faster. Indeed, I've put up one commit of just the current snapshot here: <https://github.com/coderintherye/kivaloans>
However, we have a desire to not keep the git history, because we want to not make it easy to grab past history, so as to piece together data over time. The reasoning of course is that we have a legal responsibility to protect user privacy, and we have a realistic expectation that no matter how much we try to anonymize the data, if enough of it is put together, it's possible that user activity could be pinpointed to groups or individuals such as what happened with the Netflix contest: <http://www.wired.com/threatlevel/2010/03/netflix-cancels-contest/>
Is there a way we could use Git and provide the data, while not keeping the history? One option we're considering is using git, but using rebase -i to clobber previous commits. But in order to get any benefit from Git, I think we'd at least need to keep the previous commit, and of course anyone who didn't pull regularly wouldn't get much benefit at all, because they wouldn't have the old commit to reference (or so we think?)
Or is the expectation of attempting to be good citizens with data in this way an unreasonable expectation? If so, we can abandon the idea altogether. | 2012/05/30 | [
"https://Stackoverflow.com/questions/10822717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/293306/"
] | GitHub has the ability to upload static files for download outside of source control. This is often used by projects for providing pre-compiled binary installers or other large files.
You can use their [Repo Downloads](http://developer.github.com/v3/repos/downloads/) API to automate this. | Well, the ultimate solution we decided here is perhaps unconventional, but should work for us.
We'll keep only the latest two snapshots in their json file form, and if there is a problem with the data, we will flip the repository to be private. Then, when the data is fixed and/or scrubbed to the degree needed, we'll flip it back to public.
In addition though we are probably going to provide the full snapshots via the repo download API, as suggested by AlanBarber. |
2,635,188 | I have the function $f(x)={7x^6+8x+2}$ and I'm trying to prove that $f$ has *exactly* 2 real roots.
**What I've done:**
The only *kind of* solution I have come up with is essentially guessing pairs of values for $x$ that give $f$ a different sign and then make use of Bolzano's Theorem.
More specifically:
* $f(-1)=1>0$ and $f(-{1\over 2})=-{121\over 64}<0$, so according to Bolzano's Theorem, there is some $x \in (-1, -{1 \over 2})$ such that $f(x)=0$.
* $f(-{1\over 2})=-{121\over 64}<0$ and $f(0)=2$, so according to Bolzano's Theorem, there is some $x \in (-{1 \over 2}, 0)$ such that $f(x)=0$.
**Question:**
The above solution looks kind of *meh* to me and I don't think it proves there are *exactly* 2 real roots, but rather that only 2 were found. Is there a better, more convincing way to prove the existence of *exactly* 2 roots? | 2018/02/04 | [
"https://math.stackexchange.com/questions/2635188",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/349270/"
] | **Hint**
You proved so far that there are at least 2 solutions.
If the function would have 3 or more solutions, then by Rolle's Theorem, $f'$ would have at least 2 solutions. | We just have to count the intersections between the graph of $g(x)=7x^6$ and the graph of $h(x)=-8x-2$. By convexity, they can be either $0,1$ or $2$.
$f(x)$ has a sign change over $\left[-1,-\frac{1}{2}\right]$ and another sign change over $\left[-\frac{1}{2},0\right]$.
It follows that $f(x)$ has exactly $2$ real roots.
One of them is pretty close to $-\frac{1}{4}$ since $7x^6$ is negligible in a small neighbourhood of the origin. |
2,635,188 | I have the function $f(x)={7x^6+8x+2}$ and I'm trying to prove that $f$ has *exactly* 2 real roots.
**What I've done:**
The only *kind of* solution I have come up with is essentially guessing pairs of values for $x$ that give $f$ a different sign and then make use of Bolzano's Theorem.
More specifically:
* $f(-1)=1>0$ and $f(-{1\over 2})=-{121\over 64}<0$, so according to Bolzano's Theorem, there is some $x \in (-1, -{1 \over 2})$ such that $f(x)=0$.
* $f(-{1\over 2})=-{121\over 64}<0$ and $f(0)=2$, so according to Bolzano's Theorem, there is some $x \in (-{1 \over 2}, 0)$ such that $f(x)=0$.
**Question:**
The above solution looks kind of *meh* to me and I don't think it proves there are *exactly* 2 real roots, but rather that only 2 were found. Is there a better, more convincing way to prove the existence of *exactly* 2 roots? | 2018/02/04 | [
"https://math.stackexchange.com/questions/2635188",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/349270/"
] | $$f''(x)=7\cdot6\cdot5x^4\geq0,$$ which says that $f$ is a convex function.
Thus, $f$ has two roots maximum and by your work we get two roots exactly. | We have:
$f(x)=7x^6+8x+2$. On differentiating,
$f'(x)=42x^5+8$ which has one solution and the solution is $x=-0.718$. Now, you can be sure that your polynomial equation has at the most two roots. To prove exactly two roots, divide the real line in two intervals $(-\infty,-0.718]$ and $[-0.718,\infty)$. Now, you can check (using the sign of derivative) in the first Interval, the function is decreasing and in the second Interval function is increasing.
Also, note that the function takes positive values at the end of Interval and negative value in the neighborhood of your critical point which is $-0.718$. Can you guess what this means. This means, the function cuts the x-axis two times. In the first and second Interval. Hence, function has exactly two roots. |
2,635,188 | I have the function $f(x)={7x^6+8x+2}$ and I'm trying to prove that $f$ has *exactly* 2 real roots.
**What I've done:**
The only *kind of* solution I have come up with is essentially guessing pairs of values for $x$ that give $f$ a different sign and then make use of Bolzano's Theorem.
More specifically:
* $f(-1)=1>0$ and $f(-{1\over 2})=-{121\over 64}<0$, so according to Bolzano's Theorem, there is some $x \in (-1, -{1 \over 2})$ such that $f(x)=0$.
* $f(-{1\over 2})=-{121\over 64}<0$ and $f(0)=2$, so according to Bolzano's Theorem, there is some $x \in (-{1 \over 2}, 0)$ such that $f(x)=0$.
**Question:**
The above solution looks kind of *meh* to me and I don't think it proves there are *exactly* 2 real roots, but rather that only 2 were found. Is there a better, more convincing way to prove the existence of *exactly* 2 roots? | 2018/02/04 | [
"https://math.stackexchange.com/questions/2635188",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/349270/"
] | Hint: by [Descartes' rule of signs](https://en.wikipedia.org/wiki/Descartes%27_rule_of_signs) the equation has no positive real roots, and at most $2$ negative ones. But you showed that it has *at least* one real root (and it's enough that $\,f(-1/2) \lt 0 \lt f(0)\,$ for that), then it must have a second real one, since non-real complex roots come in conjugate pairs. | We have:
$f(x)=7x^6+8x+2$. On differentiating,
$f'(x)=42x^5+8$ which has one solution and the solution is $x=-0.718$. Now, you can be sure that your polynomial equation has at the most two roots. To prove exactly two roots, divide the real line in two intervals $(-\infty,-0.718]$ and $[-0.718,\infty)$. Now, you can check (using the sign of derivative) in the first Interval, the function is decreasing and in the second Interval function is increasing.
Also, note that the function takes positive values at the end of Interval and negative value in the neighborhood of your critical point which is $-0.718$. Can you guess what this means. This means, the function cuts the x-axis two times. In the first and second Interval. Hence, function has exactly two roots. |
2,635,188 | I have the function $f(x)={7x^6+8x+2}$ and I'm trying to prove that $f$ has *exactly* 2 real roots.
**What I've done:**
The only *kind of* solution I have come up with is essentially guessing pairs of values for $x$ that give $f$ a different sign and then make use of Bolzano's Theorem.
More specifically:
* $f(-1)=1>0$ and $f(-{1\over 2})=-{121\over 64}<0$, so according to Bolzano's Theorem, there is some $x \in (-1, -{1 \over 2})$ such that $f(x)=0$.
* $f(-{1\over 2})=-{121\over 64}<0$ and $f(0)=2$, so according to Bolzano's Theorem, there is some $x \in (-{1 \over 2}, 0)$ such that $f(x)=0$.
**Question:**
The above solution looks kind of *meh* to me and I don't think it proves there are *exactly* 2 real roots, but rather that only 2 were found. Is there a better, more convincing way to prove the existence of *exactly* 2 roots? | 2018/02/04 | [
"https://math.stackexchange.com/questions/2635188",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/349270/"
] | We have:
$f(x)=7x^6+8x+2$. On differentiating,
$f'(x)=42x^5+8$ which has one solution and the solution is $x=-0.718$. Now, you can be sure that your polynomial equation has at the most two roots. To prove exactly two roots, divide the real line in two intervals $(-\infty,-0.718]$ and $[-0.718,\infty)$. Now, you can check (using the sign of derivative) in the first Interval, the function is decreasing and in the second Interval function is increasing.
Also, note that the function takes positive values at the end of Interval and negative value in the neighborhood of your critical point which is $-0.718$. Can you guess what this means. This means, the function cuts the x-axis two times. In the first and second Interval. Hence, function has exactly two roots. | We just have to count the intersections between the graph of $g(x)=7x^6$ and the graph of $h(x)=-8x-2$. By convexity, they can be either $0,1$ or $2$.
$f(x)$ has a sign change over $\left[-1,-\frac{1}{2}\right]$ and another sign change over $\left[-\frac{1}{2},0\right]$.
It follows that $f(x)$ has exactly $2$ real roots.
One of them is pretty close to $-\frac{1}{4}$ since $7x^6$ is negligible in a small neighbourhood of the origin. |
2,635,188 | I have the function $f(x)={7x^6+8x+2}$ and I'm trying to prove that $f$ has *exactly* 2 real roots.
**What I've done:**
The only *kind of* solution I have come up with is essentially guessing pairs of values for $x$ that give $f$ a different sign and then make use of Bolzano's Theorem.
More specifically:
* $f(-1)=1>0$ and $f(-{1\over 2})=-{121\over 64}<0$, so according to Bolzano's Theorem, there is some $x \in (-1, -{1 \over 2})$ such that $f(x)=0$.
* $f(-{1\over 2})=-{121\over 64}<0$ and $f(0)=2$, so according to Bolzano's Theorem, there is some $x \in (-{1 \over 2}, 0)$ such that $f(x)=0$.
**Question:**
The above solution looks kind of *meh* to me and I don't think it proves there are *exactly* 2 real roots, but rather that only 2 were found. Is there a better, more convincing way to prove the existence of *exactly* 2 roots? | 2018/02/04 | [
"https://math.stackexchange.com/questions/2635188",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/349270/"
] | We have:
$f(x)=7x^6+8x+2$. On differentiating,
$f'(x)=42x^5+8$ which has one solution and the solution is $x=-0.718$. Now, you can be sure that your polynomial equation has at the most two roots. To prove exactly two roots, divide the real line in two intervals $(-\infty,-0.718]$ and $[-0.718,\infty)$. Now, you can check (using the sign of derivative) in the first Interval, the function is decreasing and in the second Interval function is increasing.
Also, note that the function takes positive values at the end of Interval and negative value in the neighborhood of your critical point which is $-0.718$. Can you guess what this means. This means, the function cuts the x-axis two times. In the first and second Interval. Hence, function has exactly two roots. | $f'(x)$=42$x^5$+8
$f''(x)$ =210$x^4$
now you can observe that the double derivative of your function is always positive for all values of x in $R$ and also that
$f'(x)$ is negative for x=-1 and positive for x=1, hence $f'(x)$ is zero atleast once (USING IMVT)
but since $f''(x)=0$ has no real root hence, $f'(x)=0$ has only a single real root.
And now using ROLLE'S THEOREM,we can say that $f(x)=0$ has at most two real roots or say atleast 4 complex roots.Now since $f(x)$ is negative at x=-1/2 and positive at x=-1. Thus, $f(x) =0$ has a real root.
Since, there are atleast 4 complex roots but they occur in pairs so they can be either 6 or 4 in number. But we already have one solution for $f(x) =0$,there are 4 complex solution or exactly 2 real roots. |
2,635,188 | I have the function $f(x)={7x^6+8x+2}$ and I'm trying to prove that $f$ has *exactly* 2 real roots.
**What I've done:**
The only *kind of* solution I have come up with is essentially guessing pairs of values for $x$ that give $f$ a different sign and then make use of Bolzano's Theorem.
More specifically:
* $f(-1)=1>0$ and $f(-{1\over 2})=-{121\over 64}<0$, so according to Bolzano's Theorem, there is some $x \in (-1, -{1 \over 2})$ such that $f(x)=0$.
* $f(-{1\over 2})=-{121\over 64}<0$ and $f(0)=2$, so according to Bolzano's Theorem, there is some $x \in (-{1 \over 2}, 0)$ such that $f(x)=0$.
**Question:**
The above solution looks kind of *meh* to me and I don't think it proves there are *exactly* 2 real roots, but rather that only 2 were found. Is there a better, more convincing way to prove the existence of *exactly* 2 roots? | 2018/02/04 | [
"https://math.stackexchange.com/questions/2635188",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/349270/"
] | $$f''(x)=7\cdot6\cdot5x^4\geq0,$$ which says that $f$ is a convex function.
Thus, $f$ has two roots maximum and by your work we get two roots exactly. | **Hint**
You proved so far that there are at least 2 solutions.
If the function would have 3 or more solutions, then by Rolle's Theorem, $f'$ would have at least 2 solutions. |
2,635,188 | I have the function $f(x)={7x^6+8x+2}$ and I'm trying to prove that $f$ has *exactly* 2 real roots.
**What I've done:**
The only *kind of* solution I have come up with is essentially guessing pairs of values for $x$ that give $f$ a different sign and then make use of Bolzano's Theorem.
More specifically:
* $f(-1)=1>0$ and $f(-{1\over 2})=-{121\over 64}<0$, so according to Bolzano's Theorem, there is some $x \in (-1, -{1 \over 2})$ such that $f(x)=0$.
* $f(-{1\over 2})=-{121\over 64}<0$ and $f(0)=2$, so according to Bolzano's Theorem, there is some $x \in (-{1 \over 2}, 0)$ such that $f(x)=0$.
**Question:**
The above solution looks kind of *meh* to me and I don't think it proves there are *exactly* 2 real roots, but rather that only 2 were found. Is there a better, more convincing way to prove the existence of *exactly* 2 roots? | 2018/02/04 | [
"https://math.stackexchange.com/questions/2635188",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/349270/"
] | Hint: by [Descartes' rule of signs](https://en.wikipedia.org/wiki/Descartes%27_rule_of_signs) the equation has no positive real roots, and at most $2$ negative ones. But you showed that it has *at least* one real root (and it's enough that $\,f(-1/2) \lt 0 \lt f(0)\,$ for that), then it must have a second real one, since non-real complex roots come in conjugate pairs. | **Hint**
You proved so far that there are at least 2 solutions.
If the function would have 3 or more solutions, then by Rolle's Theorem, $f'$ would have at least 2 solutions. |
2,635,188 | I have the function $f(x)={7x^6+8x+2}$ and I'm trying to prove that $f$ has *exactly* 2 real roots.
**What I've done:**
The only *kind of* solution I have come up with is essentially guessing pairs of values for $x$ that give $f$ a different sign and then make use of Bolzano's Theorem.
More specifically:
* $f(-1)=1>0$ and $f(-{1\over 2})=-{121\over 64}<0$, so according to Bolzano's Theorem, there is some $x \in (-1, -{1 \over 2})$ such that $f(x)=0$.
* $f(-{1\over 2})=-{121\over 64}<0$ and $f(0)=2$, so according to Bolzano's Theorem, there is some $x \in (-{1 \over 2}, 0)$ such that $f(x)=0$.
**Question:**
The above solution looks kind of *meh* to me and I don't think it proves there are *exactly* 2 real roots, but rather that only 2 were found. Is there a better, more convincing way to prove the existence of *exactly* 2 roots? | 2018/02/04 | [
"https://math.stackexchange.com/questions/2635188",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/349270/"
] | Reading all of the given answers and using elements from the proposed solutions, I came up with the following explanation:
1. By calculating the first derivative of $f$, which is $f'(x)=42x^5+8$, we get that:
* $f$ has an extremum at $f'(x)=0\Leftrightarrow x=-\left({4 \over 21}\right)^{{1 \over 5}}≈-0.718$ with $f(-0.718)≈-2.785$.
* $f$ is strictly decreasing in $(-\infty, -0.718)$.
* $f$ is strictly increasing in $(-0.718, \infty)$.
* The extremum is a minimum.
2. By calculating the second derivative of $f$, which is $f''(x)=210x^4$, we get that:
* $f$ is strictly convex in $ℝ$, because $f''(x)=210x^4 ≥0,\ \ ∀\ \ x ∈ ℝ$.
* $f$ has an undulation point at $x=0$, because $f''(0)=0$.
Taking into account that $f$ has a minimum at $(-0.718, -2.785)$, which is located below the real axis, and that $f$ is strictly convex in $ℝ$, it is evident that $f$ intersects with the real axis at exactly two points, which are the roots of $f$. | We just have to count the intersections between the graph of $g(x)=7x^6$ and the graph of $h(x)=-8x-2$. By convexity, they can be either $0,1$ or $2$.
$f(x)$ has a sign change over $\left[-1,-\frac{1}{2}\right]$ and another sign change over $\left[-\frac{1}{2},0\right]$.
It follows that $f(x)$ has exactly $2$ real roots.
One of them is pretty close to $-\frac{1}{4}$ since $7x^6$ is negligible in a small neighbourhood of the origin. |
2,635,188 | I have the function $f(x)={7x^6+8x+2}$ and I'm trying to prove that $f$ has *exactly* 2 real roots.
**What I've done:**
The only *kind of* solution I have come up with is essentially guessing pairs of values for $x$ that give $f$ a different sign and then make use of Bolzano's Theorem.
More specifically:
* $f(-1)=1>0$ and $f(-{1\over 2})=-{121\over 64}<0$, so according to Bolzano's Theorem, there is some $x \in (-1, -{1 \over 2})$ such that $f(x)=0$.
* $f(-{1\over 2})=-{121\over 64}<0$ and $f(0)=2$, so according to Bolzano's Theorem, there is some $x \in (-{1 \over 2}, 0)$ such that $f(x)=0$.
**Question:**
The above solution looks kind of *meh* to me and I don't think it proves there are *exactly* 2 real roots, but rather that only 2 were found. Is there a better, more convincing way to prove the existence of *exactly* 2 roots? | 2018/02/04 | [
"https://math.stackexchange.com/questions/2635188",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/349270/"
] | Hint: by [Descartes' rule of signs](https://en.wikipedia.org/wiki/Descartes%27_rule_of_signs) the equation has no positive real roots, and at most $2$ negative ones. But you showed that it has *at least* one real root (and it's enough that $\,f(-1/2) \lt 0 \lt f(0)\,$ for that), then it must have a second real one, since non-real complex roots come in conjugate pairs. | $f'(x)$=42$x^5$+8
$f''(x)$ =210$x^4$
now you can observe that the double derivative of your function is always positive for all values of x in $R$ and also that
$f'(x)$ is negative for x=-1 and positive for x=1, hence $f'(x)$ is zero atleast once (USING IMVT)
but since $f''(x)=0$ has no real root hence, $f'(x)=0$ has only a single real root.
And now using ROLLE'S THEOREM,we can say that $f(x)=0$ has at most two real roots or say atleast 4 complex roots.Now since $f(x)$ is negative at x=-1/2 and positive at x=-1. Thus, $f(x) =0$ has a real root.
Since, there are atleast 4 complex roots but they occur in pairs so they can be either 6 or 4 in number. But we already have one solution for $f(x) =0$,there are 4 complex solution or exactly 2 real roots. |
2,635,188 | I have the function $f(x)={7x^6+8x+2}$ and I'm trying to prove that $f$ has *exactly* 2 real roots.
**What I've done:**
The only *kind of* solution I have come up with is essentially guessing pairs of values for $x$ that give $f$ a different sign and then make use of Bolzano's Theorem.
More specifically:
* $f(-1)=1>0$ and $f(-{1\over 2})=-{121\over 64}<0$, so according to Bolzano's Theorem, there is some $x \in (-1, -{1 \over 2})$ such that $f(x)=0$.
* $f(-{1\over 2})=-{121\over 64}<0$ and $f(0)=2$, so according to Bolzano's Theorem, there is some $x \in (-{1 \over 2}, 0)$ such that $f(x)=0$.
**Question:**
The above solution looks kind of *meh* to me and I don't think it proves there are *exactly* 2 real roots, but rather that only 2 were found. Is there a better, more convincing way to prove the existence of *exactly* 2 roots? | 2018/02/04 | [
"https://math.stackexchange.com/questions/2635188",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/349270/"
] | $$f''(x)=7\cdot6\cdot5x^4\geq0,$$ which says that $f$ is a convex function.
Thus, $f$ has two roots maximum and by your work we get two roots exactly. | Reading all of the given answers and using elements from the proposed solutions, I came up with the following explanation:
1. By calculating the first derivative of $f$, which is $f'(x)=42x^5+8$, we get that:
* $f$ has an extremum at $f'(x)=0\Leftrightarrow x=-\left({4 \over 21}\right)^{{1 \over 5}}≈-0.718$ with $f(-0.718)≈-2.785$.
* $f$ is strictly decreasing in $(-\infty, -0.718)$.
* $f$ is strictly increasing in $(-0.718, \infty)$.
* The extremum is a minimum.
2. By calculating the second derivative of $f$, which is $f''(x)=210x^4$, we get that:
* $f$ is strictly convex in $ℝ$, because $f''(x)=210x^4 ≥0,\ \ ∀\ \ x ∈ ℝ$.
* $f$ has an undulation point at $x=0$, because $f''(0)=0$.
Taking into account that $f$ has a minimum at $(-0.718, -2.785)$, which is located below the real axis, and that $f$ is strictly convex in $ℝ$, it is evident that $f$ intersects with the real axis at exactly two points, which are the roots of $f$. |
11,619,177 | Is there a GUI tool out there that will allow me to migrate entire SQL Server 2008 R2 databases to MySQL? I have MySQL Workbench installed, but it looks like there isn't a feature in it like SSIS to copy and paste entire databases from SQL Server. I downloaded the MySQL Migration Toolkit, but it is no longer supported and I get a Java error when running it. | 2012/07/23 | [
"https://Stackoverflow.com/questions/11619177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1423787/"
] | The new version of MySQL Workbench incorporated the old Migration Toolkit. You can now do direct imports / exports between different databases inside of MySQL Workbench.
To get to the Migration Wizard, click on 'Database' on the tab menu. Then select 'Migrate' | You might want to try [Navicat Premium](http://www.navicat.com) |
11,619,177 | Is there a GUI tool out there that will allow me to migrate entire SQL Server 2008 R2 databases to MySQL? I have MySQL Workbench installed, but it looks like there isn't a feature in it like SSIS to copy and paste entire databases from SQL Server. I downloaded the MySQL Migration Toolkit, but it is no longer supported and I get a Java error when running it. | 2012/07/23 | [
"https://Stackoverflow.com/questions/11619177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1423787/"
] | What version of the Workbench brings back the Migration Toolkit? I don't see it in 5.2.45 CE so maybe this is a full version feature? | You might want to try [Navicat Premium](http://www.navicat.com) |
11,619,177 | Is there a GUI tool out there that will allow me to migrate entire SQL Server 2008 R2 databases to MySQL? I have MySQL Workbench installed, but it looks like there isn't a feature in it like SSIS to copy and paste entire databases from SQL Server. I downloaded the MySQL Migration Toolkit, but it is no longer supported and I get a Java error when running it. | 2012/07/23 | [
"https://Stackoverflow.com/questions/11619177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1423787/"
] | The new version of MySQL Workbench incorporated the old Migration Toolkit. You can now do direct imports / exports between different databases inside of MySQL Workbench.
To get to the Migration Wizard, click on 'Database' on the tab menu. Then select 'Migrate' | What version of the Workbench brings back the Migration Toolkit? I don't see it in 5.2.45 CE so maybe this is a full version feature? |
16,140 | To put this in context, what I need to do to complete work on a custom action is to hide a particular column from users who aren't members of a given group. Given that the custom action is implemented with C# code, I'm looking for a tidy way to do this programmatically.
For a brief moment, it looked like a single line of code would do the trick:
```
SPContext.Current.List.DefaultView.ViewFields.Delete("Name Of Column I Want To Hide");
```
Even though the view seems to change internally, this statement seems to have no effect.
There are a few available examples that use ViewFields.Delete, but they're all followed by calls to ViewFields.Update() - in other words, they presume that you want to ***permanently*** remove the column. But I just want to remove it for the current context.
Can anyone here enlighten me as to what tactic might work in this case?
Thanks in advance
Josh | 2011/07/13 | [
"https://sharepoint.stackexchange.com/questions/16140",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/3730/"
] | WIth the standard controls, it's not possible to put authorization on viewing/editing on a field. The smallest scope is per listitem.
I don't know if this would be an option:
* create two listviews and put them on your page, both with an audience on it: one for group 1, one for the others.
this is no security, but this way you are hiding that one column for that one specific audience. | You can accomplish this without coding using [SharePoint Forms Designer](http://spform.com), it allow to display or hide specified fields on forms just by dragging and dropping it, you also can create forms with different fields displayed for specified SharePoint group. |
70,500 | I would like to go from a list of words through a dedicated command, for instance `\listofwords{one word;one longer word;word and word}` to the expanded list of the same words, ie:
```
\begin{list}{}
\item one word
\item one longer word
\item word and word
\end{list}
```
and the initial list could store more (or less) semicolon-separated words.
**Edit** The following may be more challenging: how to go from two different lists, `\listofwords{word;wordd;worddd}` and `\listofterms{term;termm;termmm}` to
```
\begin{list}{}{}
\item word term
\item wordd termm
\item worddd termmm
\end{list}
```
where `worddd` (or any other of the lists above) could store several space-separated words. Based on the previous answers, I had a look at the `xparse` and `etoolbox` packages but could no find any useful solution :( | 2012/09/06 | [
"https://tex.stackexchange.com/questions/70500",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/371/"
] | The problem is that the operation leaves something after the last `\\` (or `\cr`) which starts a new cell (albeit producing no output). So operating in that way inside a `tabular` (aka as `\halign`) is dangerous; you'd better build the table in a token list variable and deliver it:
```
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\DeclareDocumentCommand \myTable {m}
{
\seq_set_split:Nnn \l_tmpa_seq {,} {#1}
\tl_set:Nn \l_tmpa_tl { \begin{tabular}{|c|c|} }
\seq_map_inline:Nn \l_tmpa_seq
{
\tl_put_right:Nn \l_tmpa_tl { Entry & ##1 \\ }
}
\tl_put_right:Nn \l_tmpa_tl { \end{tabular} }
\tl_use:N \l_tmpa_tl
}
\ExplSyntaxOff
\begin{document}
\myTable{A,B,C,D}
\end{document}
``` | The problem disappears when you use an explicit function for the rows rather than an inline function. (By the way, the function could be taken out of the macro in this case, but I prefer to have it locally.)
```
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\DeclareDocumentCommand \myTable {m} {
\newcommand{\myrow}[1]{Entry&##1\cr}
\seq_set_split:Nnn \l_tmpa_seq {,} {#1}
\begin{tabular}{|c|c|}\seq_map_function:NN \l_tmpa_seq \myrow \end{tabular}
}
\ExplSyntaxOff
\begin{document}
\myTable{A,B,C,D}
\end{document}
```
[![enter image description here](https://i.stack.imgur.com/KFSIj.png)](https://i.stack.imgur.com/KFSIj.png) |
34,549,508 | I use Webpack dev server for development and would like to use [hot module replacement](https://webpack.github.io/docs/webpack-dev-server.html#hot-module-replacement) feature, but when I run dev server I get error:
```
ERROR in debug (bower component)
Module not found: Error: Cannot resolve 'file' or 'directory' ./dist/debug.js in /Users/and/devel/WebstormProjects/Wonderland_front/node_modules/webpack-dev-server/node_modules/sockjs-client/node_modules/debug
@ debug (bower component) 1:17-43
```
**package.json**
```
{
"name": "Wond",
"version": "0.0.1",
"description": "Internal evidence application",
"main": "index.jsx",
"scripts": {
"start": "npm run serve | npm run dev",
"serve": "./node_modules/.bin/http-server -p 8080",
"dev": "webpack-dev-server -d --hot --inline --progress --colors --port 8090"
},
"author": "And",
"license": "ISC",
"devDependencies": {
"autoprefixer": "^6.2.2",
"babel-core": "^6.0.20",
"babel-loader": "^6.0.1",
"babel-preset-es2015": "^6.0.15",
"babel-preset-react": "^6.0.15",
"backbone": "^1.2.3",
"bootstrap": "^3.3.5",
"bootstrap-select": "^1.9.3",
"bower-webpack-plugin": "^0.1.9",
"cookies-js": "^1.2.2",
"css-loader": "^0.23.0",
"eonasdan-bootstrap-datetimepicker": "^4.15.35",
"events": "^1.1.0",
"extract-text-webpack-plugin": "^0.9.0",
"file-loader": "^0.8.5",
"flux": "^2.1.1",
"html-webpack-plugin": "^1.7.0",
"http-server": "^0.8.5",
"immutable": "^3.7.6",
"immutablediff": "0.4.2",
"jquery": "^2.1.4",
"jquery-resizable-columns": "^0.2.3",
"jquery-ui": "^1.10.5",
"json-markup": "^0.1.6",
"less": "^2.5.3",
"less-loader": "^2.2.2",
"lodash": "^3.10.1",
"moment": "^2.10.6",
"node-sass": "^3.4.1",
"object-assign": "^4.0.1",
"path": "^0.12.7",
"postcss": "^5.0.13",
"postcss-loader": "^0.8.0",
"react": "^0.14.3",
"react-dom": "^0.14.3",
"react-hot-loader": "^1.3.0",
"react-mixin": "^3.0.3",
"sass-loader": "^3.1.2",
"select2": "^4.0.0",
"select2-bootstrap-css": "^1.4.6",
"style-loader": "^0.13.0",
"svg-sprite-loader": "0.0.2",
"typeahead.js": "^0.11.1",
"url-loader": "^0.5.7",
"webpack": "^1.12.9",
"webpack-dev-server": "^1.14.0",
"webpack-merge": "^0.5.1"
}
}
```
**webpack.config.js**
```
var webpack = require('webpack');
var merge = require('webpack-merge');
var BowerWebpackPlugin = require("bower-webpack-plugin");
var autoprefixer = require('autoprefixer');
const TARGET = process.env.npm_lifecycle_event;
console.log("target is event is " + TARGET);
var common = {
cache: true,
debug: true,
entry: './src/script/index.jsx',
resolve: {
extensions: ['', '.js', '.jsx']
},
output: {
sourceMapFilename: '[file].map'
},
module: {
loaders: [
{
test: /\.js[x]?$/,
loaders: ['react-hot', 'babel'],
exclude: /(node_modules|bower_components|other_modules)/
},
{test: /\.css$/, loaders: ['style', 'css']},
{test: /\.scss$/, loaders: ['style', 'css', 'postcss', 'sass']},
{test: /\.less$/, loaders: ['style', 'css', 'less']},
{ test: /\.woff$/, loader: "url-loader?limit=10000&mimetype=application/font-woff&name=[path][name].[ext]" },
{ test: /\.woff2$/, loader: "url-loader?limit=10000&mimetype=application/font-woff2&name=[path][name].[ext]" },
{test: /\.(eot|ttf|svg|gif|png)$/, loader: "file-loader"}
]
},
plugins: [
new BowerWebpackPlugin()
],
postcss: function () {
return [autoprefixer({browsers: ['last 3 versions']})];
}
};
if(TARGET === 'dev' || !TARGET) {
module.exports = merge(common,{
devtool: 'eval-source-map',
devServer: {
historyApiFallback: true,
// display only errors to reduce the amount of output
stats: 'errors-only'
},
output: {
filename: 'index.js',
publicPath: 'http://localhost:8090/assets'
}
});
}
```
If I remove `--hot` and `--inline` flags, dev server works (without hot module replacement feature). | 2015/12/31 | [
"https://Stackoverflow.com/questions/34549508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/968379/"
] | Reference: <http://dev.mysql.com/doc/refman/5.6/en/timestamp-initialization.html>
The behavior you observe is defined behavior for the first `TIMESTAMP` column defined in the table.
When both `DEFAULT` and `ON UPDATE` are *omitted* from the column definition (when the column is added to the table), e.g.
```
mycol TIMESTAMP NOT NULL
```
MySQL (helpfully?) sees that as if you had actually specified
```
mycol TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
```
(The output from `SHOW CREATE TABLE mytable` will show that the column is defined as if you had specified that.)
You can disable the `ON UPDATE` behavior (i.e. avoid that from being added to the column definition) by specifying a `DEFAULT`
```
ALTER TABLE mytable
mycol TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
```
When only the DEFAULT is specified, then MySQL doesn't automatically add the `ON UPDATE`.
---
The MySQL Reference Manual documents this behavior. | use datetime rather than timestamp as the type for the columns you dont want the update to happen. |
273,338 | I have a view that shows nodes and groups them by their taxonomy term. Is it possible to show less fields for a specific term? For example there are user profiles with names and pictures that are listed, but if they have a specific taxonomy term the picture field shall not be shown. | 2018/11/30 | [
"https://drupal.stackexchange.com/questions/273338",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/69568/"
] | These types of problems are often solved by creating another Views display.
1. Add a Filter to your original Views to only show the results with the terms where you want to show the additional fields.
2. Then Duplicate this display as Attachment, attach it to the original views display.
3. Override the Attachment Filters and change the one for the terms - reverse the choices to filter out only the terms where you *don't* want additional fields
4. Override the Attachment Fields, remove the ones you don't want.
The Attachment results will display below or above the original results, depending on whether you choose to attach it After or Before. | Try preprocessing the views field.
Something like this is a good starting place:
<https://drupal.stackexchange.com/a/36712/80164>
Note that if you only need to preprocess a certain field, the function to use is `template_preprocess_views_view_field(&$vars)`:
<https://api.drupal.org/api/drupal/core%21modules%21views%21views.theme.inc/function/template_preprocess_views_view_field/8.6.x> |
3,776,708 | Have somebody tried to rewrite CanCan ActiverRecordAddtions for
Mongoid <http://github.com/ryanb/cancan/blob/master/lib/cancan/active_record_additions.rb>
Regards,
Alexey Zakharov | 2010/09/23 | [
"https://Stackoverflow.com/questions/3776708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/161287/"
] | I've managed to get CanCan and Mongoid (version 2) to work together pretty well on a rails 3 app. Still get some errors here and there related to conditions in the permission definition (the Ability model).
I just put the contents of this gist into a file in config/initializers:
* <http://gist.github.com/561639>
The condition hashes are almost the same as with ActiveRecord:
```
# can only manage own account
can :manage, User, :_id => current_user.id
```
I'm still working on how to use more advanced Mongoid::Criteria conditions, but you can always use a block to do more complex conditions:
```
# can only manage own account
can :eat, Cake do
current_user.jobs.any?{ |job| job.title == 'Peasant'}
end
``` | I know it's an old one, but for those who search mongoid and cancancan integration, you could try official mongoid adapter
For cacancan gem version >2.0 there's separate gem [cancacan-mongoid](https://github.com/CanCanCommunity/cancancan-mongoid)
Bear in mind that this gem status is "in development", but still it's working pretty well and build passing |
52,250,895 | my understanding is this
I have
```
class Season(models.Model):
drama = models.ForeignKey('Drama', on_delete=models.CASCADE)
```
so in my views.py
```
def seasons(request, slug):
drama = Drama.objects.get(name=drama_name)
seasons = Season.objects.filter(drama)
```
because I have drama as foreignkey for seasons, I can use drama.name with seasons in views.py using \_ underbar? but it says
'drama\_name' is not defined
What am I missing? | 2018/09/10 | [
"https://Stackoverflow.com/questions/52250895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10335816/"
] | Since you want to filter seasons by a given drama name, presumably stored in `slug`, you should simply filter the `Seasons` queryset like this (note the double underscores denoting the use of the `name` field in the foreign key `drama`):
```
def seasons(request, slug):
seasons = Season.objects.filter(drama__name=slug)
``` | Try `drama__name`. Note the two `_`'s. See <https://docs.djangoproject.com/en/2.1/topics/db/queries/#field-lookups> and <https://docs.djangoproject.com/en/2.1/topics/db/queries/#lookups-that-span-relationships> |
47,920,238 | I am using the jquery ui range slider.
Trying to add comma to the numbers so it will bore readable.
tried like yo different ways including [regex](https://stackoverflow.com/questions/15808773/add-comma-separator-to-a-value-variable) and `parseFloat`but without success.
this is the [jsfiddle](https://jsfiddle.net/davseveloff/L01900xc/). | 2017/12/21 | [
"https://Stackoverflow.com/questions/47920238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3471458/"
] | You should use `self` to invoke the instance methods. So, change your `apply` function to
```
def apply(self):
rules = [{'action': 'replace'}, {'action': 'split'}, {'action': 'remove'}]
return [eval('self._perform_' + r['action'])() for r in rules
if r['action'] in ['replace', 'split', 'remove']]
```
**Note**: Using `eval` is a bad practice. You can find the reason [here](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice)
You can make use of `getattr` instead.
**For example**(this example is just to illustrate how `getattr` is working)
```
class SomeClass(object):
def apply(self):
method_to_be_called = "_perform_replace"
SomeClass.method_caller(method_to_be_called)(self)
# Invoke like this if you want your function to accept args.
# SomeClass.method_caller(method_to_be_called, args1, args2,...)(self)
def _perform_replace(self):
print("performing replace")
def _perform_split(self):
print("performing split")
def _perform_remove(self):
print("performing remove")
@staticmethod
def method_caller(name_, *args, **kwargs):
def caller(obj):
return getattr(obj, name_)(*args, **kwargs)
return caller
``` | Your example is a little involved, but if you want to call functions based on some logic, you can just use the function like a pointer. Here is an example:
```
class SomeClass(object):
@staticmethod
def apply():
rules = [{'action':SomeClass.test()}]
return rules[0]['action']
@staticmethod
def test():
print("test")
SomeClass.apply()
>test
```
I'm not sure if you are familiar with `staticmethods` but if your functions can live at their own, you can `decorate` your functions to be static to call them from anywhere. |
32,578,487 | Question link: <http://codeforces.com/contest/2/problem/B>
There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that
starts in the upper left cell of the matrix;
each following cell is to the right or down from the current cell;
the way ends in the bottom right cell.
Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros.
Input
The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 10^9).
Output
In the first line print the least number of trailing zeros. In the second line print the correspondent way itself.
I thought of the following: In the end, whatever the answer will be, it should contain minimum powers of 2's and 5's. Therefore, what I did was, for each entry in the input matrix, I calculated the powers of 2's and 5's and stored them in separate matrices.
```
for (i = 0; i < n; i++)
{
for ( j = 0; j < n; j++)
{
cin>>foo;
matrix[i][j] = foo;
int n1 = calctwo(foo); // calculates the number of 2's in factorisation of that number
int n2 = calcfive(foo); // calculates number of 5's
two[i][j] = n1;
five[i][j] = n2;
}
}
```
After that, I did this:
```
for (i = 0; i < n; i++)
{
for ( j = 0; j < n; j++ )
{
dp[i][j] = min(two[i][j],five[i][j]); // Here, dp[i][j] will store minimum number of 2's and 5's.
}
}
```
But the above doesn't really a valid answer, I don't know why? Have I implemented the correct approach? Or, is this the correct way of solving this question?
Edit: Here are my functions of calculating the number of two's and number of five's in a number.
```
int calctwo (int foo)
{
int counter = 0;
while (foo%2 == 0)
{
if (foo%2 == 0)
{
counter++;
foo = foo/2;
}
else
break;
}
return counter;
}
int calcfive (int foo)
{
int counter = 0;
while (foo%5 == 0)
{
if (foo%5 == 0)
{
counter++;
foo = foo/5;
}
else
break;
}
return counter;
}
```
Edit2: I/O Example as given in the link:
Input:
```
3
1 2 3
4 5 6
7 8 9
```
Output:
```
0
DDRR
``` | 2015/09/15 | [
"https://Stackoverflow.com/questions/32578487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4112864/"
] | Since you are interested only in the number of trailing zeroes you need only to consider the powers of `2`, `5` which you could keep in two separate `nxn` arrays. So for the array
```
1 2 3
4 5 6
7 8 9
```
you just keep the arrays
```
the powers of 2 the powers of 5
0 1 0 0 0 0
2 0 1 0 1 0
0 3 0 0 0 0
```
The insight for the problem is the following. Notice that if you find a path which minimizes the sum of the powers of 2 and a path which minimizes the number sum of the powers of 5 then the answer is the one with lower value of those two paths. So you reduce your problem to the two times application of the following classical dp problem: find a path, starting from the top-left corner and ending at the bottom-right, such that the sum of its elements is minimum. Again, following the example, we have:
```
minimal path for the
powers of 2 value
* * - 2
- * *
- - *
minimal path for the
powers of 5 value
* - - 0
* - -
* * *
```
so your answer is
```
* - -
* - -
* * *
```
with value `0`
**Note 1**
It might seem that taking the minimum of the both optimal paths gives only an upper bound so a question that may rise is: is this bound actually achieved? The answer is yes. For convenience, let the number of 2's along the 2's optimal path is `a` and the number of 5's along the 5's optimal path is `b`. Without loss of generality assume that the minimum of the both optimal paths is the one for the power of 2's (that is `a < b`). Let the number of 5's along the minimal path is `c`. Now the question is: are there as much as 5's as there are 2's along this path (i.e. is `c >= a`?). Assume that the answer is no. That means that there are less 5's than 2's along the minimal path (that is `c < a`). Since the optimal value of 5's paths is `b` we have that every 5's path has at least `b` 5's in it. This should also be true for the minimal path. That means that `c > b`. We have that `c < a` so `a > b` but the initial assumption was that `a < b`. Contradiction.
**Note 2**
You might also want consider the case in which there is an element `0` in your matrix. I'd assume that number of trailing zeroes when the product is 1. In this case, if the algorithm has produced a result with a value more than 1 you should output 1 and print a path that goes through the element `0`. | Here is the code. I've used `pair<int,int>` to store factor of 2 and 5 in the matrix.
```
#include<vector>
#include<iostream>
using namespace std;
#define pii pair<int,int>
#define F first
#define S second
#define MP make_pair
int calc2(int a){
int c=0;
while(a%2==0){
c++;
a/=2;
}
return c;
}
int calc5(int a){
int c=0;
while(a%5==0){
c++;
a/=5;
}
return c;
}
int mini(int a,int b){
return a<b?a:b;
}
pii min(pii a, pii b){
if(mini(a.F,a.S) < mini(b.F,b.S))
return a;
return b;
}
int main(){
int n;
cin>>n;
vector<vector<pii > > v;
vector<vector<int> > path;
int i,j;
for(i=0;i<n;i++){
vector<pii > x;
vector<int> q(n,0);
for(j=0;j<n;j++){
int y;cin>>y;
x.push_back(MP(calc2(y),calc5(y))); //I store factors of 2,5 in the vector to calculate
}
x.push_back(MP(100000,100000)); //padding each row to n+1 elements (to handle overflow in code)
v.push_back(x);
path.push_back(q); //initialize path matrix to 0
}
vector<pii > x(n+1,MP(100000,100000));
v.push_back(x); //pad 1 more row to handle index overflow
for(i=n-1;i>=0;i--){
for(j=n-1;j>=0;j--){ //move from destination to source grid
if(i==n-1 && j==n-1)
continue;
//here, the LHS of condition in if block is the condition which determines minimum number of trailing 0's. This is the same condition that is used to manipulate "v" for getting the same result.
if(min(MP(v[i][j].F+v[i+1][j].F,v[i][j].S+v[i+1][j].S), MP(v[i][j].F+v[i][j+1].F,v[i][j].S+v[i][j+1].S)) == MP(v[i][j].F+v[i+1][j].F,v[i][j].S+v[i+1][j].S))
path[i][j] = 1; //go down
else
path[i][j] = 2; //go right
v[i][j] = min(MP(v[i][j].F+v[i+1][j].F,v[i][j].S+v[i+1][j].S), MP(v[i][j].F+v[i][j+1].F,v[i][j].S+v[i][j+1].S));
}
}
cout<<mini(v[0][0].F, v[0][0].S)<<endl; //print result
for(i=0,j=0;i<=n-1 && j<=n-1;){ //print path (I don't know o/p format)
cout<<"("<<i<<","<<j<<") -> ";
if(path[i][j]==1)
i++;
else
j++;
}
return 0;
}
```
This code gives fine results as far as the test cases I checked. If you have any doubts regarding this code, ask in comments.
EDIT:
The basic thought process.
To reach the destination, there are only 2 options. I started with destination to avoid the problem of path ahead calculation, because if 2 have same minimum values, then we chose any one of them. If the path to destination is already calculated, it does not matter which we take.
And minimum is to check which pair is more suitable. If a pair has minimum 2's or 5's than other, it will produce less 0's. |
32,578,487 | Question link: <http://codeforces.com/contest/2/problem/B>
There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that
starts in the upper left cell of the matrix;
each following cell is to the right or down from the current cell;
the way ends in the bottom right cell.
Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros.
Input
The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 10^9).
Output
In the first line print the least number of trailing zeros. In the second line print the correspondent way itself.
I thought of the following: In the end, whatever the answer will be, it should contain minimum powers of 2's and 5's. Therefore, what I did was, for each entry in the input matrix, I calculated the powers of 2's and 5's and stored them in separate matrices.
```
for (i = 0; i < n; i++)
{
for ( j = 0; j < n; j++)
{
cin>>foo;
matrix[i][j] = foo;
int n1 = calctwo(foo); // calculates the number of 2's in factorisation of that number
int n2 = calcfive(foo); // calculates number of 5's
two[i][j] = n1;
five[i][j] = n2;
}
}
```
After that, I did this:
```
for (i = 0; i < n; i++)
{
for ( j = 0; j < n; j++ )
{
dp[i][j] = min(two[i][j],five[i][j]); // Here, dp[i][j] will store minimum number of 2's and 5's.
}
}
```
But the above doesn't really a valid answer, I don't know why? Have I implemented the correct approach? Or, is this the correct way of solving this question?
Edit: Here are my functions of calculating the number of two's and number of five's in a number.
```
int calctwo (int foo)
{
int counter = 0;
while (foo%2 == 0)
{
if (foo%2 == 0)
{
counter++;
foo = foo/2;
}
else
break;
}
return counter;
}
int calcfive (int foo)
{
int counter = 0;
while (foo%5 == 0)
{
if (foo%5 == 0)
{
counter++;
foo = foo/5;
}
else
break;
}
return counter;
}
```
Edit2: I/O Example as given in the link:
Input:
```
3
1 2 3
4 5 6
7 8 9
```
Output:
```
0
DDRR
``` | 2015/09/15 | [
"https://Stackoverflow.com/questions/32578487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4112864/"
] | Since you are interested only in the number of trailing zeroes you need only to consider the powers of `2`, `5` which you could keep in two separate `nxn` arrays. So for the array
```
1 2 3
4 5 6
7 8 9
```
you just keep the arrays
```
the powers of 2 the powers of 5
0 1 0 0 0 0
2 0 1 0 1 0
0 3 0 0 0 0
```
The insight for the problem is the following. Notice that if you find a path which minimizes the sum of the powers of 2 and a path which minimizes the number sum of the powers of 5 then the answer is the one with lower value of those two paths. So you reduce your problem to the two times application of the following classical dp problem: find a path, starting from the top-left corner and ending at the bottom-right, such that the sum of its elements is minimum. Again, following the example, we have:
```
minimal path for the
powers of 2 value
* * - 2
- * *
- - *
minimal path for the
powers of 5 value
* - - 0
* - -
* * *
```
so your answer is
```
* - -
* - -
* * *
```
with value `0`
**Note 1**
It might seem that taking the minimum of the both optimal paths gives only an upper bound so a question that may rise is: is this bound actually achieved? The answer is yes. For convenience, let the number of 2's along the 2's optimal path is `a` and the number of 5's along the 5's optimal path is `b`. Without loss of generality assume that the minimum of the both optimal paths is the one for the power of 2's (that is `a < b`). Let the number of 5's along the minimal path is `c`. Now the question is: are there as much as 5's as there are 2's along this path (i.e. is `c >= a`?). Assume that the answer is no. That means that there are less 5's than 2's along the minimal path (that is `c < a`). Since the optimal value of 5's paths is `b` we have that every 5's path has at least `b` 5's in it. This should also be true for the minimal path. That means that `c > b`. We have that `c < a` so `a > b` but the initial assumption was that `a < b`. Contradiction.
**Note 2**
You might also want consider the case in which there is an element `0` in your matrix. I'd assume that number of trailing zeroes when the product is 1. In this case, if the algorithm has produced a result with a value more than 1 you should output 1 and print a path that goes through the element `0`. | Here is a solution proposal using Javascript and functional programming.
It relies on several functions:
* the core function is `smallest_trailer` that recursively goes through the grid. I have chosen to go in 4 possible direction, left "L", right "R", down "D" and "U". It is not possible to pass twice on the same cell. The direction that is chosen is the one with the smallest number of trailing zeros. The counting of trailing zeros is devoted to another function.
* the function `zero_trailer(p,n,nbz)` assumes that you arrive on a cell with a value `p` while you already have an accumulator `n` and met `nbz` zeros on your way. The function returns an array with two elements, the new number of zeros and the new accumulator. The accumulator will be a power of 2 or 5. The function uses the auxiliary function `pow_2_5(n)` that returns the powers of 2 and 5 inside `n`.
* Other functions are more anecdotical: `deepCopy(arr)` makes a standard deep copy of the array `arr`, `out_bound(i,j,n)` returns true if the cell `(i,j)` is out of bound of the grid of size `n`, `myMinIndex(arr)` returns the min index of an array of 2 dimensional arrays (each subarray contains the nb of trailing zeros and the path as a string). The min is only taken on the first element of subarrays.
* `MAX_SAFE_INTEGER` is a (large) constant for the maximal number of trailing zeros when the path is wrong (goes out of bound for example).
Here is the code, which works on the example given in the comments above and in the orginal link.
```
var MAX_SAFE_INTEGER = 9007199254740991;
function pow_2_5(n) {
// returns the power of 2 and 5 inside n
function pow_not_2_5(k) {
if (k%2===0) {
return pow_not_2_5(k/2);
}
else if (k%5===0) {
return pow_not_2_5(k/5);
}
else {
return k;
}
}
return n/pow_not_2_5(n);
}
function zero_trailer(p,n,nbz) {
// takes an input two numbers p and n that should be multiplied and a given initial number of zeros (nbz = nb of zeros)
// n is the accumulator of previous multiplications (a power of 5 or 2)
// returns an array [kbz, k] where kbz is the total new number of zeros (nbz + the trailing zeros from the multiplication of p and n)
// and k is the new accumulator (typically a power of 5 or 2)
function zero_aux(k,kbz) {
if (k===0) {
return [1,0];
}
else if (k%10===0) {
return zero_aux(k/10,kbz+1);
}
else {
return [kbz,k];
}
}
return zero_aux(pow_2_5(p)*n,nbz);
}
function out_bound(i,j,n) {
return !((i>=0)&&(i<n)&&(j>=0)&&(j<n));
}
function deepCopy(arr){
var toR = new Array(arr.length);
for(var i=0;i<arr.length;i++){
var toRi = new Array(arr[i].length);
for(var j=0;j<arr[i].length;j++){
toRi[j] = arr[i][j];
}
toR[i] = toRi;
}
return toR;
}
function myMinIndex(arr) {
var min = arr[0][0];
var minIndex = 0;
for (var i = 1; i < arr.length; i++) {
if (arr[i][0] < min) {
minIndex = i;
min = arr[i][0];
}
}
return minIndex;
}
function smallest_trailer(grid) {
var n = grid.length;
function st_aux(i,j,grid_aux, acc_mult, nb_z, path) {
if ((i===n-1)&&(j===n-1)) {
var tmp_acc_nbz_f = zero_trailer(grid_aux[i][j],acc_mult,nb_z);
return [tmp_acc_nbz_f[0], path];
}
else if (out_bound(i,j,n)) {
return [MAX_SAFE_INTEGER,[]];
}
else if (grid_aux[i][j]<0) {
return [MAX_SAFE_INTEGER,[]];
}
else {
var tmp_acc_nbz = zero_trailer(grid_aux[i][j],acc_mult,nb_z) ;
grid_aux[i][j]=-1;
var res = [st_aux(i+1,j,deepCopy(grid_aux), tmp_acc_nbz[1], tmp_acc_nbz[0], path+"D"),
st_aux(i-1,j,deepCopy(grid_aux), tmp_acc_nbz[1], tmp_acc_nbz[0], path+"U"),
st_aux(i,j+1,deepCopy(grid_aux), tmp_acc_nbz[1], tmp_acc_nbz[0], path+"R"),
st_aux(i,j-1,deepCopy(grid_aux), tmp_acc_nbz[1], tmp_acc_nbz[0], path+"L")];
return res[myMinIndex(res)];
}
}
return st_aux(0,0,grid, 1, 0, "");
}
myGrid = [[1, 25, 100],[2, 1, 25],[100, 5, 1]];
console.log(smallest_trailer(myGrid)); //[0,"RDDR"]
myGrid = [[1, 2, 100],[25, 1, 5],[100, 25, 1]];
console.log(smallest_trailer(myGrid)); //[0,"DRDR"]
myGrid = [[1, 10, 1, 1, 1],[1, 1, 1, 10, 1],[10, 10, 10, 10, 1],[10, 10, 10, 10, 1],[10, 10, 10, 10, 1]];
console.log(smallest_trailer(myGrid)); //[0,"DRRURRDDDD"]
``` |
32,578,487 | Question link: <http://codeforces.com/contest/2/problem/B>
There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that
starts in the upper left cell of the matrix;
each following cell is to the right or down from the current cell;
the way ends in the bottom right cell.
Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros.
Input
The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 10^9).
Output
In the first line print the least number of trailing zeros. In the second line print the correspondent way itself.
I thought of the following: In the end, whatever the answer will be, it should contain minimum powers of 2's and 5's. Therefore, what I did was, for each entry in the input matrix, I calculated the powers of 2's and 5's and stored them in separate matrices.
```
for (i = 0; i < n; i++)
{
for ( j = 0; j < n; j++)
{
cin>>foo;
matrix[i][j] = foo;
int n1 = calctwo(foo); // calculates the number of 2's in factorisation of that number
int n2 = calcfive(foo); // calculates number of 5's
two[i][j] = n1;
five[i][j] = n2;
}
}
```
After that, I did this:
```
for (i = 0; i < n; i++)
{
for ( j = 0; j < n; j++ )
{
dp[i][j] = min(two[i][j],five[i][j]); // Here, dp[i][j] will store minimum number of 2's and 5's.
}
}
```
But the above doesn't really a valid answer, I don't know why? Have I implemented the correct approach? Or, is this the correct way of solving this question?
Edit: Here are my functions of calculating the number of two's and number of five's in a number.
```
int calctwo (int foo)
{
int counter = 0;
while (foo%2 == 0)
{
if (foo%2 == 0)
{
counter++;
foo = foo/2;
}
else
break;
}
return counter;
}
int calcfive (int foo)
{
int counter = 0;
while (foo%5 == 0)
{
if (foo%5 == 0)
{
counter++;
foo = foo/5;
}
else
break;
}
return counter;
}
```
Edit2: I/O Example as given in the link:
Input:
```
3
1 2 3
4 5 6
7 8 9
```
Output:
```
0
DDRR
``` | 2015/09/15 | [
"https://Stackoverflow.com/questions/32578487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4112864/"
] | Since you are interested only in the number of trailing zeroes you need only to consider the powers of `2`, `5` which you could keep in two separate `nxn` arrays. So for the array
```
1 2 3
4 5 6
7 8 9
```
you just keep the arrays
```
the powers of 2 the powers of 5
0 1 0 0 0 0
2 0 1 0 1 0
0 3 0 0 0 0
```
The insight for the problem is the following. Notice that if you find a path which minimizes the sum of the powers of 2 and a path which minimizes the number sum of the powers of 5 then the answer is the one with lower value of those two paths. So you reduce your problem to the two times application of the following classical dp problem: find a path, starting from the top-left corner and ending at the bottom-right, such that the sum of its elements is minimum. Again, following the example, we have:
```
minimal path for the
powers of 2 value
* * - 2
- * *
- - *
minimal path for the
powers of 5 value
* - - 0
* - -
* * *
```
so your answer is
```
* - -
* - -
* * *
```
with value `0`
**Note 1**
It might seem that taking the minimum of the both optimal paths gives only an upper bound so a question that may rise is: is this bound actually achieved? The answer is yes. For convenience, let the number of 2's along the 2's optimal path is `a` and the number of 5's along the 5's optimal path is `b`. Without loss of generality assume that the minimum of the both optimal paths is the one for the power of 2's (that is `a < b`). Let the number of 5's along the minimal path is `c`. Now the question is: are there as much as 5's as there are 2's along this path (i.e. is `c >= a`?). Assume that the answer is no. That means that there are less 5's than 2's along the minimal path (that is `c < a`). Since the optimal value of 5's paths is `b` we have that every 5's path has at least `b` 5's in it. This should also be true for the minimal path. That means that `c > b`. We have that `c < a` so `a > b` but the initial assumption was that `a < b`. Contradiction.
**Note 2**
You might also want consider the case in which there is an element `0` in your matrix. I'd assume that number of trailing zeroes when the product is 1. In this case, if the algorithm has produced a result with a value more than 1 you should output 1 and print a path that goes through the element `0`. | This is my Dynamic Programming solution.
<https://app.codility.com/demo/results/trainingAXFQ5B-SZQ/>
For better understanding we can simplify the task and assume that there are no zeros in the matrix (i.e. matrix contains only positive integers), then the Java solution will be the following:
```
class Solution {
public int solution(int[][] a) {
int minPws[][] = new int[a.length][a[0].length];
int minPws2 = getMinPws(a, minPws, 2);
int minPws5 = getMinPws(a, minPws, 5);
return min(minPws2, minPws5);
}
private int getMinPws(int[][] a, int[][] minPws, int p) {
minPws[0][0] = pws(a[0][0], p);
//Fullfill the first row
for (int j = 1; j < a[0].length; j++) {
minPws[0][j] = minPws[0][j-1] + pws(a[0][j], p);
}
//Fullfill the first column
for (int i = 1; i < a.length; i++) {
minPws[i][0] = minPws[i-1][0] + pws(a[i][0], p);
}
//Fullfill the rest of matrix
for (int i = 1; i < a.length; i++) {
for (int j = 1; j < a[0].length; j++) {
minPws[i][j] = min(minPws[i-1][j], minPws[i][j-1]) + pws(a[i][j], p);
}
}
return minPws[a.length-1][a[0].length-1];
}
private int pws(int n, int p) {
//Only when n > 0
int pws = 0;
while (n % p == 0) {
pws++;
n /= p;
}
return pws;
}
private int min(int a, int b) {
return (a < b) ? a : b;
}
}
``` |
47,857,014 | Let's say that my function returns a map and some of the value may be randomly generated. I'd like to be able to at least test again output type, or in another words - to check from the doctest level weather returned value is a map. Eventually does it contains specific keys. Is it even possible? The function call may look following:
```
iex> MyApp.function(params, opts)
%{_}
``` | 2017/12/17 | [
"https://Stackoverflow.com/questions/47857014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5753084/"
] | The output can't be a pattern, but you can either use `is_map` or the `match?` macro with the pattern `%{}`, both of which will return `true` if the value is a map.
```
iex> is_map MyApp.function(params, opts)
true
iex> match? %{}, MyApp.function(params, opts)
true
``` | While answer by @Dogbert is perfectly correct, it could not be used in all cases. When one needs to check a value that is unpredictable in advance (say, randomly generated,) there is still an ability to do that with `ExUnit`.
Each run of test suite prints out the *Random seed* value as the very last line of test run:
```
Randomized with seed 486290
```
It might be recorded and passed back to [`ExUnit.configure/1`](https://hexdocs.pm/ex_unit/ExUnit.html#configure/1-options). In such a case, random value returned from the function will be the same (it will not change between different runs.)
This trick won’t work for data, received from third-party services, of course. |
40,505,643 | I want to improve the way I do git commits and I've been reading around the web. I followed the site here <http://chris.beams.io/posts/git-commit/> and this lead me to <https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration> where I can set my default editor, but I still don't understand how I edit the subject line separately from the body of the commit.
I'm used to doing:
```
git commit -am "message here"
```
but as I understand it for longer commits, I should use an editor like vim (on my mac) | 2016/11/09 | [
"https://Stackoverflow.com/questions/40505643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/296775/"
] | The easiest way to do it is to run `git commit` without `-m` and the message.
(`git commit -a` is a shortcut for `git add -u; git commit`, with some other minor technical differences)
It will start an editor where you can enter the commit message on multiple lines. Then you save the file and when the editor exits, `git commit` continues and uses the message from the file.
If you prefer to do everything from a single command (or you write a script that needs to call `git commit` and this interactive way of committing is not an option) then you can provide the commit subject and the commit message body by [using the `-m` argument two times](https://git-scm.com/docs/git-commit):
```
git commit -m "this is the subject" -m "this is the body"
```
Using `-m` multiple times in the command line concatenates the messages as separate paragraphs (separated by an empty line). This works perfectly to provide the subject as the argument of the first `-m` and the message body as the argument of the second `-m`.
There is no easy way to embed newlines in the commit message body. Using three or more times the `-m` option will produce a commit message that contains empty lines and this is probably not what you want.
If you are on `Linux` or `macOS` and you shell of choice is `bash` then there is an ugly but working way to write a message body that contains new lines. Embed each line in quotes (`"`) to allow them contain spaces and join the lines with `$'\n'` which is the `bash` way of writing special characters in the command line (or in a script).
The command looks like this:
```
git commit -m "the subject" -m "the first line"$'\n'"the second line"$'\n'"the third line"
``` | Run: `git commit -a` and you should get a VI editor interface that lets you enter Subject line and message. After finishing entering text press ESC then :wq |
1,898,192 | I have the following differential equation that I need to solve:
$x^3 y^{(3)} + 3 x^2 y'' + x y' = x^3 ln(x)$
I have managed to find the homogeneous solution which is:
$y\_h = c\_1 + c\_2 ln\ |x| + \frac{1}{2}c\_3ln^2\ |x| $
But I don't know how to calculate the particular solution.
I tried to substitute $x = e^t$ but that gives me some garbage answer. | 2016/08/20 | [
"https://math.stackexchange.com/questions/1898192",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/362602/"
] | Whenever you want to solve an equation, you need to be precise about the field in which you are looking for the roots. In general, unless you are in $\mathbb{C}$ where any polynomial has as many roots as its degree, an equation may have no root (example $x^2-2$ over $\Bbb{Q}$) one root (example $x^3-1$ over $\Bbb{R}$)...
In your case when looking to complex roots of the form $x=\rho\cdot e^{i\theta}$ one has $x^3=1=\rho^3\cdot e^{3i\theta}$ and this means besides $\rho=1$
$$3i\theta=2k\pi\,\,\,(k=0,1,2)$$
And this gives three distinct solutions $1,e^{2i\pi/3},e^{4i\pi/3}$ | Because of $e^{i2\pi}=1$ and therefore also $e^{i4\pi}=1$ the roots are solving the equation. Think about $(-1)\cdot(-1)=1\cdot 1$, that's the same type of problem. |
7,306,653 | I would like to change some styling (for example body background color) when specific tab is selected (clicked) in jquery ui tabs.
Sth like:
```
if (tab nr 2 is selected) { $(body).css('background', 'red') }
if (tab nr 3 is selected) { $(body).css('background', 'blue') }
```
How can I check which tab is selected? | 2011/09/05 | [
"https://Stackoverflow.com/questions/7306653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/810506/"
] | ```
$('.ui-tabs-nav').bind('tabsselect', function(event, ui) {
var index=ui.index;
if(index===2){
$(body).css('background', 'red')
}
else if(index===3){
$(body).css('background', 'blue')
}
});
```
[Tab select documentation](http://jqueryui.com/demos/tabs/#event-select)
[Tabs Events documenation](http://docs.jquery.com/UI/Tabs#Events) | [Looking at the documentation](http://jqueryui.com/demos/tabs/#event-enable), you can use the event "enable" to keep track of this.
You could also do as such:
```
var $tabs = $('#example').tabs();
var selected = $tabs.tabs('option', 'selected');
```
*(always from the [documentation](http://jqueryui.com/demos/tabs/#...retrieve_the_index_of_the_currently_selected_tab))*
Generally speaking, read the documentation, you'll find your answer there. |
4,984,284 | Recently, I have been writing many classes which have, apart from generic variant, some primitive variants, for example `Foo<T>`, `IntFoo`, `DoubleFoo` etc. First, I used to put every variant in separate files but I soon found out that the package content has become unreadable due to large number of classes with similar names. On the other hand, putting those in a separate package often results in a loss of cohesion and extra dependencies between packages.
In the meanwhile, I have come to the idea to have the following structure:
```
public class Foo {
public static class TypeFoo<T> { ... }
public static class IntFoo { ... }
public static class DoubleFoo { ... }
...
}
```
or
```
public class Foo {
public static class Type<T> { ... }
public static class Int { ... }
public static class Double { ... }
}
```
I am interested in two things:
1. Does any of these two approaches result in greater overhead when using only one inner class (e.g. int-variant of the class), compared to one-class-per-file approach? Does this overhead, if any, applies when there are inner interfaces instead?
2. Which of these two approaches is better, if any, or if none is good, what are the alternatives? | 2011/02/13 | [
"https://Stackoverflow.com/questions/4984284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/395744/"
] | inner classes will be more of a pain in the long run, in my opinion. if you look at the way Microsoft named their [animation classes](http://msdn.microsoft.com/en-us/library/ms608874.aspx), they had the same dilemma that you did. They chose to have tons of different classes, but as a consumer of these I have found that I prefer it to be this way.
to answer your first question, there should be no overhead. When java compiles inner classes it separates them into separate `*.class` files anyway, so in the end the result is the same. During compilation the parser will have to sift through a lot of `Foo.*` references but the extra time would be negligible. | Might be completely irrelevant to what you're doing, but you could consider replacing all these classes with a Builder (or otherwise known as [Fluent Interface](http://en.wikipedia.org/wiki/Fluent_interface)) pattern. If these classes implement a generic interface, you shouldn't need to expose them anywhere and can still keep them inside one builder class.
A good example of this would be [MapMaker](http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/MapMaker.html) which probably has zillion different inner classes but the only thing you care about is the `Map` or `ConcurrentMap` instance you get out of it. |
29,647,201 | I'm a noob but I was able to build this: <https://www.gloeckle.de/landing/0custom/nouislider/test.html>
But when I try to integrate that into my Joomla site and click the slider the height of the slider is set to 0px. Just try for yourself. I gave every id and class a prefix ("lp\_") but still no luck.
Anyone knows what the problem here is? --> <https://www.gloeckle.de/landing/skl/gewinnchance-bestimmen>
Thanks in advance for any help!
getimo | 2015/04/15 | [
"https://Stackoverflow.com/questions/29647201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2728566/"
] | You should try this
>
> In CakePHP database, table name should be a plural. Model name should be a singular nount with CamelCase. Controller should be a plural with CamelCase add suffix *Controller* must be added. View folder name always is the same as Controller plural name (without suffix) and `.ctp` file name should be a verb.
>
>
>
**AppController.php**
```
<?php
class AppController extends Controller {
public $components = array(
'RequestHandler','Session',
'Auth' => array(
'Autoredirect'=>false,
'loginRedirect' => array('controller' => 'books', 'action' => 'view'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'home'),
'authError' => 'Did you really think you are allowed to see that?',
)
);
}
?>
```
**UsersController.php**
```
<?php
class UsersController extends AppController
{
var $helpers = array('Html', 'Form','Js','Session');
public $components = array(
'RequestHandler',
'Session'
);
public function login(){
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->Session->setFlash('You are successfully login','default',array('class'=>'alert alert-success'));
return $this->redirect($this->Auth->redirect());
}
return $this->Session->setFlash('Invalid username and password,please try again','default',array('class'=>'alert alert-danger'));
}
}
}
?>
```
**login.ctp**
```
<?php echo $this->Session->flash(); ?>
<?php echo $this->Form->create('User'); ?>
<div class="form-group">
<label>Email</label>
<?php echo $this->Form->input('User.username');?>
</div>
<div class="form-group">
<label>Password</label>
<?php echo $this->Form->input('User.password');?>
</div>
<div class="form-group">
<?php echo $this->Form->button('Login',array('type'=>'submit','class'=>'btn btn-primary btn-block')); ?>
</div>
<?php echo $this->Form->end(); ?>
```
**AppModel.php**
```
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class AppModel extends Model {
public $components = array(
'Auth' => array(
'authenticate' => array(
'Form' => array(
'passwordHasher' => array(
'className' => 'Simple',
'hashType' => 'sha1'
)
)
)
)
);
public function beforeSave($options = array()) {
if (!empty($this->data[$this->alias]['password'])) {
$passwordHasher = new SimplePasswordHasher(array('hashType' => 'sha1'));
$this->data[$this->alias]['password'] = $passwordHasher->hash(
$this->data[$this->alias]['password']
);
}
return true;
}
}
?>
```
**User.php (User Model)**
```
<?php
class User extends AppModel
{
public $validate = array(
'username' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Letters and numbers only'
),
),
'password' => array(
'rule' => array('minLength', '8'),
'message' => 'Minimum 8 characters long'
),
);
}
?>
``` | Accidentally i have limited the password field in the database so that password stored partially in the DB that is the reason for this issue. |
36,784,763 | I'm using the `erf` function in Swift, like this:
```
import Foundation
erf(2)
```
Is there an inverse error function as well? | 2016/04/22 | [
"https://Stackoverflow.com/questions/36784763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1318734/"
] | We do not have such function in standard library. But here is an implementation of this function-
<https://github.com/antelopeusersgroup/antelope_contrib/blob/master/lib/location/libgenloc/erfinv.c>
HTH. | The solution that OP had posted on GitHub:
```
func erfinv(y: Double) -> Double {
let center = 0.7
let a = [ 0.886226899, -1.645349621, 0.914624893, -0.140543331]
let b = [-2.118377725, 1.442710462, -0.329097515, 0.012229801]
let c = [-1.970840454, -1.624906493, 3.429567803, 1.641345311]
let d = [ 3.543889200, 1.637067800]
if abs(y) <= center {
let z = pow(y,2)
let num = (((a[3]*z + a[2])*z + a[1])*z) + a[0]
let den = ((((b[3]*z + b[2])*z + b[1])*z + b[0])*z + 1.0)
var x = y*num/den
x = x - (erf(x) - y)/(2.0/sqrt(.pi)*exp(-x*x))
x = x - (erf(x) - y)/(2.0/sqrt(.pi)*exp(-x*x))
return x
}
else if abs(y) > center && abs(y) < 1.0 {
let z = pow(-log((1.0-abs(y))/2),0.5)
let num = ((c[3]*z + c[2])*z + c[1])*z + c[0]
let den = (d[1]*z + d[0])*z + 1
// should use the sign function instead of pow(pow(y,2),0.5)
var x = y/pow(pow(y,2),0.5)*num/den
x = x - (erf(x) - y)/(2.0/sqrt(.pi)*exp(-x*x))
x = x - (erf(x) - y)/(2.0/sqrt(.pi)*exp(-x*x))
return x
} else if abs(y) == 1 {
return y * Double(Int.max)
} else {
return .nan
}
}
``` |
36,784,763 | I'm using the `erf` function in Swift, like this:
```
import Foundation
erf(2)
```
Is there an inverse error function as well? | 2016/04/22 | [
"https://Stackoverflow.com/questions/36784763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1318734/"
] | We do not have such function in standard library. But here is an implementation of this function-
<https://github.com/antelopeusersgroup/antelope_contrib/blob/master/lib/location/libgenloc/erfinv.c>
HTH. | Swift does not appear to have it. This has an algorithm that could be translated into Swift:
[Need code for Inverse Error Function](https://stackoverflow.com/questions/5971830/need-code-for-inverse-error-function)
Also, Ch 6.2.2 or Numerical Solutions, 3e has an algorithm:
<https://e-maxx.ru/bookz/files/numerical_recipes.pdf> |
36,784,763 | I'm using the `erf` function in Swift, like this:
```
import Foundation
erf(2)
```
Is there an inverse error function as well? | 2016/04/22 | [
"https://Stackoverflow.com/questions/36784763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1318734/"
] | Swift does not appear to have it. This has an algorithm that could be translated into Swift:
[Need code for Inverse Error Function](https://stackoverflow.com/questions/5971830/need-code-for-inverse-error-function)
Also, Ch 6.2.2 or Numerical Solutions, 3e has an algorithm:
<https://e-maxx.ru/bookz/files/numerical_recipes.pdf> | The solution that OP had posted on GitHub:
```
func erfinv(y: Double) -> Double {
let center = 0.7
let a = [ 0.886226899, -1.645349621, 0.914624893, -0.140543331]
let b = [-2.118377725, 1.442710462, -0.329097515, 0.012229801]
let c = [-1.970840454, -1.624906493, 3.429567803, 1.641345311]
let d = [ 3.543889200, 1.637067800]
if abs(y) <= center {
let z = pow(y,2)
let num = (((a[3]*z + a[2])*z + a[1])*z) + a[0]
let den = ((((b[3]*z + b[2])*z + b[1])*z + b[0])*z + 1.0)
var x = y*num/den
x = x - (erf(x) - y)/(2.0/sqrt(.pi)*exp(-x*x))
x = x - (erf(x) - y)/(2.0/sqrt(.pi)*exp(-x*x))
return x
}
else if abs(y) > center && abs(y) < 1.0 {
let z = pow(-log((1.0-abs(y))/2),0.5)
let num = ((c[3]*z + c[2])*z + c[1])*z + c[0]
let den = (d[1]*z + d[0])*z + 1
// should use the sign function instead of pow(pow(y,2),0.5)
var x = y/pow(pow(y,2),0.5)*num/den
x = x - (erf(x) - y)/(2.0/sqrt(.pi)*exp(-x*x))
x = x - (erf(x) - y)/(2.0/sqrt(.pi)*exp(-x*x))
return x
} else if abs(y) == 1 {
return y * Double(Int.max)
} else {
return .nan
}
}
``` |
51,632,752 | I have an intent with an Assistant List containing two options, Apples and Cheese. I want to provide a different response to each option chosen.
My first attempt was to use follow-up intents for each item, but when I do this I get a “not understood” message when tapping/choosing the item. On reading more, I understand this is because the `actions_intent_OPTION` event has been fired and there is no intent to handle it.
My second attempt was to add the `actions_intent_OPTION` event handler to each of my follow-up intents. When I did this, only the Cheese intent was invoked each time. I understand this is because `actions_intent_OPTION` can only be handled by a single intent.
So my conclusion is that the only way I can provide different responses for different items in an Assistant List is to handle this event with a webhook, and that it’s not possible using Dialogflow alone. Can anyone confirm or point me in the right direction if not? | 2018/08/01 | [
"https://Stackoverflow.com/questions/51632752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/248918/"
] | The answer is, as suspected, that you can’t use an Assistant List purely in Dialogflow, you have to add a handler function in the fulfilment, that fires on the event `actions_intent_OPTION`. For example:
`const option = conv.arguments.get('OPTION');
if (!option) {
conv.ask('No choice made');
} else if (option === 'optionA') {
// Do something
} else if (option === 'optionB') {
// Do something else
}` | Follow this ideal approach:
* remove follow-up intents
* add a new intent with event set as `actions_intent_OPTION`
* enable webhook for the new intent
* in the webhook extract the selected option
* based on the selected option, pass the required response
If you want to use only Dialogflow, then it won't work! This is because, when you select an option, the output context and the generated event both will be the same as the 2 intents - cheese and apple. There will be no way for the AI engine to decide which Intent should be triggered. Whichever intent is first, it will be called every time.
I tried to recreate what you did all be Dialogflow and even put cheese and apple as training phrases for the 2 intents just to provide some differentiation to the AI engine, but it still selected only one intent. |
46,428,207 | I am still a very bad programmer, currently starting my project. I have mostly Java experience, but need to switch to Python3 for my project now.
I want to use the excel data files I have and build a dictionary for each column, meaning the list of values it takes.
I have done similar stuff with CSV files using the pandas library in Python3.
As far as I can go I imported the file with pandas, how do I create it into a dictionary? Should I take care of categorical data first or can that be done in the dictionary?
```
import pandas as pd
d = pd.read_excel("file.xls")
``` | 2017/09/26 | [
"https://Stackoverflow.com/questions/46428207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6065810/"
] | I had the same issue and found that while i was getting reasonable times initially (opening and closing was taking maybe 2-3 seconds), this suddenly increased to over a minute. I had introduced logging, so thought that may have been the cause, but after commenting this out, there was still a long delay
I copied the data from the Excel spreadsheet and just saved to a new excel spreadsheet which fixed it for me. Seems like it must have got corrupted somehow.
Note - saving the same filename as another filename didn't work, neither did saving the same filename on a local drive. | I do not know what you need to do with the Excel file, but I would try opening the .xmls file as Pandas DataFrame:
```
import pandas as pd
df = pd.ExcelFile('file path')
``` |
29,499,144 | I am new to Django and DjangoCMS. I recently installed DjangoCMS and am looking to write my own app for it by following the tutorials [Tutorial 1](https://docs.djangoproject.com/en/1.7/intro/tutorial01/) and [Introduction to Plugins](http://django-cms.readthedocs.org/en/latest/introduction/plugins.html).
After some researching and testing, I have discovered that when I try to run either of the commands:
```
python manage.py migrate
or
python manage.py makemigrations polls
```
I end up running into the following error:
```
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute
django.setup()
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/djangocms_text_ckeditor/models.py", line 14, in <module>
from cms.models import CMSPlugin
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/cms/models/__init__.py", line 3, in <module>
from .pagemodel import * # nopyflakes
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/cms/models/pagemodel.py", line 20, in <module>
from cms.models.placeholdermodel import Placeholder
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/cms/models/placeholdermodel.py", line 16, in <module>
from cms.utils.placeholder import PlaceholderNoAction, get_placeholder_conf
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/cms/utils/placeholder.py", line 8, in <module>
from sekizai.helpers import get_varname
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/sekizai/helpers.py", line 3, in <module>
from django.template import VariableNode, Variable
ImportError: cannot import name VariableNode
```
I think it is specific to the installed apps I have set in my settings.py file because as I have been working on this error, I have discovered that most of the apps that come set in INSTALLED\_APPS for DjangoCMS actually don't have to be installed for me to run the website locally.
```
INSTALLED_APPS = (
'djangocms_admin_style',
'djangocms_text_ckeditor',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.sites',
'django.contrib.sitemaps',
'django.contrib.staticfiles',
'django.contrib.messages',
'djangocms_style',
'djangocms_column',
'djangocms_file',
'djangocms_flash',
'djangocms_googlemap',
'djangocms_inherit',
'djangocms_link',
'djangocms_picture',
'djangocms_teaser',
'djangocms_video',
'cms',
'menus',
'sekizai',
'reversion',
'mptt',
'south',
'mywebsite',
'polls'
)
```
Looking at the stack I think this particular error is related to the sekizai app but when I go ahead and pip install django-sekizai I still get the same error when I try to migrate. | 2015/04/07 | [
"https://Stackoverflow.com/questions/29499144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3150413/"
] | Change Script1.ps1 to launch python as a job:
```
./activate anaconda_env
cd C:\webserver
Invoke-Command -ScriptBlock {.\python.exe api_server.py} -AsJob -ComputerName .
```
I don't have the specific script you're using, so I tested this with turtle.py which ships with 3.43 and it seems to work. | To not have invoke-expression close your script you can pipe the output to Out-Null. Your code above would look like:
```
Invoke-Expression C:\script1.ps1 | Out-Null
Invoke-Expression C:\script2.ps1 | Out-Null
``` |
29,499,144 | I am new to Django and DjangoCMS. I recently installed DjangoCMS and am looking to write my own app for it by following the tutorials [Tutorial 1](https://docs.djangoproject.com/en/1.7/intro/tutorial01/) and [Introduction to Plugins](http://django-cms.readthedocs.org/en/latest/introduction/plugins.html).
After some researching and testing, I have discovered that when I try to run either of the commands:
```
python manage.py migrate
or
python manage.py makemigrations polls
```
I end up running into the following error:
```
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute
django.setup()
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/djangocms_text_ckeditor/models.py", line 14, in <module>
from cms.models import CMSPlugin
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/cms/models/__init__.py", line 3, in <module>
from .pagemodel import * # nopyflakes
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/cms/models/pagemodel.py", line 20, in <module>
from cms.models.placeholdermodel import Placeholder
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/cms/models/placeholdermodel.py", line 16, in <module>
from cms.utils.placeholder import PlaceholderNoAction, get_placeholder_conf
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/cms/utils/placeholder.py", line 8, in <module>
from sekizai.helpers import get_varname
File "/home/username/folder/DjangoCMS/env/local/lib/python2.7/site-packages/sekizai/helpers.py", line 3, in <module>
from django.template import VariableNode, Variable
ImportError: cannot import name VariableNode
```
I think it is specific to the installed apps I have set in my settings.py file because as I have been working on this error, I have discovered that most of the apps that come set in INSTALLED\_APPS for DjangoCMS actually don't have to be installed for me to run the website locally.
```
INSTALLED_APPS = (
'djangocms_admin_style',
'djangocms_text_ckeditor',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.sites',
'django.contrib.sitemaps',
'django.contrib.staticfiles',
'django.contrib.messages',
'djangocms_style',
'djangocms_column',
'djangocms_file',
'djangocms_flash',
'djangocms_googlemap',
'djangocms_inherit',
'djangocms_link',
'djangocms_picture',
'djangocms_teaser',
'djangocms_video',
'cms',
'menus',
'sekizai',
'reversion',
'mptt',
'south',
'mywebsite',
'polls'
)
```
Looking at the stack I think this particular error is related to the sekizai app but when I go ahead and pip install django-sekizai I still get the same error when I try to migrate. | 2015/04/07 | [
"https://Stackoverflow.com/questions/29499144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3150413/"
] | You don't need to use Invoke-Expression to run a Powershell script from another script. Just run it as if you're on the command line
```
c:\script1.ps1
c:\script2.ps1
```
Now if script1.ps1 starts a process that doesn't exit, it will halt execution for the next statements in the script, and thus also prevent the second script from running.
In most cases this sequential execution is exactly what you want.
In your case you can start the scripts asynchronously by using Start-Process.
So your main script becomes something like:
```
start-process c:\script1.ps1
start-process c:\script2.ps1
```
[Start-Process](https://technet.microsoft.com/library/hh849848.aspx) basically starts a new command shell to run the statement in. Check out the docs for more info. There's a bunch of parameters you can use to tweak how this happens. | To not have invoke-expression close your script you can pipe the output to Out-Null. Your code above would look like:
```
Invoke-Expression C:\script1.ps1 | Out-Null
Invoke-Expression C:\script2.ps1 | Out-Null
``` |
35,979,301 | Does the Apache HttpClient handle GET requests differently compared to java.net.HttpURLConnection?
I tried making a GET request to a URL which returns a redirect using both methods. While the response code from HttpURLConnection returns a 302 as expected, making the same call using HttpClient results in a 200.
Below is my code:
```
// Using Apache HttpClient
HttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
HttpGet request = new HttpGet(authUrl);
HttpResponse response = client.execute(request);
int responseCode = response.getStatusLine().getStatusCode(); //Returns 200
// Using java.net.HttpURLConnection
URL obj = new URL(authUrl);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
int responseCode = conn.getResponseCode(); //Returns 302
```
This is my first time using Apache HttpClient, so my code might be wrong.
Thanks. | 2016/03/14 | [
"https://Stackoverflow.com/questions/35979301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2789812/"
] | [Handling GET requests - Apache HttpClient vs java.net.HttpURLConnection](https://stackoverflow.com/questions/35979301/handling-get-requests-apache-httpclient-vs-java-net-httpurlconnection)
If you need to walk through a chain of redirects, you should set redirects disabled for HttpPost/HttpGet (HttpRequestBase), for example:
```
public void disableRedirect(HttpRequestBase request) {
request.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build());
}
```
After that you will get expected 302 response code with `response.getStatusLine().getStatusCode()` and may read headers as @Ascalonian said | Try turning off automatic redirect handling. Most likely HttpClient redirects to a location specified in 302 response, while HUC for some reason does not |
69,041,545 | I have this code, where the conditions are very similar and the methods being called are the same. I was wondering if there's a way to make this look better, or at least make it smaller and thus easier to read.
```
public void open(int i, int j){
if (i > n - 1 || i < 0 || j > n - 1 || j < 0) {
throw new IndexOutOfBoundsException
("Index out of bounds.");
}
grid[i][j] = true;
if (i - 1 >= 0 && grid[i - 1][j]) {
unionFind.union(location(i - 1, j), location(i, j));
unionFind2.union(location(i - 1, j), location(i, j));
}
if (i + 1 < n && grid[i + 1][j]) {
unionFind.union(location(i + 1, j), location(i, j));
unionFind2.union(location(i + 1, j), location(i, j));
}
if (j - 1 >= 0 && grid[i][j - 1]) {
unionFind.union(location(i, j - 1), location(i, j));
unionFind2.union(location(i, j - 1), location(i, j));
}
if (j + 1 < n && grid[i][j + 1]) {
unionFind.union(location(i, j + 1), location(i, j));
unionFind2.union(location(i, j + 1), location(i, j));
}
numberOpen++;
}
``` | 2021/09/03 | [
"https://Stackoverflow.com/questions/69041545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16769086/"
] | Well, you could easily write a method which *conditionally* calls the `union` method, then call that unconditionally from `open`:
```java
public void open(int i, int j) {
if (i > n - 1 || i < 0 || j > n - 1 || j < 0) {
throw new IndexOutOfBoundsException("Index out of bounds.");
}
grid[i][j] = true;
// I'm assuming the result of this doesn't change between calls?
// (We don't know the type, either.)
Location thisLocation = location(i, j);
maybeUnion(i - 1, j, thisLocation);
maybeUnion(i + 1, j, thisLocation);
maybeUnion(i, j + 1, thisLocation);
maybeUnion(i, j - 1, thisLocation);
numberOpen++;
}
private void maybeUnion(int x, int y, Location unionWith) {
if (x < 0 || y < 0 || x >= n || y >= n || !grid[x][y]) {
return;
}
unionFind.union(location(x, y), unionWith);
unionFind2.union(location(x, y), unionWith);
}
``` | ```
private int[] dr = new int[] {-1, 1, 0, 0};
private int[] dc = new int[] { 0, 0, -1, 1};
public void open(int i, int j) {
if (i > n - 1 || i < 0 || j > n - 1 || j < 0) {
throw new IndexOutOfBoundsException("Index out of bounds.");
}
grid[i][j] = true;
Location thisLocation = new location(i, j);
for (int k = 0; k < 4; i++) {
int newI = dr[k] + i;
int newJ = dc[k] + j;
performUnion(new Location(newI, newJ), thisLocation);
}
numberOpen++;
}
private void performUnion(Location loc, Location unionWith) {
if (loc.x < 0 || loc.y < 0 || loc.x >= n || loc.y >= n && !grid[loc.x][loc.y]) {
return;
}
unionFind.union(loc, unionWith);
unionFind2.union(loc, unionWith);
}
``` |
69,041,545 | I have this code, where the conditions are very similar and the methods being called are the same. I was wondering if there's a way to make this look better, or at least make it smaller and thus easier to read.
```
public void open(int i, int j){
if (i > n - 1 || i < 0 || j > n - 1 || j < 0) {
throw new IndexOutOfBoundsException
("Index out of bounds.");
}
grid[i][j] = true;
if (i - 1 >= 0 && grid[i - 1][j]) {
unionFind.union(location(i - 1, j), location(i, j));
unionFind2.union(location(i - 1, j), location(i, j));
}
if (i + 1 < n && grid[i + 1][j]) {
unionFind.union(location(i + 1, j), location(i, j));
unionFind2.union(location(i + 1, j), location(i, j));
}
if (j - 1 >= 0 && grid[i][j - 1]) {
unionFind.union(location(i, j - 1), location(i, j));
unionFind2.union(location(i, j - 1), location(i, j));
}
if (j + 1 < n && grid[i][j + 1]) {
unionFind.union(location(i, j + 1), location(i, j));
unionFind2.union(location(i, j + 1), location(i, j));
}
numberOpen++;
}
``` | 2021/09/03 | [
"https://Stackoverflow.com/questions/69041545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16769086/"
] | Well, you could easily write a method which *conditionally* calls the `union` method, then call that unconditionally from `open`:
```java
public void open(int i, int j) {
if (i > n - 1 || i < 0 || j > n - 1 || j < 0) {
throw new IndexOutOfBoundsException("Index out of bounds.");
}
grid[i][j] = true;
// I'm assuming the result of this doesn't change between calls?
// (We don't know the type, either.)
Location thisLocation = location(i, j);
maybeUnion(i - 1, j, thisLocation);
maybeUnion(i + 1, j, thisLocation);
maybeUnion(i, j + 1, thisLocation);
maybeUnion(i, j - 1, thisLocation);
numberOpen++;
}
private void maybeUnion(int x, int y, Location unionWith) {
if (x < 0 || y < 0 || x >= n || y >= n || !grid[x][y]) {
return;
}
unionFind.union(location(x, y), unionWith);
unionFind2.union(location(x, y), unionWith);
}
``` | Try this.
```
static final int[][] DIRECTIONS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
boolean inRange(int i, int j) {
return i >= 0 && i < n && j >= 0 && j < n;
}
public void open(int i, int j) {
if (!inRange(i, j))
throw new IndexOutOfBoundsException("Index out of bounds.");
grid[i][j] = true;
for (int[] dir : DIRECTIONS) {
int ii = i + dir[0], jj = j + dir[1];
if (inRange(ii, jj) && grid[ii][jj]) {
unionFind.union(location(ii, jj), location(i, j));
unionFind2.union(location(ii, jj), location(i, j));
}
}
numberOpen++;
}
``` |
69,041,545 | I have this code, where the conditions are very similar and the methods being called are the same. I was wondering if there's a way to make this look better, or at least make it smaller and thus easier to read.
```
public void open(int i, int j){
if (i > n - 1 || i < 0 || j > n - 1 || j < 0) {
throw new IndexOutOfBoundsException
("Index out of bounds.");
}
grid[i][j] = true;
if (i - 1 >= 0 && grid[i - 1][j]) {
unionFind.union(location(i - 1, j), location(i, j));
unionFind2.union(location(i - 1, j), location(i, j));
}
if (i + 1 < n && grid[i + 1][j]) {
unionFind.union(location(i + 1, j), location(i, j));
unionFind2.union(location(i + 1, j), location(i, j));
}
if (j - 1 >= 0 && grid[i][j - 1]) {
unionFind.union(location(i, j - 1), location(i, j));
unionFind2.union(location(i, j - 1), location(i, j));
}
if (j + 1 < n && grid[i][j + 1]) {
unionFind.union(location(i, j + 1), location(i, j));
unionFind2.union(location(i, j + 1), location(i, j));
}
numberOpen++;
}
``` | 2021/09/03 | [
"https://Stackoverflow.com/questions/69041545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16769086/"
] | Try this.
```
static final int[][] DIRECTIONS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
boolean inRange(int i, int j) {
return i >= 0 && i < n && j >= 0 && j < n;
}
public void open(int i, int j) {
if (!inRange(i, j))
throw new IndexOutOfBoundsException("Index out of bounds.");
grid[i][j] = true;
for (int[] dir : DIRECTIONS) {
int ii = i + dir[0], jj = j + dir[1];
if (inRange(ii, jj) && grid[ii][jj]) {
unionFind.union(location(ii, jj), location(i, j));
unionFind2.union(location(ii, jj), location(i, j));
}
}
numberOpen++;
}
``` | ```
private int[] dr = new int[] {-1, 1, 0, 0};
private int[] dc = new int[] { 0, 0, -1, 1};
public void open(int i, int j) {
if (i > n - 1 || i < 0 || j > n - 1 || j < 0) {
throw new IndexOutOfBoundsException("Index out of bounds.");
}
grid[i][j] = true;
Location thisLocation = new location(i, j);
for (int k = 0; k < 4; i++) {
int newI = dr[k] + i;
int newJ = dc[k] + j;
performUnion(new Location(newI, newJ), thisLocation);
}
numberOpen++;
}
private void performUnion(Location loc, Location unionWith) {
if (loc.x < 0 || loc.y < 0 || loc.x >= n || loc.y >= n && !grid[loc.x][loc.y]) {
return;
}
unionFind.union(loc, unionWith);
unionFind2.union(loc, unionWith);
}
``` |
45,405 | Recently I came across two sites that help programmers sell source code - binpress and codecanyon. Anyone have experience/success with sites like these?
Would you use them again? What was good about them? What was bad about them? | 2011/02/08 | [
"https://softwareengineering.stackexchange.com/questions/45405",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/16371/"
] | I think the problem with purchasing random snippets of code is that you really have NO idea what you're getting; you could be buying a complete piece of crap.
Programming is not like design or photography, and I do not see an iStockPhoto-type solution working in our industry. With iStockPhoto, You get what you preview, and that is that. With programming however, you cannot preview the source, nor do you have much of a guarantee on the functionality of the code.
I've seen way to many horrible pieces of code floating around the net for me to think I would use such a system. | The prices that the software is being sold at only makes sense (for the seller) if you live in a third world country OR if you think your component will sell thousands of copies. Just look at the prices...the ones I've seen are between $10 and $100. If your component only sells a handful of copies you're losing money, guaranteed. |
5,732,989 | I read a few other posts on SO that came close to what I was looking for, but I'm basically looking for a service to provide accurate GeoLocation services that will get you close to a location.
We used one IP based service that plotted us 4 hours away. That's no good. What is the most accurate service outside of the HTML5 GeoLocation API? | 2011/04/20 | [
"https://Stackoverflow.com/questions/5732989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/605698/"
] | in Firebird 2.5 you have built-in function to make [this](http://www.firebirdsql.org/rlsnotesh/rlsnotes25.html#rnfb25-dml-uuid) | Char(16) looks like byte representation of the GUID. Try converting each character of the string to a byte array and than creating GUID out of it
```
new Guid("0000000000000000".Select(c=> (byte)c).ToArray())
```
For reverse conversion use guid.ToByteArray() and convert it to string with ASCII encoding.
```
Encoding.ASCII.GetString(Guid.Empty.ToByteArray())
``` |
5,732,989 | I read a few other posts on SO that came close to what I was looking for, but I'm basically looking for a service to provide accurate GeoLocation services that will get you close to a location.
We used one IP based service that plotted us 4 hours away. That's no good. What is the most accurate service outside of the HTML5 GeoLocation API? | 2011/04/20 | [
"https://Stackoverflow.com/questions/5732989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/605698/"
] | Char(16) looks like byte representation of the GUID. Try converting each character of the string to a byte array and than creating GUID out of it
```
new Guid("0000000000000000".Select(c=> (byte)c).ToArray())
```
For reverse conversion use guid.ToByteArray() and convert it to string with ASCII encoding.
```
Encoding.ASCII.GetString(Guid.Empty.ToByteArray())
``` | This question is pretty old but I just had similar problem, while working with Firebird 2.0 (no built-in UUID generator).
So, the main problem with the code presented above was wrong parameter type (binary). It should either be FbDbType.Char or FbDbType.Guid. Below is a working example.
```
Guid newGuid = Guid.NewGuid();
Guid retrieved = Guid.Empty;
using (FbConnection conn = new FbConnection(connectionString)) {
conn.Open();
using (FbCommand cmd = conn.CreateCommand()) {
// first create the table for testing
cmd.CommandText = "recreate table GUID_test (guid char(16) character set octets)";
cmd.ExecuteNonQuery();
}
using (FbCommand cmd = conn.CreateCommand()) {
// inserting GUID into db table
cmd.CommandText = "insert into GUID_test values (@guid)";
// classic way, works good
//cmd.Parameters.Add("@guid", FbDbType.Char, 16).Value = newGuid.ToByteArray();
// another way, maybe better readability, but same result
cmd.Parameters.Add("@guid", FbDbType.Guid).Value = newGuid;
cmd.ExecuteNonQuery();
}
using (FbCommand cmd = conn.CreateCommand()) {
// reading GUID back from db
cmd.CommandText = "select first 1 guid from GUID_test";
retrieved = (Guid)cmd.ExecuteScalar();
}
using (FbCommand cmd = conn.CreateCommand()) {
// drop the table, it has no real application
cmd.CommandText = "drop table GUID_test";
cmd.ExecuteNonQuery();
}
}
MessageBox.Show(newGuid.Equals(retrieved).ToString());
``` |
5,732,989 | I read a few other posts on SO that came close to what I was looking for, but I'm basically looking for a service to provide accurate GeoLocation services that will get you close to a location.
We used one IP based service that plotted us 4 hours away. That's no good. What is the most accurate service outside of the HTML5 GeoLocation API? | 2011/04/20 | [
"https://Stackoverflow.com/questions/5732989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/605698/"
] | Char(16) looks like byte representation of the GUID. Try converting each character of the string to a byte array and than creating GUID out of it
```
new Guid("0000000000000000".Select(c=> (byte)c).ToArray())
```
For reverse conversion use guid.ToByteArray() and convert it to string with ASCII encoding.
```
Encoding.ASCII.GetString(Guid.Empty.ToByteArray())
``` | When inserting guids values, pass them in your query as
```
"INSERT INTO MyTable(GuidCol) VALUES (CHAR_TO_UUID(" + yourGuid.ToString() + "))"
```
when reading, you can correct the badly parsed value from the Firebird .NET Data Provider using the below class:
```
public class FirebirdCorrectingReader : IDataReader {
private readonly IDataReader _decoratedReader;
public FirebirdCorrectingReader(IDataReader decoratedReader) {
_decoratedReader = decoratedReader;
}
#region DataReader Impl
public void Dispose() {
_decoratedReader.Dispose();
}
public string GetName(int i) {
return _decoratedReader.GetName(i);
}
public string GetDataTypeName(int i) {
return _decoratedReader.GetDataTypeName(i);
}
public Type GetFieldType(int i) {
return _decoratedReader.GetFieldType(i);
}
public object GetValue(int i) {
var result = _decoratedReader.GetValue(i);
if (result is Guid) {
result = CorrectGuid((Guid)result);
}
return result;
}
public int GetValues(object[] values) {
return _decoratedReader.GetValues(values);
}
public int GetOrdinal(string name) {
return _decoratedReader.GetOrdinal(name);
}
public bool GetBoolean(int i) {
return _decoratedReader.GetBoolean(i);
}
public byte GetByte(int i) {
return _decoratedReader.GetByte(i);
}
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) {
return _decoratedReader.GetBytes(i, fieldOffset, buffer, bufferoffset, length);
}
public char GetChar(int i) {
return _decoratedReader.GetChar(i);
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length) {
return _decoratedReader.GetChars(i, fieldoffset, buffer, bufferoffset, length);
}
public Guid GetGuid(int i) {
return CorrectGuid(_decoratedReader.GetGuid(i));
}
public short GetInt16(int i) {
return _decoratedReader.GetInt16(i);
}
public int GetInt32(int i) {
return _decoratedReader.GetInt32(i);
}
public long GetInt64(int i) {
return _decoratedReader.GetInt64(i);
}
public float GetFloat(int i) {
return _decoratedReader.GetFloat(i);
}
public double GetDouble(int i) {
return _decoratedReader.GetDouble(i);
}
public string GetString(int i) {
return _decoratedReader.GetString(i);
}
public decimal GetDecimal(int i) {
return _decoratedReader.GetDecimal(i);
}
public DateTime GetDateTime(int i) {
return _decoratedReader.GetDateTime(i);
}
public IDataReader GetData(int i) {
return _decoratedReader.GetData(i);
}
public bool IsDBNull(int i) {
return _decoratedReader.IsDBNull(i);
}
public int FieldCount { get { return _decoratedReader.FieldCount; } }
object IDataRecord.this[int i] {
get { return _decoratedReader[i]; }
}
object IDataRecord.this[string name] {
get {return _decoratedReader[name]; }
}
public void Close() {
_decoratedReader.Close();
}
public DataTable GetSchemaTable() {
return _decoratedReader.GetSchemaTable();
}
public bool NextResult() {
return _decoratedReader.NextResult();
}
public bool Read() {
return _decoratedReader.Read();
}
public int Depth { get { return _decoratedReader.Depth; } }
public bool IsClosed { get { return _decoratedReader.IsClosed; } }
public int RecordsAffected { get { return _decoratedReader.RecordsAffected; } }
#endregion
public static Guid CorrectGuid(Guid badlyParsedGuid) {
var rfc4122bytes = badlyParsedGuid.ToByteArray();
if (BitConverter.IsLittleEndian) {
Array.Reverse(rfc4122bytes, 0, 4);
Array.Reverse(rfc4122bytes, 4, 2);
Array.Reverse(rfc4122bytes, 6, 2);
}
return new Guid(rfc4122bytes);
}
}
```
**Note**: Do not use this class when this bug is fixed. |
5,732,989 | I read a few other posts on SO that came close to what I was looking for, but I'm basically looking for a service to provide accurate GeoLocation services that will get you close to a location.
We used one IP based service that plotted us 4 hours away. That's no good. What is the most accurate service outside of the HTML5 GeoLocation API? | 2011/04/20 | [
"https://Stackoverflow.com/questions/5732989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/605698/"
] | in Firebird 2.5 you have built-in function to make [this](http://www.firebirdsql.org/rlsnotesh/rlsnotes25.html#rnfb25-dml-uuid) | This question is pretty old but I just had similar problem, while working with Firebird 2.0 (no built-in UUID generator).
So, the main problem with the code presented above was wrong parameter type (binary). It should either be FbDbType.Char or FbDbType.Guid. Below is a working example.
```
Guid newGuid = Guid.NewGuid();
Guid retrieved = Guid.Empty;
using (FbConnection conn = new FbConnection(connectionString)) {
conn.Open();
using (FbCommand cmd = conn.CreateCommand()) {
// first create the table for testing
cmd.CommandText = "recreate table GUID_test (guid char(16) character set octets)";
cmd.ExecuteNonQuery();
}
using (FbCommand cmd = conn.CreateCommand()) {
// inserting GUID into db table
cmd.CommandText = "insert into GUID_test values (@guid)";
// classic way, works good
//cmd.Parameters.Add("@guid", FbDbType.Char, 16).Value = newGuid.ToByteArray();
// another way, maybe better readability, but same result
cmd.Parameters.Add("@guid", FbDbType.Guid).Value = newGuid;
cmd.ExecuteNonQuery();
}
using (FbCommand cmd = conn.CreateCommand()) {
// reading GUID back from db
cmd.CommandText = "select first 1 guid from GUID_test";
retrieved = (Guid)cmd.ExecuteScalar();
}
using (FbCommand cmd = conn.CreateCommand()) {
// drop the table, it has no real application
cmd.CommandText = "drop table GUID_test";
cmd.ExecuteNonQuery();
}
}
MessageBox.Show(newGuid.Equals(retrieved).ToString());
``` |
5,732,989 | I read a few other posts on SO that came close to what I was looking for, but I'm basically looking for a service to provide accurate GeoLocation services that will get you close to a location.
We used one IP based service that plotted us 4 hours away. That's no good. What is the most accurate service outside of the HTML5 GeoLocation API? | 2011/04/20 | [
"https://Stackoverflow.com/questions/5732989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/605698/"
] | in Firebird 2.5 you have built-in function to make [this](http://www.firebirdsql.org/rlsnotesh/rlsnotes25.html#rnfb25-dml-uuid) | When inserting guids values, pass them in your query as
```
"INSERT INTO MyTable(GuidCol) VALUES (CHAR_TO_UUID(" + yourGuid.ToString() + "))"
```
when reading, you can correct the badly parsed value from the Firebird .NET Data Provider using the below class:
```
public class FirebirdCorrectingReader : IDataReader {
private readonly IDataReader _decoratedReader;
public FirebirdCorrectingReader(IDataReader decoratedReader) {
_decoratedReader = decoratedReader;
}
#region DataReader Impl
public void Dispose() {
_decoratedReader.Dispose();
}
public string GetName(int i) {
return _decoratedReader.GetName(i);
}
public string GetDataTypeName(int i) {
return _decoratedReader.GetDataTypeName(i);
}
public Type GetFieldType(int i) {
return _decoratedReader.GetFieldType(i);
}
public object GetValue(int i) {
var result = _decoratedReader.GetValue(i);
if (result is Guid) {
result = CorrectGuid((Guid)result);
}
return result;
}
public int GetValues(object[] values) {
return _decoratedReader.GetValues(values);
}
public int GetOrdinal(string name) {
return _decoratedReader.GetOrdinal(name);
}
public bool GetBoolean(int i) {
return _decoratedReader.GetBoolean(i);
}
public byte GetByte(int i) {
return _decoratedReader.GetByte(i);
}
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) {
return _decoratedReader.GetBytes(i, fieldOffset, buffer, bufferoffset, length);
}
public char GetChar(int i) {
return _decoratedReader.GetChar(i);
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length) {
return _decoratedReader.GetChars(i, fieldoffset, buffer, bufferoffset, length);
}
public Guid GetGuid(int i) {
return CorrectGuid(_decoratedReader.GetGuid(i));
}
public short GetInt16(int i) {
return _decoratedReader.GetInt16(i);
}
public int GetInt32(int i) {
return _decoratedReader.GetInt32(i);
}
public long GetInt64(int i) {
return _decoratedReader.GetInt64(i);
}
public float GetFloat(int i) {
return _decoratedReader.GetFloat(i);
}
public double GetDouble(int i) {
return _decoratedReader.GetDouble(i);
}
public string GetString(int i) {
return _decoratedReader.GetString(i);
}
public decimal GetDecimal(int i) {
return _decoratedReader.GetDecimal(i);
}
public DateTime GetDateTime(int i) {
return _decoratedReader.GetDateTime(i);
}
public IDataReader GetData(int i) {
return _decoratedReader.GetData(i);
}
public bool IsDBNull(int i) {
return _decoratedReader.IsDBNull(i);
}
public int FieldCount { get { return _decoratedReader.FieldCount; } }
object IDataRecord.this[int i] {
get { return _decoratedReader[i]; }
}
object IDataRecord.this[string name] {
get {return _decoratedReader[name]; }
}
public void Close() {
_decoratedReader.Close();
}
public DataTable GetSchemaTable() {
return _decoratedReader.GetSchemaTable();
}
public bool NextResult() {
return _decoratedReader.NextResult();
}
public bool Read() {
return _decoratedReader.Read();
}
public int Depth { get { return _decoratedReader.Depth; } }
public bool IsClosed { get { return _decoratedReader.IsClosed; } }
public int RecordsAffected { get { return _decoratedReader.RecordsAffected; } }
#endregion
public static Guid CorrectGuid(Guid badlyParsedGuid) {
var rfc4122bytes = badlyParsedGuid.ToByteArray();
if (BitConverter.IsLittleEndian) {
Array.Reverse(rfc4122bytes, 0, 4);
Array.Reverse(rfc4122bytes, 4, 2);
Array.Reverse(rfc4122bytes, 6, 2);
}
return new Guid(rfc4122bytes);
}
}
```
**Note**: Do not use this class when this bug is fixed. |
35,027,729 | >
> ng-disabled="condition" not disabling the div even when the condition is true.
>
>
>
---
```
<div ng-disabled="true">
// display something
</div>
``` | 2016/01/27 | [
"https://Stackoverflow.com/questions/35027729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1635800/"
] | you can try
```
<fieldset ng-disabled="true">
// display something
</fieldset>
``` | >
> Note: You can use `ng-show / ng-hide` directive for DIV elements to show or hide !
>
>
>
Use for `Form Elements` for appropriate usage of `ng-disabled` directive. see below code snippet.
```html
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="">
<label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
<button ng-model="button" ng-disabled="checked">Button</button>
</div>
```
Reference: <https://docs.angularjs.org/api/ng/directive/ngDisabled>
What to disable: <https://www.w3.org/TR/html5/disabled-elements.html>
>
> Below elements can be disabled.
>
>
>
1. button
2. input
3. select
4. textarea
5. optgroup
6. option
7. fieldset |
64,482,429 | The problem:
============
I have a model, which is referencing the basic User model of django. Right now, if I submit the form Django updates my database by replacing the existing data with the new one. I want to be able to access both of them. (In weight and date field)
Models file:
============
I saw other posts here, where they solved a problem by specifying a foreign key, but that doesn't solve it for me.
```
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
weight = models.FloatField(max_length=20, blank=True, null=True)
height = models.FloatField(max_length=20, blank=True, null=True)
date = models.DateField(auto_now_add=True)
def __str__(self):
return self.user.username
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
```
Views file:
===========
This is where I save the data that I get from my form called WeightForm
```
from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from users import models
from users.models import Profile
from .forms import WeightForm
def home(request):
form = WeightForm()
if request.is_ajax():
profile = get_object_or_404(Profile, id = request.user.id)
form = WeightForm(request.POST, instance=profile)
if form.is_valid():
form.save()
return JsonResponse({
'msg': 'Success'
})
return render(request, 'Landing/index.html',{'form':form})
```
What I tried:
=============
I used to have a OneToOneField relation with this model, but as you can see I changed it to foreignkey, according to answers I saw on this site.
Thanks if you've gotten this far in my mess :D | 2020/10/22 | [
"https://Stackoverflow.com/questions/64482429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14422281/"
] | I didn't understood exactly what you mean by "I want to be able to access both of them. (In weight and date field)" but I guess you want user to be able to see their previous data of weight and Date also, so you can try doing this:
In your models.py do try doing this,
```
class Profile(models.Model):
user_id = models.AutoField(primary_key=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
height = models.FloatField(max_length=20, blank=True, null=True)
def __str__(self):
return self.user.username
class UserData(models.Model):
Data_id = models.AutoField(primary_key=True)
user_id = models.ForeignKey(Profile, on_delete=models.CASCADE)
weight = models.FloatField(max_length=20, blank=True, null=True)
date = models.DateField(auto_now_add=True)
```
then u can have seperate forms for both the models and use them combined. | You can make a workaround
1. Create new model which would include something like "version"
2. Reference to version with foreign key
```
class ProfileChange(models.Model):
Date = models.DateField(default=datetime.datetime.today().strftime('%Y-%m-%d'))
@classmethod
def create(cls):
object = cls()
return object
class Profile(models.Model):
version = models.ForeignKey(ProfileChange,on_delete=models.CASCADE)
```
Unfortunately, you could see only one ProfileChange a day. If you want to see more of them, instead of `models.DataField` use `models.IntegerField` |
9,282,859 | Consider the following code for printing questions from text file:
```
foreach ($lines as $line_num => $line) {
if($line_num%3 == 1){
echo 'Question '.$count.':'.'<br/>'.'<input type="text" value="$line" class="tcs"/>'.'<br/>';
```
I've tried many string escaping combinations. The problem is that I get `$line` **inside the text field** instead of the variable value. Any help is greatly appreciated. | 2012/02/14 | [
"https://Stackoverflow.com/questions/9282859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/700089/"
] | Remove the variable from the `'` quoted string, or use `"` so the variable is interpreted.
```
echo 'Question ' . $count . ':<br/><input type="text" value="' . $line . '" class="tcs"/><br/>';
```
or
```
echo "Question " . $count . ":<br/><input type=\"text\" value=\"$line\" class=\"tcs\"/><br/>";
```
The first option is better, since you don't have to escape anything else. | Did you try:
```
echo 'Question ' . $count . ':'.'<br/>'.'<input type="text" value="' . $line . '" class="tcs"/>'.'<br/>';
``` |
9,282,859 | Consider the following code for printing questions from text file:
```
foreach ($lines as $line_num => $line) {
if($line_num%3 == 1){
echo 'Question '.$count.':'.'<br/>'.'<input type="text" value="$line" class="tcs"/>'.'<br/>';
```
I've tried many string escaping combinations. The problem is that I get `$line` **inside the text field** instead of the variable value. Any help is greatly appreciated. | 2012/02/14 | [
"https://Stackoverflow.com/questions/9282859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/700089/"
] | Remove the variable from the `'` quoted string, or use `"` so the variable is interpreted.
```
echo 'Question ' . $count . ':<br/><input type="text" value="' . $line . '" class="tcs"/><br/>';
```
or
```
echo "Question " . $count . ":<br/><input type=\"text\" value=\"$line\" class=\"tcs\"/><br/>";
```
The first option is better, since you don't have to escape anything else. | Variables don't get processed in single quoted strings. You need to use double quotes or another way of inserting them (such as concatenation). |
40,680,860 | I have an ASP.NET Core website that fetches data from a model and creates a dynamic HTML table to display it on the page. I have 3 selectlists on the page that determine the filtering for the data being displayed:
```
<select id="Timeframe" name="Timeframe" asp-for="timeframe" asp-items="@Model.timeframes"></select>
<select id="Category" name="Category" asp-for="category" asp-items="@Model.categories"></select>
<select id="FormOption" name="FormOption" asp-for="formOption" asp-items="@Model.formOptions"></select>
```
The code to build the table is below. The filters determine how many rows and columns are added (and filled) to the table.
```
<div>
@if (Model.selectedForm.rows.Count > 0)
{
<table name="Displaytable">
<tr>
<th></th>
<th>
Forms
</th>
@foreach (var stage in Model.selectedForm.rows[0].stages)
{
<th>
@Html.DisplayFor(modelitem => stage.label)
</th>
}
<th>
TotalTime
</th>
</tr>
@foreach (var row in Model.selectedForm.rows)
{
<tr>
<th>
@Html.DisplayFor(modelItem => row.label)
</th>
<td>
@Html.DisplayFor(modelItem => row.formCount)
</td>
@foreach (var stage in row.stages)
{
<td>
@Html.DisplayFor(modelitem => stage.timespan.TotalHours)
</td>
}
<td>
@Html.DisplayFor(modelitem => row.totalTimespan.TotalHours)
</td>
</tr>
}
</table>
}
</div>
```
These filters are submitted with a button and change the number of rows and columns of the data (as well as the data in each column and row) according to the values of the selectlists.
Depending on the filters, I could have anywhere from 2 rows to 50 and with the exception of one of my `formOptions`, will generally have a label and a single column for data (which will translate into a single bar in Google Charts).
I already have all the data I will need for any charting coming in to the table correctly for every filter - **my question is how to actually build a Google Chart based on this data, where according to the filters selected will change the charts being displayed in a similar fashion to how my table is generated?**
My intent here is to have one view with the raw data in a table (that I can access to verify the data displayed in the charts is correct) and then another view displaying said data in a Google chart instead of the table I created. | 2016/11/18 | [
"https://Stackoverflow.com/questions/40680860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154478/"
] | if you just want to grab the data from the html table
build an array using the text from each cell
then create the google DataTable using `arrayToDataTable` method
see following working snippet...
```js
google.charts.load('current', {
packages: ['corechart'],
callback: drawChart
});
function drawChart() {
var tableRows = [];
var results = document.getElementById('Displaytable');
Array.prototype.forEach.call(results.rows, function(row) {
var tableColumns = [];
Array.prototype.forEach.call(row.cells, function(cell) {
var cellText = cell.textContent || cell.innerText;
switch (cell.cellIndex) {
case 0:
tableColumns.push(cellText.trim());
break;
default:
switch (row.rowIndex) {
case 0:
tableColumns.push(cellText.trim());
break;
default:
tableColumns.push(parseFloat(cellText));
}
}
});
tableRows.push(tableColumns);
});
var data = google.visualization.arrayToDataTable(tableRows);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data);
}
```
```html
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<table id="Displaytable">
<tr>
<th></th>
<th>
Forms
</th>
<th>
A
</th>
<th>
B
</th>
<th>
C
</th>
<th>
TotalTime
</th>
</tr>
<tr>
<th>
Row 1
</th>
<td>
1
</td>
<td>
1
</td>
<td>
1
</td>
<td>
1
</td>
<td>
3
</td>
</tr>
<tr>
<th>
Row 2
</th>
<td>
2
</td>
<td>
2
</td>
<td>
2
</td>
<td>
2
</td>
<td>
6
</td>
</tr>
<tr>
<th>
Row 3
</th>
<td>
3
</td>
<td>
3
</td>
<td>
3
</td>
<td>
3
</td>
<td>
9
</td>
</tr>
</table>
``` | First off, thanks so much WhiteHat for the answer below. I realized that this question was maybe a bit too specific in terms of what I needed done. I ended up finding a solution that fit my needs. I'll post the code below in case anyone comes along and wants to see how I solved this problem.
```
<script type="text/javascript">
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn("string", "Category");
@foreach (var stage in Model.selectedForm.rows[0].stages)
{
@Html.Raw("data.addColumn('number', '" + stage.label + "');")
}
@foreach (var row in Model.selectedForm.rows)
{
@Html.Raw("data.addRow(['" + row.label + "'") //The first part of our row is the label - each subsequent stage will be filled in at each iteration below
foreach (var stage in row.stages) //For each stage in the row being created...
{
@Html.Raw(", " + stage.timespan.TotalHours) //...Continue the HTML builder adding additional timespans to eventually...
}
@Html.Raw("]);\n\n") //...close it here
}
var options = {
titlePosition: 'none',
width: 1200,
height: 400,
legend: { position: 'top', maxLines: 3 },
bar: { groupWidth: '75%' },
isStacked: true
}
var chart = new google.visualization.BarChart(document.getElementById('Chart'));
chart.draw(data, options);
}
</script>
```
This functions as both the dynamic chart creation and allows for the different forms to display a different number of columns. |
61,051,302 | I wrote this Racket code to find and display the longest sublist in a list of lists, but if the lengths of multiple sublists are equal and all the longest, I want it to return the last sublist having the longest length.
```
(define longest '())
;returns longest sublist in a list of lists
(define (longestSub losl)
(set! longest (car losl))
(for ([x (- (length losl) 1)])
(if (>= (length (list-ref losl x)) (length longest))
(set! longest (list-ref losl x))
(void losl)))
(display longest))
```
For example, if "losl" is ((1 2) (3 4 5) (6 7 8)), I want it to return (6 7 8), but right now it would return (3 4 5). Can anyone tell me what I'm doing wrong? | 2020/04/06 | [
"https://Stackoverflow.com/questions/61051302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | >
> *Can anyone tell me what I'm doing wrong?*
>
>
>
With `(for ([x (- (length losl) 1)]) ;...` the loop does not iterate to the end of the input list. With the given input, `(length losl)` is 3; so the loop clause is equivalent to `(for ([x 2]) ;...`, which is similar to `(for ([x (in-range 2)]) ;...`. This generates the values 0 and 1 for `x`, but 2 is never reached, hence the last list is never checked. To correct this problem, change to:
```
(define (longestSub losl)
(set! longest (car losl))
(for ([x (length losl)])
(if (>= (length (list-ref losl x)) (length longest))
(set! longest (list-ref losl x))
(void losl)))
(display longest))
```
Incidentally, you could get rid of the `(void losl)` by using `when` instead of `if`:
```
(define (longestSub losl)
(set! longest (car losl))
(for ([x (length losl)])
(when (>= (length (list-ref losl x)) (length longest))
(set! longest (list-ref losl x))))
(display longest))
```
Using a loop and `set!` for this may not be the most idiomatic solution. Another approach would be to use recursion, and a helper function that passes the current longest sublist:
```
(define (longest-sublist losl)
(define (lsl-helper losl longest)
(cond [(empty? losl)
longest]
[(>= (length (first losl)) (length longest))
(lsl-helper (rest losl) (first losl))]
[else (lsl-helper (rest losl) longest)]))
(lsl-helper losl '()))
```
Both solutions will work, but there are a couple of differences. The OP solution will fail with a runtime error in the event of an empty list for input: `(longestSub '())`. But this recursive solution will return the empty list for the same input instead of failing. Which behavior is preferred is up to OP. The other difference is that this recursive solution returns the longest sublist, while the OP solution merely prints it. | We kick out smaller element or left element.
```
(define (longest lst)
(foldr (λ (a b) (if (> (length a) (length b)) a b))
'()
lst))
;;; TEST
(longest '((1 2) (3 4 5) (6 7 8)))
``` |
725,943 | Recently, my default 404 action in Google Chrome is to search Yahoo. Can anyone tell me why and how I can turn it off please?
If searched most forums and all the articles are about Yahoo default search rather than 404 replacement. | 2014/03/07 | [
"https://superuser.com/questions/725943",
"https://superuser.com",
"https://superuser.com/users/305855/"
] | Since we can now work from it likely being a hijack. Couple places to start:
* Disable all browser extensions. If this solves it add them back one at a time to find the issue.
* Run an antivirus program of your choice
* Run a spyware cleaner of your choice - I personally use [superantispyware](http://www.superantispyware.com/)
* Try a different browser to see if the problem persists. If it does Chrome is the issue. If not it is a system issue.
Give these a try and come back with a result. | I had the same issue and found that the Chrome extensions to blame were called "Domain Error Assistant" and "eBay Shopping Assistant". These invasive extensions were automatically planted when I installed the uTorrent client. |
19,881 | This is Carol Ann Duffy's poem, "Mrs Icarus".
>
> I'm not the first or the last
>
> to stand on a hillock,
>
> watching the man she married
>
> prove to the world
>
> he's a total, utter, absolute, Grade A pillock.
>
>
>
>
Clearly, Duffy makes reference to Greek mythology and the story of Icarus and Daedalus' wings. However, the speaker in the poem refers to "the man she married" - is the speaker perhaps a friend of Mrs Icarus? Also, the original story states that Icarus is a boy, so it seems counterintuitive for him to have a wife, could "the man" be referring to Daedalus instead? On the other hand the last line seems to describe Icarus' overconfidence in flying too close to the Sun, so the poem appears very ambiguous about who is who. Is there an authoritative interpretation on the identities of the characters in the poem, or has the poet deliberately left it ambiguous? | 2021/11/01 | [
"https://literature.stackexchange.com/questions/19881",
"https://literature.stackexchange.com",
"https://literature.stackexchange.com/users/14069/"
] | I think you’re taking it too literally. The speaker is an imaginative invention by the poet, and is not intended to represent any specific character within the classical Icarus myth. She is a woman – any modern wife – who is embarrassed by her husband doing something idiotic in public. She is imagining herself as ‘Mrs Icarus’ and comparing Icarus’s very public demonstration of his foolishness with that of her own husband.
The poet is not being ambiguous at all. Bear in mind that the poem comes from a collection called *The World's Wife* which, according to [Wikipedia](https://en.wikipedia.org/wiki/The_World%27s_Wife), "focuses on the unheard perspective of female counterparts of famously known male figures; it gives a voice to the wives of famous and infamous 'great men' of world literature and civilization". Her speaker, as in all these poems, is an 'everywoman' character whose words shed light on female experience generally. | As no account claims that Icarus was married, it's a metaphor. Her husband has proven his folly as thoroughly as Icarus had when he crashed owing to his own folly, ignoring what Daedalus had warned him of in advance. |
4,940,586 | How would one go about caching / managing many large files (videos) on a user's computer via browser mechanisms (plugins are acceptable solutions). From what I can tell, local storage is about database type data, not files. | 2011/02/09 | [
"https://Stackoverflow.com/questions/4940586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/174621/"
] | HTML5 FileSystem API is dead as others have said. IndexedDB seems to be the other option. See [here](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API#Browser_compatibility). | The answer to this question depends on your answers to the following questions:
* Are you fine with the fact that support for writing files currently exists only in Chromium-based browsers (Chrome & Opera)?
* Are you fine with utilizing an as-of-now proprietary API to take advantage of such a capbility?
* Are you fine with the possibility of removal of said API in the future?
* Are you fine with the constriction of files created with said API to a **sandbox** (a location outside of which the files can produce no effect) on disk?
* Are you fine with the use of a **virtual file system** (a directory structure which does not necessarily exist on disk in the same form that it does when accessed from within the browser) to represent such files?
If you answered "yes" to all of the above, then with the [File](https://www.w3.org/TR/FileAPI/), [FileWriter](https://www.w3.org/TR/2012/WD-file-writer-api-20120417/) and [FileSystem](https://www.w3.org/TR/2012/WD-file-system-api-20120417/) APIs, you can read and write files from the context of a browser tab/window using Javascript.
Here are simple examples of how the APIs are used, directly and indirectly, in tandem to do these things:
**[BakedGoods](https://github.com/klawson88/Baked-Goods)\***
Write file:
```
//"SGVsbG8gd29ybGQh" is "Hello world!" encoded in Base64; raw binary data can
//also be written with the use of Typed Arrays and the appropriate mime type
bakedGoods.set({
data: [{key: "testFile", value: "SGVsbG8gd29ybGQh", dataFormat: "text/plain"}],
storageTypes: ["fileSystem"],
options: {fileSystem:{storageType: Window.PERSISTENT}},
complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});
```
Read file:
```
bakedGoods.get({
data: ["testFile"],
storageTypes: ["fileSystem"],
options: {fileSystem:{storageType: Window.PERSISTENT}},
complete: function(resultDataObj, byStorageTypeErrorObj){}
});
```
**Using the raw File, FileWriter, and FileSystem APIs**
Write file:
```
function onQuotaRequestSuccess(grantedQuota)
{
function saveFile(directoryEntry)
{
function createFileWriter(fileEntry)
{
function write(fileWriter)
{
//"SGVsbG8gd29ybGQh" is "Hello world!" encoded in Base64;
//raw binary data can also be written with the use of
//Typed Arrays and the appropriate mime type
var dataBlob = new Blob(["SGVsbG8gd29ybGQh"], {type: "text/plain"});
fileWriter.write(dataBlob);
}
fileEntry.createWriter(write);
}
directoryEntry.getFile(
"testFile",
{create: true, exclusive: true},
createFileWriter
);
}
requestFileSystem(Window.PERSISTENT, grantedQuota, saveFile);
}
var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);
```
Read file:
```
function onQuotaRequestSuccess(grantedQuota)
{
function getfile(directoryEntry)
{
function readFile(fileEntry)
{
function read(file)
{
var fileReader = new FileReader();
fileReader.onload = function(){var fileData = fileReader.result};
fileReader.readAsText(file);
}
fileEntry.file(read);
}
directoryEntry.getFile(
"testFile",
{create: false},
readFile
);
}
requestFileSystem(Window.PERSISTENT, grantedQuota, getFile);
}
var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);
```
---
Since you're also open to non-native (plug-in based) solutions, you can take advantage of file i/o enabled by Silverlight in [IsolatedStorage](https://msdn.microsoft.com/en-us/library/bdts8hk0(v=vs.95).ASPX), access to which is provided through Silverlight.
IsolatedStorage is similar in many aspects to FileSystem, in particular it also exists in a sandbox and makes use of a virtual file system. However, [managed code](https://msdn.microsoft.com/en-us/library/windows/desktop/bb318664(v=vs.85).aspx) is required to utilize this facility; a solution which requires writing such code is beyond the scope of this question.
Of course, a solution which makes use of complementary managed code, leaving one with only Javascript to write, is well within the scope of this question ;) :
```
//Write file to first of either FileSystem or IsolatedStorage
bakedGoods.set({
data: [{key: "testFile", value: "SGVsbG8gd29ybGQh", dataFormat: "text/plain"}],
storageTypes: ["fileSystem", "silverlight"],
options: {fileSystem:{storageType: Window.PERSISTENT}},
complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});
```
*\*BakedGoods is maintained by none other than this guy right here :)* |
4,940,586 | How would one go about caching / managing many large files (videos) on a user's computer via browser mechanisms (plugins are acceptable solutions). From what I can tell, local storage is about database type data, not files. | 2011/02/09 | [
"https://Stackoverflow.com/questions/4940586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/174621/"
] | The FileSystem API[1,2] was going to be your best bet going forward, at one point it was very much bleeding edge. However it has been been abandoned by w3c. From their own documentation:
>
> Work on this document has been discontinued and it should not be referenced or used as a basis for implementation.
>
>
>
1. <http://dev.w3.org/2009/dap/file-system/pub/FileSystem/>
2. <http://www.html5rocks.com/tutorials/file/filesystem/> | The answer to this question depends on your answers to the following questions:
* Are you fine with the fact that support for writing files currently exists only in Chromium-based browsers (Chrome & Opera)?
* Are you fine with utilizing an as-of-now proprietary API to take advantage of such a capbility?
* Are you fine with the possibility of removal of said API in the future?
* Are you fine with the constriction of files created with said API to a **sandbox** (a location outside of which the files can produce no effect) on disk?
* Are you fine with the use of a **virtual file system** (a directory structure which does not necessarily exist on disk in the same form that it does when accessed from within the browser) to represent such files?
If you answered "yes" to all of the above, then with the [File](https://www.w3.org/TR/FileAPI/), [FileWriter](https://www.w3.org/TR/2012/WD-file-writer-api-20120417/) and [FileSystem](https://www.w3.org/TR/2012/WD-file-system-api-20120417/) APIs, you can read and write files from the context of a browser tab/window using Javascript.
Here are simple examples of how the APIs are used, directly and indirectly, in tandem to do these things:
**[BakedGoods](https://github.com/klawson88/Baked-Goods)\***
Write file:
```
//"SGVsbG8gd29ybGQh" is "Hello world!" encoded in Base64; raw binary data can
//also be written with the use of Typed Arrays and the appropriate mime type
bakedGoods.set({
data: [{key: "testFile", value: "SGVsbG8gd29ybGQh", dataFormat: "text/plain"}],
storageTypes: ["fileSystem"],
options: {fileSystem:{storageType: Window.PERSISTENT}},
complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});
```
Read file:
```
bakedGoods.get({
data: ["testFile"],
storageTypes: ["fileSystem"],
options: {fileSystem:{storageType: Window.PERSISTENT}},
complete: function(resultDataObj, byStorageTypeErrorObj){}
});
```
**Using the raw File, FileWriter, and FileSystem APIs**
Write file:
```
function onQuotaRequestSuccess(grantedQuota)
{
function saveFile(directoryEntry)
{
function createFileWriter(fileEntry)
{
function write(fileWriter)
{
//"SGVsbG8gd29ybGQh" is "Hello world!" encoded in Base64;
//raw binary data can also be written with the use of
//Typed Arrays and the appropriate mime type
var dataBlob = new Blob(["SGVsbG8gd29ybGQh"], {type: "text/plain"});
fileWriter.write(dataBlob);
}
fileEntry.createWriter(write);
}
directoryEntry.getFile(
"testFile",
{create: true, exclusive: true},
createFileWriter
);
}
requestFileSystem(Window.PERSISTENT, grantedQuota, saveFile);
}
var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);
```
Read file:
```
function onQuotaRequestSuccess(grantedQuota)
{
function getfile(directoryEntry)
{
function readFile(fileEntry)
{
function read(file)
{
var fileReader = new FileReader();
fileReader.onload = function(){var fileData = fileReader.result};
fileReader.readAsText(file);
}
fileEntry.file(read);
}
directoryEntry.getFile(
"testFile",
{create: false},
readFile
);
}
requestFileSystem(Window.PERSISTENT, grantedQuota, getFile);
}
var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);
```
---
Since you're also open to non-native (plug-in based) solutions, you can take advantage of file i/o enabled by Silverlight in [IsolatedStorage](https://msdn.microsoft.com/en-us/library/bdts8hk0(v=vs.95).ASPX), access to which is provided through Silverlight.
IsolatedStorage is similar in many aspects to FileSystem, in particular it also exists in a sandbox and makes use of a virtual file system. However, [managed code](https://msdn.microsoft.com/en-us/library/windows/desktop/bb318664(v=vs.85).aspx) is required to utilize this facility; a solution which requires writing such code is beyond the scope of this question.
Of course, a solution which makes use of complementary managed code, leaving one with only Javascript to write, is well within the scope of this question ;) :
```
//Write file to first of either FileSystem or IsolatedStorage
bakedGoods.set({
data: [{key: "testFile", value: "SGVsbG8gd29ybGQh", dataFormat: "text/plain"}],
storageTypes: ["fileSystem", "silverlight"],
options: {fileSystem:{storageType: Window.PERSISTENT}},
complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});
```
*\*BakedGoods is maintained by none other than this guy right here :)* |
4,940,586 | How would one go about caching / managing many large files (videos) on a user's computer via browser mechanisms (plugins are acceptable solutions). From what I can tell, local storage is about database type data, not files. | 2011/02/09 | [
"https://Stackoverflow.com/questions/4940586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/174621/"
] | The FileSystem API[1,2] was going to be your best bet going forward, at one point it was very much bleeding edge. However it has been been abandoned by w3c. From their own documentation:
>
> Work on this document has been discontinued and it should not be referenced or used as a basis for implementation.
>
>
>
1. <http://dev.w3.org/2009/dap/file-system/pub/FileSystem/>
2. <http://www.html5rocks.com/tutorials/file/filesystem/> | HTML5 FileSystem API is dead as others have said. IndexedDB seems to be the other option. See [here](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API#Browser_compatibility). |
4,940,586 | How would one go about caching / managing many large files (videos) on a user's computer via browser mechanisms (plugins are acceptable solutions). From what I can tell, local storage is about database type data, not files. | 2011/02/09 | [
"https://Stackoverflow.com/questions/4940586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/174621/"
] | The answer to this question depends on your answers to the following questions:
* Are you fine with the fact that support for writing files currently exists only in Chromium-based browsers (Chrome & Opera)?
* Are you fine with utilizing an as-of-now proprietary API to take advantage of such a capbility?
* Are you fine with the possibility of removal of said API in the future?
* Are you fine with the constriction of files created with said API to a **sandbox** (a location outside of which the files can produce no effect) on disk?
* Are you fine with the use of a **virtual file system** (a directory structure which does not necessarily exist on disk in the same form that it does when accessed from within the browser) to represent such files?
If you answered "yes" to all of the above, then with the [File](https://www.w3.org/TR/FileAPI/), [FileWriter](https://www.w3.org/TR/2012/WD-file-writer-api-20120417/) and [FileSystem](https://www.w3.org/TR/2012/WD-file-system-api-20120417/) APIs, you can read and write files from the context of a browser tab/window using Javascript.
Here are simple examples of how the APIs are used, directly and indirectly, in tandem to do these things:
**[BakedGoods](https://github.com/klawson88/Baked-Goods)\***
Write file:
```
//"SGVsbG8gd29ybGQh" is "Hello world!" encoded in Base64; raw binary data can
//also be written with the use of Typed Arrays and the appropriate mime type
bakedGoods.set({
data: [{key: "testFile", value: "SGVsbG8gd29ybGQh", dataFormat: "text/plain"}],
storageTypes: ["fileSystem"],
options: {fileSystem:{storageType: Window.PERSISTENT}},
complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});
```
Read file:
```
bakedGoods.get({
data: ["testFile"],
storageTypes: ["fileSystem"],
options: {fileSystem:{storageType: Window.PERSISTENT}},
complete: function(resultDataObj, byStorageTypeErrorObj){}
});
```
**Using the raw File, FileWriter, and FileSystem APIs**
Write file:
```
function onQuotaRequestSuccess(grantedQuota)
{
function saveFile(directoryEntry)
{
function createFileWriter(fileEntry)
{
function write(fileWriter)
{
//"SGVsbG8gd29ybGQh" is "Hello world!" encoded in Base64;
//raw binary data can also be written with the use of
//Typed Arrays and the appropriate mime type
var dataBlob = new Blob(["SGVsbG8gd29ybGQh"], {type: "text/plain"});
fileWriter.write(dataBlob);
}
fileEntry.createWriter(write);
}
directoryEntry.getFile(
"testFile",
{create: true, exclusive: true},
createFileWriter
);
}
requestFileSystem(Window.PERSISTENT, grantedQuota, saveFile);
}
var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);
```
Read file:
```
function onQuotaRequestSuccess(grantedQuota)
{
function getfile(directoryEntry)
{
function readFile(fileEntry)
{
function read(file)
{
var fileReader = new FileReader();
fileReader.onload = function(){var fileData = fileReader.result};
fileReader.readAsText(file);
}
fileEntry.file(read);
}
directoryEntry.getFile(
"testFile",
{create: false},
readFile
);
}
requestFileSystem(Window.PERSISTENT, grantedQuota, getFile);
}
var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);
```
---
Since you're also open to non-native (plug-in based) solutions, you can take advantage of file i/o enabled by Silverlight in [IsolatedStorage](https://msdn.microsoft.com/en-us/library/bdts8hk0(v=vs.95).ASPX), access to which is provided through Silverlight.
IsolatedStorage is similar in many aspects to FileSystem, in particular it also exists in a sandbox and makes use of a virtual file system. However, [managed code](https://msdn.microsoft.com/en-us/library/windows/desktop/bb318664(v=vs.85).aspx) is required to utilize this facility; a solution which requires writing such code is beyond the scope of this question.
Of course, a solution which makes use of complementary managed code, leaving one with only Javascript to write, is well within the scope of this question ;) :
```
//Write file to first of either FileSystem or IsolatedStorage
bakedGoods.set({
data: [{key: "testFile", value: "SGVsbG8gd29ybGQh", dataFormat: "text/plain"}],
storageTypes: ["fileSystem", "silverlight"],
options: {fileSystem:{storageType: Window.PERSISTENT}},
complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});
```
*\*BakedGoods is maintained by none other than this guy right here :)* | HTML5 local storage is currently limited to 5MB by default in most implementations. I don't think you can store a lot of video in there.
Source: <https://web.archive.org/web/20120714114208/http://diveintohtml5.info/storage.html> |
4,940,586 | How would one go about caching / managing many large files (videos) on a user's computer via browser mechanisms (plugins are acceptable solutions). From what I can tell, local storage is about database type data, not files. | 2011/02/09 | [
"https://Stackoverflow.com/questions/4940586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/174621/"
] | HTML5 FileSystem API is dead as others have said. IndexedDB seems to be the other option. See [here](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API#Browser_compatibility). | Well most parts of html5 local storage are explained above.
here <https://stackoverflow.com/a/11272187/1460465> there was a similar question, not about video's but if you can add a xml to local storage.
I mentioned a article in my answer in the article javascript is used to parse a xml to local storage and how to query it offline.
Might help you. |
4,940,586 | How would one go about caching / managing many large files (videos) on a user's computer via browser mechanisms (plugins are acceptable solutions). From what I can tell, local storage is about database type data, not files. | 2011/02/09 | [
"https://Stackoverflow.com/questions/4940586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/174621/"
] | HTML5 FileSystem API is dead as others have said. IndexedDB seems to be the other option. See [here](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API#Browser_compatibility). | [FSO.js](http://fsojs.com/) will wrap the HTML5 FileSystem API for you, making it really easy to store, manage, and manipulate sets of large files in a sandboxed File System. |
4,940,586 | How would one go about caching / managing many large files (videos) on a user's computer via browser mechanisms (plugins are acceptable solutions). From what I can tell, local storage is about database type data, not files. | 2011/02/09 | [
"https://Stackoverflow.com/questions/4940586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/174621/"
] | The answer to this question depends on your answers to the following questions:
* Are you fine with the fact that support for writing files currently exists only in Chromium-based browsers (Chrome & Opera)?
* Are you fine with utilizing an as-of-now proprietary API to take advantage of such a capbility?
* Are you fine with the possibility of removal of said API in the future?
* Are you fine with the constriction of files created with said API to a **sandbox** (a location outside of which the files can produce no effect) on disk?
* Are you fine with the use of a **virtual file system** (a directory structure which does not necessarily exist on disk in the same form that it does when accessed from within the browser) to represent such files?
If you answered "yes" to all of the above, then with the [File](https://www.w3.org/TR/FileAPI/), [FileWriter](https://www.w3.org/TR/2012/WD-file-writer-api-20120417/) and [FileSystem](https://www.w3.org/TR/2012/WD-file-system-api-20120417/) APIs, you can read and write files from the context of a browser tab/window using Javascript.
Here are simple examples of how the APIs are used, directly and indirectly, in tandem to do these things:
**[BakedGoods](https://github.com/klawson88/Baked-Goods)\***
Write file:
```
//"SGVsbG8gd29ybGQh" is "Hello world!" encoded in Base64; raw binary data can
//also be written with the use of Typed Arrays and the appropriate mime type
bakedGoods.set({
data: [{key: "testFile", value: "SGVsbG8gd29ybGQh", dataFormat: "text/plain"}],
storageTypes: ["fileSystem"],
options: {fileSystem:{storageType: Window.PERSISTENT}},
complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});
```
Read file:
```
bakedGoods.get({
data: ["testFile"],
storageTypes: ["fileSystem"],
options: {fileSystem:{storageType: Window.PERSISTENT}},
complete: function(resultDataObj, byStorageTypeErrorObj){}
});
```
**Using the raw File, FileWriter, and FileSystem APIs**
Write file:
```
function onQuotaRequestSuccess(grantedQuota)
{
function saveFile(directoryEntry)
{
function createFileWriter(fileEntry)
{
function write(fileWriter)
{
//"SGVsbG8gd29ybGQh" is "Hello world!" encoded in Base64;
//raw binary data can also be written with the use of
//Typed Arrays and the appropriate mime type
var dataBlob = new Blob(["SGVsbG8gd29ybGQh"], {type: "text/plain"});
fileWriter.write(dataBlob);
}
fileEntry.createWriter(write);
}
directoryEntry.getFile(
"testFile",
{create: true, exclusive: true},
createFileWriter
);
}
requestFileSystem(Window.PERSISTENT, grantedQuota, saveFile);
}
var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);
```
Read file:
```
function onQuotaRequestSuccess(grantedQuota)
{
function getfile(directoryEntry)
{
function readFile(fileEntry)
{
function read(file)
{
var fileReader = new FileReader();
fileReader.onload = function(){var fileData = fileReader.result};
fileReader.readAsText(file);
}
fileEntry.file(read);
}
directoryEntry.getFile(
"testFile",
{create: false},
readFile
);
}
requestFileSystem(Window.PERSISTENT, grantedQuota, getFile);
}
var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);
```
---
Since you're also open to non-native (plug-in based) solutions, you can take advantage of file i/o enabled by Silverlight in [IsolatedStorage](https://msdn.microsoft.com/en-us/library/bdts8hk0(v=vs.95).ASPX), access to which is provided through Silverlight.
IsolatedStorage is similar in many aspects to FileSystem, in particular it also exists in a sandbox and makes use of a virtual file system. However, [managed code](https://msdn.microsoft.com/en-us/library/windows/desktop/bb318664(v=vs.85).aspx) is required to utilize this facility; a solution which requires writing such code is beyond the scope of this question.
Of course, a solution which makes use of complementary managed code, leaving one with only Javascript to write, is well within the scope of this question ;) :
```
//Write file to first of either FileSystem or IsolatedStorage
bakedGoods.set({
data: [{key: "testFile", value: "SGVsbG8gd29ybGQh", dataFormat: "text/plain"}],
storageTypes: ["fileSystem", "silverlight"],
options: {fileSystem:{storageType: Window.PERSISTENT}},
complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});
```
*\*BakedGoods is maintained by none other than this guy right here :)* | [FSO.js](http://fsojs.com/) will wrap the HTML5 FileSystem API for you, making it really easy to store, manage, and manipulate sets of large files in a sandboxed File System. |
4,940,586 | How would one go about caching / managing many large files (videos) on a user's computer via browser mechanisms (plugins are acceptable solutions). From what I can tell, local storage is about database type data, not files. | 2011/02/09 | [
"https://Stackoverflow.com/questions/4940586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/174621/"
] | The answer to this question depends on your answers to the following questions:
* Are you fine with the fact that support for writing files currently exists only in Chromium-based browsers (Chrome & Opera)?
* Are you fine with utilizing an as-of-now proprietary API to take advantage of such a capbility?
* Are you fine with the possibility of removal of said API in the future?
* Are you fine with the constriction of files created with said API to a **sandbox** (a location outside of which the files can produce no effect) on disk?
* Are you fine with the use of a **virtual file system** (a directory structure which does not necessarily exist on disk in the same form that it does when accessed from within the browser) to represent such files?
If you answered "yes" to all of the above, then with the [File](https://www.w3.org/TR/FileAPI/), [FileWriter](https://www.w3.org/TR/2012/WD-file-writer-api-20120417/) and [FileSystem](https://www.w3.org/TR/2012/WD-file-system-api-20120417/) APIs, you can read and write files from the context of a browser tab/window using Javascript.
Here are simple examples of how the APIs are used, directly and indirectly, in tandem to do these things:
**[BakedGoods](https://github.com/klawson88/Baked-Goods)\***
Write file:
```
//"SGVsbG8gd29ybGQh" is "Hello world!" encoded in Base64; raw binary data can
//also be written with the use of Typed Arrays and the appropriate mime type
bakedGoods.set({
data: [{key: "testFile", value: "SGVsbG8gd29ybGQh", dataFormat: "text/plain"}],
storageTypes: ["fileSystem"],
options: {fileSystem:{storageType: Window.PERSISTENT}},
complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});
```
Read file:
```
bakedGoods.get({
data: ["testFile"],
storageTypes: ["fileSystem"],
options: {fileSystem:{storageType: Window.PERSISTENT}},
complete: function(resultDataObj, byStorageTypeErrorObj){}
});
```
**Using the raw File, FileWriter, and FileSystem APIs**
Write file:
```
function onQuotaRequestSuccess(grantedQuota)
{
function saveFile(directoryEntry)
{
function createFileWriter(fileEntry)
{
function write(fileWriter)
{
//"SGVsbG8gd29ybGQh" is "Hello world!" encoded in Base64;
//raw binary data can also be written with the use of
//Typed Arrays and the appropriate mime type
var dataBlob = new Blob(["SGVsbG8gd29ybGQh"], {type: "text/plain"});
fileWriter.write(dataBlob);
}
fileEntry.createWriter(write);
}
directoryEntry.getFile(
"testFile",
{create: true, exclusive: true},
createFileWriter
);
}
requestFileSystem(Window.PERSISTENT, grantedQuota, saveFile);
}
var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);
```
Read file:
```
function onQuotaRequestSuccess(grantedQuota)
{
function getfile(directoryEntry)
{
function readFile(fileEntry)
{
function read(file)
{
var fileReader = new FileReader();
fileReader.onload = function(){var fileData = fileReader.result};
fileReader.readAsText(file);
}
fileEntry.file(read);
}
directoryEntry.getFile(
"testFile",
{create: false},
readFile
);
}
requestFileSystem(Window.PERSISTENT, grantedQuota, getFile);
}
var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);
```
---
Since you're also open to non-native (plug-in based) solutions, you can take advantage of file i/o enabled by Silverlight in [IsolatedStorage](https://msdn.microsoft.com/en-us/library/bdts8hk0(v=vs.95).ASPX), access to which is provided through Silverlight.
IsolatedStorage is similar in many aspects to FileSystem, in particular it also exists in a sandbox and makes use of a virtual file system. However, [managed code](https://msdn.microsoft.com/en-us/library/windows/desktop/bb318664(v=vs.85).aspx) is required to utilize this facility; a solution which requires writing such code is beyond the scope of this question.
Of course, a solution which makes use of complementary managed code, leaving one with only Javascript to write, is well within the scope of this question ;) :
```
//Write file to first of either FileSystem or IsolatedStorage
bakedGoods.set({
data: [{key: "testFile", value: "SGVsbG8gd29ybGQh", dataFormat: "text/plain"}],
storageTypes: ["fileSystem", "silverlight"],
options: {fileSystem:{storageType: Window.PERSISTENT}},
complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});
```
*\*BakedGoods is maintained by none other than this guy right here :)* | Well most parts of html5 local storage are explained above.
here <https://stackoverflow.com/a/11272187/1460465> there was a similar question, not about video's but if you can add a xml to local storage.
I mentioned a article in my answer in the article javascript is used to parse a xml to local storage and how to query it offline.
Might help you. |
4,940,586 | How would one go about caching / managing many large files (videos) on a user's computer via browser mechanisms (plugins are acceptable solutions). From what I can tell, local storage is about database type data, not files. | 2011/02/09 | [
"https://Stackoverflow.com/questions/4940586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/174621/"
] | The FileSystem API[1,2] was going to be your best bet going forward, at one point it was very much bleeding edge. However it has been been abandoned by w3c. From their own documentation:
>
> Work on this document has been discontinued and it should not be referenced or used as a basis for implementation.
>
>
>
1. <http://dev.w3.org/2009/dap/file-system/pub/FileSystem/>
2. <http://www.html5rocks.com/tutorials/file/filesystem/> | [FSO.js](http://fsojs.com/) will wrap the HTML5 FileSystem API for you, making it really easy to store, manage, and manipulate sets of large files in a sandboxed File System. |
4,940,586 | How would one go about caching / managing many large files (videos) on a user's computer via browser mechanisms (plugins are acceptable solutions). From what I can tell, local storage is about database type data, not files. | 2011/02/09 | [
"https://Stackoverflow.com/questions/4940586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/174621/"
] | The FileSystem API[1,2] was going to be your best bet going forward, at one point it was very much bleeding edge. However it has been been abandoned by w3c. From their own documentation:
>
> Work on this document has been discontinued and it should not be referenced or used as a basis for implementation.
>
>
>
1. <http://dev.w3.org/2009/dap/file-system/pub/FileSystem/>
2. <http://www.html5rocks.com/tutorials/file/filesystem/> | HTML5 local storage is currently limited to 5MB by default in most implementations. I don't think you can store a lot of video in there.
Source: <https://web.archive.org/web/20120714114208/http://diveintohtml5.info/storage.html> |
244,509 | I'm going to install Windows and I don't want it's partition to be mounted when Ubuntu starts. How do I do this?
Also, are Ubuntu partitions mounted on Windows startup? | 2013/01/18 | [
"https://askubuntu.com/questions/244509",
"https://askubuntu.com",
"https://askubuntu.com/users/86866/"
] | recordmydesktop is buggy & inconsistant at best. Secondly, if I understand correctly, the op is not wanting to record a screencast, but external video. IF a screencast is what the op wants, ffmpeg is the most consistant & quality option. Heres a vid with instructions (for Arch, but same instruction in Ubuntu) <http://youtu.be/BuKo0l3ZfEE>
As for the best video editing/recording options? Kdenlive & Openshot for editing.
But the best way I found for recording webcam video is to open Kamerka (webcam app) in full screen while recording the screencast with ffmpeg as instructed in the video. I do this all the time & it works great.
Audio? Audacity is the clear winner here.
If you record the audio with the video, you can use kdenlive to extract the audio, then open that in audacity for any editing as the easiest way I know to get a seperate audio version that matches the video | You can install `gtk-recordMyDesktop` from software center. I think it will solve your problem.
RecordMyDesktop is one of the few video capture programs available in Ubuntu. Keeping with Linux’s free philosophy, RecordMyDesktop produces Ogg Theora video files out of your entire desktop, or just a selected section. If you haven’t heard of Ogg Theora, don’t worry – any modern video player will play these files, and you can even upload them to YouTube without having to convert them to another format. |
7,809,483 | I have a WebView in which I can access to web pages. Is it possible, when I am offline to have access for example to the images that have been previously downloaded?
And if it is possible how can I do this?
Thanks in advance. | 2011/10/18 | [
"https://Stackoverflow.com/questions/7809483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/761805/"
] | Yes, you can, at least for Android 2.3 and lower.
If you want to see the entire cache folder, it is situated here:
```
<android cache dir>/<your app package>/cache/webviewCache/
```
If you already know the URL of the cached image, you can get the actual file so:
```
String uri = "http://the url of the image that you need";
String hashCode = String.format("%08x", uri.hashCode());
File file = new File(new File(getCacheDir(), "webviewCache"), hashCode);
// if the call file.exist() returns true, then the file presents in the cache
``` | `CacheManager`: <http://developer.android.com/reference/android/webkit/CacheManager.html> |
7,809,483 | I have a WebView in which I can access to web pages. Is it possible, when I am offline to have access for example to the images that have been previously downloaded?
And if it is possible how can I do this?
Thanks in advance. | 2011/10/18 | [
"https://Stackoverflow.com/questions/7809483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/761805/"
] | Yes, you can, at least for Android 2.3 and lower.
If you want to see the entire cache folder, it is situated here:
```
<android cache dir>/<your app package>/cache/webviewCache/
```
If you already know the URL of the cached image, you can get the actual file so:
```
String uri = "http://the url of the image that you need";
String hashCode = String.format("%08x", uri.hashCode());
File file = new File(new File(getCacheDir(), "webviewCache"), hashCode);
// if the call file.exist() returns true, then the file presents in the cache
``` | If someone else faces this problem, I had a similar issue and I solve it managing(saving and retrieving) my app cache manually. [Here it is](https://stackoverflow.com/questions/17388989/check-if-file-already-exists-in-webview-cache-android/17510721#17510721) my related post. |
7,809,483 | I have a WebView in which I can access to web pages. Is it possible, when I am offline to have access for example to the images that have been previously downloaded?
And if it is possible how can I do this?
Thanks in advance. | 2011/10/18 | [
"https://Stackoverflow.com/questions/7809483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/761805/"
] | If someone else faces this problem, I had a similar issue and I solve it managing(saving and retrieving) my app cache manually. [Here it is](https://stackoverflow.com/questions/17388989/check-if-file-already-exists-in-webview-cache-android/17510721#17510721) my related post. | `CacheManager`: <http://developer.android.com/reference/android/webkit/CacheManager.html> |
44,650,956 | Say I have a Table called "MARKS" with the columns: Value, subject\_id and student\_id.
Now I want to write a query to display the names of all students who have secured more than 50 in ALL subjects that they have appeared in.
How can that be achieved?
Example:
Lets say the subjects are maths, english, history.
Even if a student scores 100 in maths, 100 in english but 40 in history, he should be considered as failed and not be displayed. | 2017/06/20 | [
"https://Stackoverflow.com/questions/44650956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6050285/"
] | There are several ways to get what you expect, but in the simplest case the `HAVING` clause may help. In the following query grouping is done by `student_id`, so the `min` function gets minimal value over all subjects for each `student_id`:
```
SELECT student_id
FROM marks_table
GROUP BY student_id
HAVING min(marks) > 50;
```
Then join student names by `student_id`. | Returns all students with subjects appeared
```
select student_id,subject_id, value from marks
where
(case when value < 50 then 'failed' else 'pass' end ) = 'pass'
``` |
44,650,956 | Say I have a Table called "MARKS" with the columns: Value, subject\_id and student\_id.
Now I want to write a query to display the names of all students who have secured more than 50 in ALL subjects that they have appeared in.
How can that be achieved?
Example:
Lets say the subjects are maths, english, history.
Even if a student scores 100 in maths, 100 in english but 40 in history, he should be considered as failed and not be displayed. | 2017/06/20 | [
"https://Stackoverflow.com/questions/44650956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6050285/"
] | Returns all students with subjects appeared
```
select student_id,subject_id, value from marks
where
(case when value < 50 then 'failed' else 'pass' end ) = 'pass'
``` | ```
select *
from
(
select student_id, MIN(Value) as sum_value
from MARKS
group by student_id
) summed
where
sum_value > 50
``` |
44,650,956 | Say I have a Table called "MARKS" with the columns: Value, subject\_id and student\_id.
Now I want to write a query to display the names of all students who have secured more than 50 in ALL subjects that they have appeared in.
How can that be achieved?
Example:
Lets say the subjects are maths, english, history.
Even if a student scores 100 in maths, 100 in english but 40 in history, he should be considered as failed and not be displayed. | 2017/06/20 | [
"https://Stackoverflow.com/questions/44650956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6050285/"
] | There are several ways to get what you expect, but in the simplest case the `HAVING` clause may help. In the following query grouping is done by `student_id`, so the `min` function gets minimal value over all subjects for each `student_id`:
```
SELECT student_id
FROM marks_table
GROUP BY student_id
HAVING min(marks) > 50;
```
Then join student names by `student_id`. | I would say:
```
select student_id
from table
where student_id not in (
select student_id
from table
where value < 50
)
```
Beware, if you have nulls in student\_id you'll receive incorrect results. Geta round this with a coalesce() in the sub-select |
44,650,956 | Say I have a Table called "MARKS" with the columns: Value, subject\_id and student\_id.
Now I want to write a query to display the names of all students who have secured more than 50 in ALL subjects that they have appeared in.
How can that be achieved?
Example:
Lets say the subjects are maths, english, history.
Even if a student scores 100 in maths, 100 in english but 40 in history, he should be considered as failed and not be displayed. | 2017/06/20 | [
"https://Stackoverflow.com/questions/44650956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6050285/"
] | There are several ways to get what you expect, but in the simplest case the `HAVING` clause may help. In the following query grouping is done by `student_id`, so the `min` function gets minimal value over all subjects for each `student_id`:
```
SELECT student_id
FROM marks_table
GROUP BY student_id
HAVING min(marks) > 50;
```
Then join student names by `student_id`. | ```
select *
from
(
select student_id, MIN(Value) as sum_value
from MARKS
group by student_id
) summed
where
sum_value > 50
``` |
44,650,956 | Say I have a Table called "MARKS" with the columns: Value, subject\_id and student\_id.
Now I want to write a query to display the names of all students who have secured more than 50 in ALL subjects that they have appeared in.
How can that be achieved?
Example:
Lets say the subjects are maths, english, history.
Even if a student scores 100 in maths, 100 in english but 40 in history, he should be considered as failed and not be displayed. | 2017/06/20 | [
"https://Stackoverflow.com/questions/44650956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6050285/"
] | I would say:
```
select student_id
from table
where student_id not in (
select student_id
from table
where value < 50
)
```
Beware, if you have nulls in student\_id you'll receive incorrect results. Geta round this with a coalesce() in the sub-select | ```
select *
from
(
select student_id, MIN(Value) as sum_value
from MARKS
group by student_id
) summed
where
sum_value > 50
``` |
26,094,833 | How to get iframe attributes inside iframe javascript code
```
<div>
<iframe src="http://192.168.0.108:8092/"
name="otherDomain"
width="100%"
height="600px"
style="border: 0;"
data-auth-token="xyz"
data-auth-key="abc"
>
</div>
```
I am trying with
```
console.log(window.frameElement.getAttribute('data-auth-token'))
```
If iframe url and browser user is same I am able to get iframe attributes. if the urls are different I am getting following error.
```
Uncaught SecurityError: Failed to read the 'frame' property from 'Window': Blocked a frame with origin "http://192.168.0.108:8092" from accessing a frame with origin "http://localhost:8092". Protocols, domains, and ports must match.
```
Is it possible to get cross domain iframe attributes inside JavaScript. | 2014/09/29 | [
"https://Stackoverflow.com/questions/26094833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/242262/"
] | You **can't add the aar** file to libs folder in Eclipse (it isn't a jar file)
**The best way** to work with the new `RecyclerView` is, currently, to switch to **Android Studio** and add this dependency to your build.gradle
```
compile 'com.android.support:recyclerview-v7:+'
```
**Just a note.** It is not a good practice to use the '+' placeholder, but in this case you are trying a preview release, so it will be update soon with stable release.
You can use one of these versions.
Check your sdk for updated version:
```
//it requires compileSdkVersion 23
compile 'com.android.support:recyclerview-v7:23.3.0'
compile 'com.android.support:recyclerview-v7:23.2.1'
compile 'com.android.support:recyclerview-v7:23.2.0'
compile 'com.android.support:recyclerview-v7:23.1.1'
compile 'com.android.support:recyclerview-v7:23.1.0'
compile 'com.android.support:recyclerview-v7:23.0.1'
compile 'com.android.support:recyclerview-v7:23.0.0'
//it requires compileSdkVersion 22
compile 'com.android.support:recyclerview-v7:22.2.1'
compile 'com.android.support:recyclerview-v7:22.2.0'
compile 'com.android.support:recyclerview-v7:22.1.1'
compile 'com.android.support:recyclerview-v7:22.1.0'
compile 'com.android.support:recyclerview-v7:22.0.0'
//it requires compileSdkVersion 21
compile 'com.android.support:recyclerview-v7:21.0.3'
compile 'com.android.support:recyclerview-v7:21.0.2'
compile 'com.android.support:recyclerview-v7:21.0.0'
```
Of course you can still use **Eclipse** but it will requires some manual operations.
You can find all the release of the support libraries library in this folder:
```
sdk/extras/android/m2repository/com/android/support/
```
Here you can check all version.
In the folders you will find the `aar` file of the support libraries.
Inside you can check the `classes.jar` file,the res folder and the AndroidManifest file.
* Create a project in your workspace
* Unzip the AAR into some directory.
* Copy the `AndroidManifest.xml`, the `res`, and `assets` folders from the AAR into your project.
* Create a `libs` directory in your project and copy into it the `classes.jar`
* Add the dependency.
* Use the SDK 23 to compile
* Mark the project as a library
The **Recyclerview** library has the `support-v4.jar` and the support-`annotations-23.x.X.jar` as dependencies. | ***ECLIPSE***
If your problem is not solved or for future readers , here is the answer: From android sdk manager download Android Support Library first.
Go to this location and copy .aar file from here
X:\android-sdk\extras\android\m2repository\com\android\support\recyclerview-v7\21.0.0
Then rename it as .zip file then unZIP it then find classes.jar file , rename it with some proper name like 'RecyclerView\_v7.jar' Then copy the that .jar file in you project library. Add it to build path then restart eclipse so that it can be instantiated (not necessary but i had to do this).
```
**=================================Update=======================**
```
After new Library Updates; RecyclerView,CardView etc are available as simple library projects.! :)
**File**~>**Import**~>**Existing Android Code**~>**SDKpath**~>**extras**~>**android**~>**support**~>
**v7**~>**recyclerView**.
Then right click on this project , go to properties under **Android** check **Is Library**. It is done ..!
Now open your app in which you want to use recyclerView.
goto properties of your app Project under **Android** add Library here you will find that Library project add that (remember don't make your app a library project by checking 'Is Library'), now go to your App Project's
**Properties**~>**Java Build Path**~>**Libraries**~>**Add Jars**~>**RecyclerView LibraryProject**~>**libs**
Then add that jar into your project and buildpath .! Pheeew.. :) |