qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
50,984,161
I have two arrays with values. I am trying to get `desiredArray` which should check `firstArray` values in `secondArray` and if its a match, it should add the numbers of those value associated with them and push it to `desiredArray`. Could any one help? ```js firstArray = ["Jack Sparrow", "Ryan Gosling", "Peter Parker", "Mark Waugh", "Steve Jobs"] secondArray = ["Jack Sparrow :10", "Ryan Gosling :40", "Peter Parker :30", "Mark Warner: 40", "Shane Warne :30", "Steve Jobs : 20", "Tony Stark :90", "Adam Gilchrist: 45.5"] desiredArray = [100] //final answer here function getCount(firstArray, secondArray) { firstArray.forEach((e1) => secondArray.forEach((e2) => { if (e1 === e2.split(":")[0].trim()) { desiredArray.push(e1) } })); return desiredArray; console.log(desiredArray); } ```
2018/06/22
[ "https://Stackoverflow.com/questions/50984161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9891009/" ]
Simple way you may try this. ``` //Define query string in route Route::get('admin/invoice/{id}','ControllerName@show') //Get `id` in show function public function show(Invoice $invoice,$id) { $invoice_id = $id; } ```
Try using `$invoiceId` ``` public function show(Invoice $invoice, $invoiceId) { $clients = Invoice::with('user','products')->get(); $invoices = Invoice::with('products')->findOrFail($invoiceId); return view('admin.invoices.show', compact('invoice','invoices'),compact('clients')); } ```
50,984,161
I have two arrays with values. I am trying to get `desiredArray` which should check `firstArray` values in `secondArray` and if its a match, it should add the numbers of those value associated with them and push it to `desiredArray`. Could any one help? ```js firstArray = ["Jack Sparrow", "Ryan Gosling", "Peter Parker", "Mark Waugh", "Steve Jobs"] secondArray = ["Jack Sparrow :10", "Ryan Gosling :40", "Peter Parker :30", "Mark Warner: 40", "Shane Warne :30", "Steve Jobs : 20", "Tony Stark :90", "Adam Gilchrist: 45.5"] desiredArray = [100] //final answer here function getCount(firstArray, secondArray) { firstArray.forEach((e1) => secondArray.forEach((e2) => { if (e1 === e2.split(":")[0].trim()) { desiredArray.push(e1) } })); return desiredArray; console.log(desiredArray); } ```
2018/06/22
[ "https://Stackoverflow.com/questions/50984161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9891009/" ]
Simple way you may try this. ``` //Define query string in route Route::get('admin/invoice/{id}','ControllerName@show') //Get `id` in show function public function show(Invoice $invoice,$id) { $invoice_id = $id; } ```
do this if you want to get the url segment in controller. ``` $invoice_id = request()->segment(3); ``` if you want this in view ``` {{ Request::segment(3) }} ``` Goodluck!
50,984,161
I have two arrays with values. I am trying to get `desiredArray` which should check `firstArray` values in `secondArray` and if its a match, it should add the numbers of those value associated with them and push it to `desiredArray`. Could any one help? ```js firstArray = ["Jack Sparrow", "Ryan Gosling", "Peter Parker", "Mark Waugh", "Steve Jobs"] secondArray = ["Jack Sparrow :10", "Ryan Gosling :40", "Peter Parker :30", "Mark Warner: 40", "Shane Warne :30", "Steve Jobs : 20", "Tony Stark :90", "Adam Gilchrist: 45.5"] desiredArray = [100] //final answer here function getCount(firstArray, secondArray) { firstArray.forEach((e1) => secondArray.forEach((e2) => { if (e1 === e2.split(":")[0].trim()) { desiredArray.push(e1) } })); return desiredArray; console.log(desiredArray); } ```
2018/06/22
[ "https://Stackoverflow.com/questions/50984161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9891009/" ]
Simple way you may try this. ``` //Define query string in route Route::get('admin/invoice/{id}','ControllerName@show') //Get `id` in show function public function show(Invoice $invoice,$id) { $invoice_id = $id; } ```
Usually happens when giving a route name different from the controller name Example: ``` Route::resource('xyzs', 'AbcController'); ``` Expected: ``` Route::resource('abcs', 'AbcController'); ```
644,187
Here's how I started: $$\int\frac{\sin{(2x)}}{1+\cos^2 x} dx = -2\int\frac{-\sin x\cos x}{1+\cos^2 x} dx = -2\int \frac{u}{1+u^2}du $$ I know the answer ends up being this from here: $$ -\ln\left(1+\cos^2 x\right) $$ But I don't understand where this u in the numerator goes, it seems like the answer should look like this: $$-2\cdot\frac{1}{2}\cdot u^2\cdot\ln\left(1+u^2\right) = -\cos^2 x \cdot \ln\left(1+\cos^2 x\right) $$ Thanks!
2014/01/19
[ "https://math.stackexchange.com/questions/644187", "https://math.stackexchange.com", "https://math.stackexchange.com/users/66171/" ]
No substitution at all needed. Just a little trigonometry and some basic integration rules: $$(\cos^2x)'=-2\sin x\cos x\;\;,\;\;\sin 2x=2\sin x\cos x$$ so $$\int\frac{\sin 2x}{1+\cos^2x}dx=-\int\frac{-2\sin x\cos x}{1+\cos^2x}dx$$ and now you may want to use the general rule $$\int\frac{f'(x)}{f(x)}dx=\log f(x)+C$$
Make the substitution $u=1+\cos^2x$. Then $du= -2\sin x\cos x=-\sin 2x$, so the integral becomes $$- \int \frac{du}{u} = -\ln(1+\cos^2x) + C. $$
99,437
I'm a Ph.D. graduate in biotechnology/molecular biology, who is actively seeking a post-doctoral position at a US or Europe-based institute. I'm neither from US, nor from Europe. Thus, I believe, my chances of getting a postdoc position is slightly harder, compared to some others. My Ph.D. supervisor was very strict in allowing Ph.D. students graduate, only after at least 3 different projects have been completed. My first project was completed long time ago and its paper was published at a high-impact journal. However, my second paper was rejected by an editor, thus we recently divided it into 2 sections and submitted them to average-impact journals. They are under review right now. The 3rd project's paper will be submitted in 2 weeks. I've contacted many well-known professors in my field, and they do respond to my e-mail, mostly saying they are interested in accepting me in their group, only if I can secure my own funding. Or, they say they are waiting for a grant to come up. But, every e-mail I get from them sounds very familiar to each other. They either have no new grant, or would like me to have my own funding. A PI I know recently told me, my chances were extremely low if I did't have at least 4 published papers. I've got 1 published, but 2 "under review" articles, and I'm the first-author of all. Do you agree with this PI? Should I wait until I get to reach to the level of having 4 published papers, which might happen after 6 months or something. Or, do you think papers "under review" are nearly as impactful as papers "published"?
2017/11/26
[ "https://academia.stackexchange.com/questions/99437", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/79355/" ]
In the UK and Scandinavia at least, provided you show that those papers are in review you should be ok except for very highly competitive labs. The 'well-known professors' are most likely to be running those kinds of labs BUT you may well still get in if you are experienced in a topic or technique they are looking for. I honestly doubt the professors are lying or trying to brush you off; nearly all postdoc positions only come up when project funding comes through. Bear in mind that the professors are probably answering several such emails a week so they do indeed keep a 'stock' reply and that is fair enough. So don't wait for your publications to happen but look for advertised positions in your specialism and/or with your skillset named. Good websites are [jobs.ac.uk](http://www.jobs.ac.uk/) and [Euraxess](https://euraxess.ec.europa.eu/jobs). Side note: I am aware that candidates from not-USA-or-Europe often get a harder time which is regrettable. My answer stands but I wanted to acknowledge that you do have it tough.
> > Do you agree with this PI? Should I wait until I get to reach to the > level of having 4 published papers, which might happen after 6 months > or something. Or, do you think papers "under review" are nearly as > impactful as papers "published"? > > > They're not nearly as impactful because *they're not published*. There's no promise that a paper under review will be published, or in a particularly impressive venue. That being said, I personally don't have a mental threshold for the exact number of papers I expect a postdoc to have - the content of them is considerably more important than just volume. > > I've contacted many well-known professors in my field, and they do > respond to my e-mail, mostly saying they are interested in accepting > me in their group, only if I can secure my own funding. Or, they say > they are waiting for a grant to come up. > > > But, every e-mail I get from them sounds very familiar to each other. > They either have no new grant, or would like me to have my own > funding. > > > Honestly, this is the answer I would give you. I don't have free postdoc slots floating around in my lab - either I have funding for one, at which point I need them filled to do the work proposed in the grant, or I don't have one. Which means either a new grant needs to come in, or you need your own money - I can't simply conjure several tens of thousands of dollars out of thin air.
4,076,952
I have the following tables: ``` Product(ProductID, ProductName ...) ProductBidHistory(ProductID, UserID, Amount, Status, ...) ``` The BidHistory table can grow to have many records for every product, I want a report containing approved bid for every products i.e.Amount where status = approved. * Is it ok to have an ApprovedAmount column in the Product table itself that gets populated when the bid is closed, so that it is easier for reporting. * Should the report be written to do a join to history table to look for 'approved' and fetch the amount. Is it ok to duplicate the column ?
2010/11/02
[ "https://Stackoverflow.com/questions/4076952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/477489/" ]
From the pure design perspective, you shouldn't keep two copies of the same data. This could lead to data inconsistency. What if the approved amount and the bid history do not agree? From the performance perspective, you may duplicate the data to gain the speedup in the generation of the report. From the application perspective, the developer has to ensure the proper update is done to the approved amount in Product table with every update in the Bid History table.
This realy depends on the size of these tables. If they are not to large, I would recomend that you not duplicate the columns, as this will cause more overhead in the application layer. A simple view or user defined table function should be good enough. Also ensure that you have indexes on the correct columns. But if the tables are going to be very large (millions of rows), then you might see performance gains by storing the values for reporting purposes.
4,076,952
I have the following tables: ``` Product(ProductID, ProductName ...) ProductBidHistory(ProductID, UserID, Amount, Status, ...) ``` The BidHistory table can grow to have many records for every product, I want a report containing approved bid for every products i.e.Amount where status = approved. * Is it ok to have an ApprovedAmount column in the Product table itself that gets populated when the bid is closed, so that it is easier for reporting. * Should the report be written to do a join to history table to look for 'approved' and fetch the amount. Is it ok to duplicate the column ?
2010/11/02
[ "https://Stackoverflow.com/questions/4076952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/477489/" ]
From the pure design perspective, you shouldn't keep two copies of the same data. This could lead to data inconsistency. What if the approved amount and the bid history do not agree? From the performance perspective, you may duplicate the data to gain the speedup in the generation of the report. From the application perspective, the developer has to ensure the proper update is done to the approved amount in Product table with every update in the Bid History table.
In general, you should never duplicate the columns in a relational database, so that it would be possible to get answers that do not jibe with each other depending upon how the (valid) queries were expressed. Approved is not an attribute of the product but an attribute of the bid, and you should always try to have the database structure mirror the real-world ontology. Of course, you could not put Approved yes/no (boolean) column in the Product table if the rows in that table do not refer to a specific product in someone's possession (e.g. iPad 16G S/N 123456789) but to a generic "catalog description" product (e.g. iPad 16G) and could appear in multiple auctions. Not clear from your simplified design for the purpose of asking the question what you had in mind here. In your queries, you're never going to ask simply for "all approved bids" with no other qualifiers. The term "approved=true" will always be in league with some other term(s), e.g. bid-date after ?, or product id = ?, or product-category in (a, b, c) which are likely candidate columns for indices. So use indices judiciously, don't violate the normalization rules, keep your ontology real, and your database will take care of you.
39,889,656
I have this javascript code attached that puts some content into a popup window and then tries to print it: ``` $(".print_friendly_popup").click(function() { var target = $(this).data('print-target'); var left = (screen.width/2)-(500/2); var top = (screen.height/2)-(500/2); var win = window.open("", "test", "width=500,height=500 top=" + top + ", left=" + left); if(target == 'review') { win.document.write($('#print_friendly_review').html()); } else if(target == 'essay') { win.document.write($('#print_friendly_essay').html()); } win.print(); win.close(); }); ``` The problem is sometimes the call to win.document.write takes too long and the window tries to print a blank screen. How do I wait for window.document to be written to before firing print?
2016/10/06
[ "https://Stackoverflow.com/questions/39889656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/795374/" ]
So how about this: create some sort of "checker" to see if the window has the content in it, for example: ``` var checkForContent = function () { setTimeout(function () { var content = win.document.querySelector('body').innerHTML if (content.length) { win.print() win.close() } else { checkForContent() } }, 200) } ``` This way you're politely waiting for the content to render before printing.
Try ``` win.onload = function(e){ //..... your codes } ```
74,652,858
my code goes through quite a large number of arrays where everything is sorted so that it is in the right place. It flies 3 times through the input data to sort everything well, which causes empty arrays to appear. I try to delete them with the following code, but in some cases the code leaves me 1 empty array The following code works correctly in most cases, but in some cases 1 array is left undeleted ``` chartTypeData.forEach((item: any, index: any) => { if (item.length === 0) { chartTypeData.splice(index, 1); } }); ``` Full code: ``` for (let i = 0; i < chartType.length; i++) { const chartItem = chartsData?.product?.data[0].attributes.product_charts.data; for (let j = 0; j < chartCategory.length; j++) { for (let k = 0; k < country.length; k++) { chartTypeData.push( chartItem.filter((item: any) => { return ( item.attributes.type === chartType[i] && item.attributes.chartCategory === chartCategory[j] && item.attributes.country === country[k] ); }) ); } chartTypeData[i].sort((a: any, b: any) => { return new Date(a.attributes.date).getTime() - new Date(b.attributes.date).getTime(); }); } } chartTypeData.forEach((item: any, index: any) => { if (item.length === 0) { chartTypeData.splice(index, 1); } }); ```
2022/12/02
[ "https://Stackoverflow.com/questions/74652858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13613817/" ]
> > 1. Is it safe to signal a condition variable after it had been destroyed? > > > No. [Its docs](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_destroy.html) say: > > A destroyed condition variable object can be reinitialized using > `pthread_cond_init()`; **the results of otherwise referencing the object > after it has been destroyed are undefined**. > > > (emphasis added). --- > > 2. Is it safe to unlock a mutex after it had been destroyed? > > > No. [It's docs](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_destroy.html) say: > > A destroyed mutex object can be reinitialized using > `pthread_mutex_init()`; **the results of otherwise referencing the > object after it has been destroyed are undefined**. > > > (emphasis added). --- > > 3. Are there similar guarantees on other threading APIs (such as C11 > Threads and C++ Threads)? > > > About using synchronization objects after they have been destroyed? No. Why would there be? These sorts of APIs are for releasing resources. If the synchronization objects rely on resources that require cleanup in the first place, then how does it make sense that they could still function once those resources are released? Generally speaking, then, before you can tear down synchronization objects such as mutexes and condition variables, you need to ensure that there are no circumstances under which any current thread could attempt to access them again. At least, not until after they have been re-initialized (in a framework where that is even possible). Under some circumstances it is reasonable simply not to tear them down at all. Otherwise, you need to be more creative.
This is not safe. Destroy will destroy any shared memory used by these objects. The solution to your problem is to `join` all the threads that are using your your mutexes and cond-vars (except one) and only then destroy them.
15,025,040
I understand that when linking against a static library i.e. libname.a, the binary code for the used functions is taken out of the archive and *inserted* in the application binary. Therefore, the static library MUST be present at compilation time. However, with shared libraries I am lost. The function definitions are not copied. Then **why is it needed that the shared library be provided on the linker command line**? Also, **are there different ways to link against shared libraries** and what are they?
2013/02/22
[ "https://Stackoverflow.com/questions/15025040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1145760/" ]
The shared libraries need to be fed to the linker's command line so that a reference to the specific functions and the file in which these functions reside, is stored into the executable. When the executable is run, the dynamic linker (`/lib/ld-linux.so`, `/libexec/ld-elf.so`, etc, depending on your system) is loaded first and checks these references. Once it finds the lib files, it maps them (using the `mmap()` system call) to your program's adress space. You can see these references by running ``` objdump -T a.out ``` or ``` nm -D a.out ``` For ELF executables, the existence of the `.interp` section implies that the program uses dynamic linking.
See the man pages for **dlopen** and **dlsym** for explicit dynamic link loader management.
35,789,283
I am working on iOS project and sending the Json string to backend through wcf webservice, Its working successfully for many users but for some users backend getting incomplete json string. Code for generating Json string ``` NSData *data = [NSJSONSerialization dataWithJSONObject:EmployeeDetails options:0 error:nil]; NSString *JsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; ``` And Attaching the json string with request by below code ``` [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]]; ``` EmployeeDetails is NSMutableDictionary with employee details. And Here is successful Json string deserialized from BackEnd ``` {"FirstName":"Donald","LastCBPaymentType":6,"AcceptEmail":true,"CellPhone":"321-300-6874","Position":"3","CarrierNum":"4","EmpNum":"96874"} ``` And Incomplete Json string ``` {"FirstName":"roset","LastCBPaymentType":6,"AcceptEmail":true,"CellPhone":"321-300-6874","Position":"3","CarrierNum":"4","EmpNum":"98799 ``` The incomplete json string occuring in backend for some user. Any one can help to solve this issue ?
2016/03/04
[ "https://Stackoverflow.com/questions/35789283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2024276/" ]
Well, I'd say [TomSwift](https://stackoverflow.com/a/39047833/6165597) is on the right track... It's apparent that the broken JSON is simply missing "} from the end of the string. That does indeed look like something being sanitised by a regex... You really should find the source of the problem; But for a quick and dirty fix *while you figure it out*, you could just run your own regex on the JSON you receive and if it doesn't end with a "}, just add it... First do something like: '/"[0-9]+$/' (to check if there is an open numeric string at the end, if there is, you close it by adding " ) then check if '/}$/' (if } is the last char, if it isn't: add it). Remember, the above would only be a temporary fix (as it is somewhat heavy and not really that pretty), but I could imagine myself being forced to do something like this, simply because of time constraints. If the issue is actually coming from within the API, you could tell the creators about it and use something like that fix above while they fixed it. PS. If anyone does choose to use a fix like the above, please please please, for the love of all that you hold holy, leave a comment in the code explaining **why you did it** (as opposed to telling us **what** you did...).
I had a similar problem in PHP/CodeIgniter recently and the problem was that the JSON was being "sanitized" via some overly ambitious regular expressions before it arrived to my handler. Perhaps there's some similar sanitization that happens in WCF? Things I would try: 1. Using [Charles Proxy](https://www.charlesproxy.com) to confirm that the request (POST?) is actually sending the full body as you expect. 2. Try Content-Type application/json instead.
12,640,728
I have one spinner in which I have set the value through an `Adapter`. The problem is that when the spinner is closed at that time it shows the text as perfectly readable with proper size. But when we click on spinner and show the text, that text shows me as not readable that means with cut text. This problem is only occurring on Galaxy Tab and Galaxy s3. Means with screen size high. So please can anybody help me to solve this problem? The screen shot of spinner is ![text cut in spinner](https://i.stack.imgur.com/WSI7N.jpg) and I want actually this ![correct spinner text](https://i.stack.imgur.com/hDnr9.png) The Spinner code in xml is ``` <Spinner android:id="@+id/ddCountry" android:layout_width="fill_parent" android:layout_height="wrap_content" /> ``` I have set the one style to set the textcolor to black, and the code is like this ``` <?xml version="1.0" encoding="utf-8"?> <resources> <style name="Theme.NoTitleBar.WithColoredSpinners" parent="@android:style/Theme.NoTitleBar"> <item name="android:spinnerItemStyle">@style/SpinnerItem</item> <item name="android:spinnerDropDownItemStyle">@style/SpinnerItem.DropDownItem</item> </style> <style name="SpinnerItem" parent="@android:style/Widget.TextView.SpinnerItem"> <item name="android:textColor">#000000</item> </style> <style name="SpinnerItem.DropDownItem" parent="@android:style/Widget.DropDownItem.Spinner"> <item name="android:textColor">#000000</item> </style> </resources> ``` The code for fillup the value in spinner is like this: ``` ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>( Registration.this, android.R.layout.simple_spinner_item, list); dataAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner1.setAdapter(dataAdapter); ``` This code is working in most of devices, but the problem comes when screen size is high like Galaxy Tab.
2012/09/28
[ "https://Stackoverflow.com/questions/12640728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1468193/" ]
try the following code: ``` <Spinner android:id="@+id/ddCountry" android:layout_width="fill_parent" android:layout_height="20dp" /> ``` try to change the layout\_height as want to fit ur spinner
Set `android:layout_height="wrap_content"`
12,640,728
I have one spinner in which I have set the value through an `Adapter`. The problem is that when the spinner is closed at that time it shows the text as perfectly readable with proper size. But when we click on spinner and show the text, that text shows me as not readable that means with cut text. This problem is only occurring on Galaxy Tab and Galaxy s3. Means with screen size high. So please can anybody help me to solve this problem? The screen shot of spinner is ![text cut in spinner](https://i.stack.imgur.com/WSI7N.jpg) and I want actually this ![correct spinner text](https://i.stack.imgur.com/hDnr9.png) The Spinner code in xml is ``` <Spinner android:id="@+id/ddCountry" android:layout_width="fill_parent" android:layout_height="wrap_content" /> ``` I have set the one style to set the textcolor to black, and the code is like this ``` <?xml version="1.0" encoding="utf-8"?> <resources> <style name="Theme.NoTitleBar.WithColoredSpinners" parent="@android:style/Theme.NoTitleBar"> <item name="android:spinnerItemStyle">@style/SpinnerItem</item> <item name="android:spinnerDropDownItemStyle">@style/SpinnerItem.DropDownItem</item> </style> <style name="SpinnerItem" parent="@android:style/Widget.TextView.SpinnerItem"> <item name="android:textColor">#000000</item> </style> <style name="SpinnerItem.DropDownItem" parent="@android:style/Widget.DropDownItem.Spinner"> <item name="android:textColor">#000000</item> </style> </resources> ``` The code for fillup the value in spinner is like this: ``` ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>( Registration.this, android.R.layout.simple_spinner_item, list); dataAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner1.setAdapter(dataAdapter); ``` This code is working in most of devices, but the problem comes when screen size is high like Galaxy Tab.
2012/09/28
[ "https://Stackoverflow.com/questions/12640728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1468193/" ]
try the following code: ``` <Spinner android:id="@+id/ddCountry" android:layout_width="fill_parent" android:layout_height="20dp" /> ``` try to change the layout\_height as want to fit ur spinner
The problem is obviously in your dropdown layout. Rather than using the stock drop-down layout of `android.R.layout.simple_spinner_dropdown_item` (which Samsung may have modified for their devices), create your own and set the text size to match the closed spinner. This could be as simple as copying the default to your layout directory, changing the name and tweaking the layout itself by adding/changing the text size.
12,640,728
I have one spinner in which I have set the value through an `Adapter`. The problem is that when the spinner is closed at that time it shows the text as perfectly readable with proper size. But when we click on spinner and show the text, that text shows me as not readable that means with cut text. This problem is only occurring on Galaxy Tab and Galaxy s3. Means with screen size high. So please can anybody help me to solve this problem? The screen shot of spinner is ![text cut in spinner](https://i.stack.imgur.com/WSI7N.jpg) and I want actually this ![correct spinner text](https://i.stack.imgur.com/hDnr9.png) The Spinner code in xml is ``` <Spinner android:id="@+id/ddCountry" android:layout_width="fill_parent" android:layout_height="wrap_content" /> ``` I have set the one style to set the textcolor to black, and the code is like this ``` <?xml version="1.0" encoding="utf-8"?> <resources> <style name="Theme.NoTitleBar.WithColoredSpinners" parent="@android:style/Theme.NoTitleBar"> <item name="android:spinnerItemStyle">@style/SpinnerItem</item> <item name="android:spinnerDropDownItemStyle">@style/SpinnerItem.DropDownItem</item> </style> <style name="SpinnerItem" parent="@android:style/Widget.TextView.SpinnerItem"> <item name="android:textColor">#000000</item> </style> <style name="SpinnerItem.DropDownItem" parent="@android:style/Widget.DropDownItem.Spinner"> <item name="android:textColor">#000000</item> </style> </resources> ``` The code for fillup the value in spinner is like this: ``` ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>( Registration.this, android.R.layout.simple_spinner_item, list); dataAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner1.setAdapter(dataAdapter); ``` This code is working in most of devices, but the problem comes when screen size is high like Galaxy Tab.
2012/09/28
[ "https://Stackoverflow.com/questions/12640728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1468193/" ]
I got the solution.Its my mistake that i had set the `android:anyDensity="false"`.So it was not working in Galaxy tab.
Set `android:layout_height="wrap_content"`
12,640,728
I have one spinner in which I have set the value through an `Adapter`. The problem is that when the spinner is closed at that time it shows the text as perfectly readable with proper size. But when we click on spinner and show the text, that text shows me as not readable that means with cut text. This problem is only occurring on Galaxy Tab and Galaxy s3. Means with screen size high. So please can anybody help me to solve this problem? The screen shot of spinner is ![text cut in spinner](https://i.stack.imgur.com/WSI7N.jpg) and I want actually this ![correct spinner text](https://i.stack.imgur.com/hDnr9.png) The Spinner code in xml is ``` <Spinner android:id="@+id/ddCountry" android:layout_width="fill_parent" android:layout_height="wrap_content" /> ``` I have set the one style to set the textcolor to black, and the code is like this ``` <?xml version="1.0" encoding="utf-8"?> <resources> <style name="Theme.NoTitleBar.WithColoredSpinners" parent="@android:style/Theme.NoTitleBar"> <item name="android:spinnerItemStyle">@style/SpinnerItem</item> <item name="android:spinnerDropDownItemStyle">@style/SpinnerItem.DropDownItem</item> </style> <style name="SpinnerItem" parent="@android:style/Widget.TextView.SpinnerItem"> <item name="android:textColor">#000000</item> </style> <style name="SpinnerItem.DropDownItem" parent="@android:style/Widget.DropDownItem.Spinner"> <item name="android:textColor">#000000</item> </style> </resources> ``` The code for fillup the value in spinner is like this: ``` ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>( Registration.this, android.R.layout.simple_spinner_item, list); dataAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner1.setAdapter(dataAdapter); ``` This code is working in most of devices, but the problem comes when screen size is high like Galaxy Tab.
2012/09/28
[ "https://Stackoverflow.com/questions/12640728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1468193/" ]
I got the solution.Its my mistake that i had set the `android:anyDensity="false"`.So it was not working in Galaxy tab.
The problem is obviously in your dropdown layout. Rather than using the stock drop-down layout of `android.R.layout.simple_spinner_dropdown_item` (which Samsung may have modified for their devices), create your own and set the text size to match the closed spinner. This could be as simple as copying the default to your layout directory, changing the name and tweaking the layout itself by adding/changing the text size.
52,318,634
I've created a script that loops through a bunch of folders and processes them each in to webpack bundles. This works great, except that I can't figure out why the `Promise` around the loop isn't resolving. Some things I've tried: * If I put a `console.log("hello world")` just before `resolve()`, within the `} else { ... }`, it outputs the log. * If I move `resolve()` out of the `} else { ... }`, it resolves, but the rest of my gulp task doesn't continue (separate, but related, issue). I would appreciate some help in figuring this out. Most relevant chunk of code is below, the rest of it's at the link below. ``` // process all the script folders const process_script_folders = () => { return new Promise((resolve) => { const FOLDER = script_folders.shift(); // lint all scripts, except for critical if (FOLDER !== "critical") { const linted = lint_scripts(js_directory, FOLDER + ".js", source_directory + "/" + FOLDER + "/**/*"); merged_streams.add(linted); } process_scripts(js_directory, FOLDER + ".js", source_directory + "/" + FOLDER + "/**/*").then((processed) => { merged_streams.add(processed); if (script_folders.length > 0) { process_script_folders(); } else { // @TODO figure out why this isn't resolving resolve(); } }); }); }; return process_script_folders().then(() => { // ... do stuff console.log("Testing"); // currently never output }); ``` <https://github.com/JacobDB/new-site/blob/dfeeb3260ab1b314e7562ef313c181adf2ef7f9c/gulp-tasks/scripts.js#L86-L89>
2018/09/13
[ "https://Stackoverflow.com/questions/52318634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654480/" ]
You are recursively calling your promise, but none of these promises will resolve aside from the last one because you have put your resolve inside of your resolve clause. I think if you put the resolve outside of else and keep the rest the same it should resolve after finishing the recursion. ``` if (script_folders.length > 0) { process_script_folders(); } resolve(); ``` Could you try it like that? EDIT: @Bergi is right. Doing it like the following should have it working properly I think. First a trivial example of what I'm suggesting you do: ```js let i = 0 const example_processing = () => { return new Promise((resolve) => { i++ setTimeout(resolve, 1000); }).then(() => { console.log(i); return i < 10 ? example_processing() : "done" }); }; example_processing().then(console.log); ``` With regards to your code it would look more like this I guess: ``` const process_script_folders = () => { return new Promise((resolve) => { const FOLDER = script_folders.shift(); // lint all scripts, except for critical if (FOLDER !== "critical") { const linted = lint_scripts(js_directory, FOLDER + ".js", source_directory + "/" + FOLDER + "/**/*"); merged_streams.add(linted); } process_scripts(js_directory, FOLDER + ".js", source_directory + "/" + FOLDER + "/**/*").then((processed) => { merged_streams.add(processed); resolve(); }); }).then(() => script_folder.length > 0 ? process_script_folders() : "done"); }; ```
I think the issue has to do with the way you are making the recursive call. Try making it ``` if (script_folders.length > 0) { process_script_folders().then(resolve); } else { resolve(); } ```
9,812,067
I have an application thats main goal is to play a specific video file. it plays the video correctly sometimes. But other times it gives me this error: ``` 03-21 14:52:36.181: I/AwesomePlayer(119): setDataSource_l('/data/data/my.package.name/files/MyMovie.mp4') 03-21 14:52:36.196: W/VideoView(26612): Unable to open content: /data/data/my.package.name/files/MyMovie.mp4 03-21 14:52:36.196: W/VideoView(26612): java.lang.IllegalArgumentException: The surface has been released 03-21 14:52:36.196: W/VideoView(26612): at android.media.MediaPlayer._setVideoSurface(Native Method) 03-21 14:52:36.196: W/VideoView(26612): at android.media.MediaPlayer.setDisplay(MediaPlayer.java:633) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView.openVideo(VideoView.java:222) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView.access$2000(VideoView.java:49) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView$6.surfaceCreated(VideoView.java:465) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView.updateWindow(SurfaceView.java:533) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView.access$000(SurfaceView.java:81) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:169) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:590) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1617) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2442) 03-21 14:52:36.196: W/VideoView(26612): at android.os.Handler.dispatchMessage(Handler.java:99) 03-21 14:52:36.196: W/VideoView(26612): at android.os.Looper.loop(Looper.java:137) 03-21 14:52:36.196: W/VideoView(26612): at android.app.ActivityThread.main(ActivityThread.java:4424) 03-21 14:52:36.196: W/VideoView(26612): at java.lang.reflect.Method.invokeNative(Native Method) 03-21 14:52:36.196: W/VideoView(26612): at java.lang.reflect.Method.invoke(Method.java:511) 03-21 14:52:36.196: W/VideoView(26612): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 03-21 14:52:36.196: W/VideoView(26612): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 03-21 14:52:36.196: W/VideoView(26612): at dalvik.system.NativeStart.main(Native Method) 03-21 14:52:36.196: D/VideoView(26612): Error: 1,0 ``` I am using the prepared listener to call start like this: ``` mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer arg0) { mVideoView.start(); } }); ``` And I set the data source with this: ``` file = new File(this.getFilesDir() + File.separator + VIDEO_FILE_NAME); mVideoView.setVideoPath(file.getAbsolutePath()); ``` I know for certain that the file does exist and is the proper format. My application has the ability to be launched from an alarm trigger. It seems to only be a problem when the trigger fires and launches my app while the devices screen is turned off(my app will turn the screen on with a wake lock). If I manually launch the app, or the trigger happens with the screen on the video plays fine. This error is also only occuring on the Galaxy Nexus. I can run the exact same code on a Nexus S(as well as a long list of others) and it starts fine every time. Does anyone know of anything specific to the Galaxy Nexus or ICS that could cause this behavior? And are there any suggestions for what I could try to fix?
2012/03/21
[ "https://Stackoverflow.com/questions/9812067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/507810/" ]
UThis is connected to your SurfaceView. Make sure you don't touch the SurfaceView after you have called prepare on you MediaPlayer and that it is visible. In your case where you try to wake up the screen make sure that everything happens in the correct order. So preparing the MediaPlayer for playback is the very last thing which your app should do. It could be that the prepare/playback is initiated prior to the app being fully awake, causing the app to attempt to manipulate the SurfaceView. The follow code example illustrates how to trigger that kind of exception: ``` private void setupVideo(String file){ ... mSurfaceView = (SurfaceView) findViewById(R.id.surface); mHolder = mSurfaceView.getHolder(); // DON'T TOUCH BEHIND THIS POINT mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mMediaPlayer.setDisplay(mHolder); mMediaPlayer.setOnPreparedListener(this); mMediaPlayer.prepare(); } @Override public void onPrepared(final MediaPlayer mp) { mSurfaceView.setVisibility(View.VISIBLE); // THIS WILL CAUSE THE ERROR mp.start(); } ```
I got around this issue with the below implementation. ``` @Override protected void onPause() { Log.v("MediaVideo", "onPause"); super.onPause(); this.mVideoView.pause(); this.mVideoView.setVisibility(View.GONE); } @Override protected void onDestroy() { Log.v("MediaVideo", "onDestroy"); super.onDestroy(); } @Override protected void onResume() { Log.v("MediaVideo", "onResume"); super.onResume(); this.mVideoView.resume(); } ``` Override the OnPause and call mVideoView.pause() and the set visibility to GONE. This way I could resolve the "Activity has leaked window" log error issue.
9,812,067
I have an application thats main goal is to play a specific video file. it plays the video correctly sometimes. But other times it gives me this error: ``` 03-21 14:52:36.181: I/AwesomePlayer(119): setDataSource_l('/data/data/my.package.name/files/MyMovie.mp4') 03-21 14:52:36.196: W/VideoView(26612): Unable to open content: /data/data/my.package.name/files/MyMovie.mp4 03-21 14:52:36.196: W/VideoView(26612): java.lang.IllegalArgumentException: The surface has been released 03-21 14:52:36.196: W/VideoView(26612): at android.media.MediaPlayer._setVideoSurface(Native Method) 03-21 14:52:36.196: W/VideoView(26612): at android.media.MediaPlayer.setDisplay(MediaPlayer.java:633) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView.openVideo(VideoView.java:222) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView.access$2000(VideoView.java:49) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView$6.surfaceCreated(VideoView.java:465) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView.updateWindow(SurfaceView.java:533) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView.access$000(SurfaceView.java:81) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:169) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:590) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1617) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2442) 03-21 14:52:36.196: W/VideoView(26612): at android.os.Handler.dispatchMessage(Handler.java:99) 03-21 14:52:36.196: W/VideoView(26612): at android.os.Looper.loop(Looper.java:137) 03-21 14:52:36.196: W/VideoView(26612): at android.app.ActivityThread.main(ActivityThread.java:4424) 03-21 14:52:36.196: W/VideoView(26612): at java.lang.reflect.Method.invokeNative(Native Method) 03-21 14:52:36.196: W/VideoView(26612): at java.lang.reflect.Method.invoke(Method.java:511) 03-21 14:52:36.196: W/VideoView(26612): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 03-21 14:52:36.196: W/VideoView(26612): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 03-21 14:52:36.196: W/VideoView(26612): at dalvik.system.NativeStart.main(Native Method) 03-21 14:52:36.196: D/VideoView(26612): Error: 1,0 ``` I am using the prepared listener to call start like this: ``` mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer arg0) { mVideoView.start(); } }); ``` And I set the data source with this: ``` file = new File(this.getFilesDir() + File.separator + VIDEO_FILE_NAME); mVideoView.setVideoPath(file.getAbsolutePath()); ``` I know for certain that the file does exist and is the proper format. My application has the ability to be launched from an alarm trigger. It seems to only be a problem when the trigger fires and launches my app while the devices screen is turned off(my app will turn the screen on with a wake lock). If I manually launch the app, or the trigger happens with the screen on the video plays fine. This error is also only occuring on the Galaxy Nexus. I can run the exact same code on a Nexus S(as well as a long list of others) and it starts fine every time. Does anyone know of anything specific to the Galaxy Nexus or ICS that could cause this behavior? And are there any suggestions for what I could try to fix?
2012/03/21
[ "https://Stackoverflow.com/questions/9812067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/507810/" ]
UThis is connected to your SurfaceView. Make sure you don't touch the SurfaceView after you have called prepare on you MediaPlayer and that it is visible. In your case where you try to wake up the screen make sure that everything happens in the correct order. So preparing the MediaPlayer for playback is the very last thing which your app should do. It could be that the prepare/playback is initiated prior to the app being fully awake, causing the app to attempt to manipulate the SurfaceView. The follow code example illustrates how to trigger that kind of exception: ``` private void setupVideo(String file){ ... mSurfaceView = (SurfaceView) findViewById(R.id.surface); mHolder = mSurfaceView.getHolder(); // DON'T TOUCH BEHIND THIS POINT mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mMediaPlayer.setDisplay(mHolder); mMediaPlayer.setOnPreparedListener(this); mMediaPlayer.prepare(); } @Override public void onPrepared(final MediaPlayer mp) { mSurfaceView.setVisibility(View.VISIBLE); // THIS WILL CAUSE THE ERROR mp.start(); } ```
Is your Galaxy Nexus by any chance rooted and running the Keyboard Manager app? I saw the exact same stack trace as you when testing my app out and kept noticing the following line in my logcat dumps: ``` 06-26 08:42:49.511 I/ActivityManager( 218): START {flg=0x10050000 cmp=com.ne0fhykLabs.android.utility.km/.TransitionDialog} from pid 11150 ``` This is the Keyboard Manager app kicking in as soon as the screen orientation changed. As soon as I disabled the Keyboard Manager service, everything started working again with my video. As far as I can tell, they were both using the same SurfaceHolder, and when Keyboard Manager was done with it, it was released, causing that exception when the VideoView tried to use it. In order to get around this, you could try what is mentioned [here](http://translate.google.com/translate?hl=en&sl=zh-CN&u=http://dingran.iteye.com/blog/1442502&prev=/search?q=IllegalArgumentException%2b%2522The%2bsurface%2bhas%2bbeen%2breleased%2522&hl=en&safe=off&client=firefox-a&rls=org.mozilla%3aen-US%3aofficial&biw=1600&bih=753&prmd=imvns&sa=X&ei=pyHrT8DGLZTW2wW-kYnYAQ&sqi=2&ved=0CGYQ7gEwAw) (the site is in Chinese, but the link is translated). I haven't tried it yet, but hopefully it will work since it's using its own dedicated SurfaceView.
9,812,067
I have an application thats main goal is to play a specific video file. it plays the video correctly sometimes. But other times it gives me this error: ``` 03-21 14:52:36.181: I/AwesomePlayer(119): setDataSource_l('/data/data/my.package.name/files/MyMovie.mp4') 03-21 14:52:36.196: W/VideoView(26612): Unable to open content: /data/data/my.package.name/files/MyMovie.mp4 03-21 14:52:36.196: W/VideoView(26612): java.lang.IllegalArgumentException: The surface has been released 03-21 14:52:36.196: W/VideoView(26612): at android.media.MediaPlayer._setVideoSurface(Native Method) 03-21 14:52:36.196: W/VideoView(26612): at android.media.MediaPlayer.setDisplay(MediaPlayer.java:633) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView.openVideo(VideoView.java:222) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView.access$2000(VideoView.java:49) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView$6.surfaceCreated(VideoView.java:465) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView.updateWindow(SurfaceView.java:533) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView.access$000(SurfaceView.java:81) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:169) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:590) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1617) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2442) 03-21 14:52:36.196: W/VideoView(26612): at android.os.Handler.dispatchMessage(Handler.java:99) 03-21 14:52:36.196: W/VideoView(26612): at android.os.Looper.loop(Looper.java:137) 03-21 14:52:36.196: W/VideoView(26612): at android.app.ActivityThread.main(ActivityThread.java:4424) 03-21 14:52:36.196: W/VideoView(26612): at java.lang.reflect.Method.invokeNative(Native Method) 03-21 14:52:36.196: W/VideoView(26612): at java.lang.reflect.Method.invoke(Method.java:511) 03-21 14:52:36.196: W/VideoView(26612): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 03-21 14:52:36.196: W/VideoView(26612): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 03-21 14:52:36.196: W/VideoView(26612): at dalvik.system.NativeStart.main(Native Method) 03-21 14:52:36.196: D/VideoView(26612): Error: 1,0 ``` I am using the prepared listener to call start like this: ``` mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer arg0) { mVideoView.start(); } }); ``` And I set the data source with this: ``` file = new File(this.getFilesDir() + File.separator + VIDEO_FILE_NAME); mVideoView.setVideoPath(file.getAbsolutePath()); ``` I know for certain that the file does exist and is the proper format. My application has the ability to be launched from an alarm trigger. It seems to only be a problem when the trigger fires and launches my app while the devices screen is turned off(my app will turn the screen on with a wake lock). If I manually launch the app, or the trigger happens with the screen on the video plays fine. This error is also only occuring on the Galaxy Nexus. I can run the exact same code on a Nexus S(as well as a long list of others) and it starts fine every time. Does anyone know of anything specific to the Galaxy Nexus or ICS that could cause this behavior? And are there any suggestions for what I could try to fix?
2012/03/21
[ "https://Stackoverflow.com/questions/9812067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/507810/" ]
UThis is connected to your SurfaceView. Make sure you don't touch the SurfaceView after you have called prepare on you MediaPlayer and that it is visible. In your case where you try to wake up the screen make sure that everything happens in the correct order. So preparing the MediaPlayer for playback is the very last thing which your app should do. It could be that the prepare/playback is initiated prior to the app being fully awake, causing the app to attempt to manipulate the SurfaceView. The follow code example illustrates how to trigger that kind of exception: ``` private void setupVideo(String file){ ... mSurfaceView = (SurfaceView) findViewById(R.id.surface); mHolder = mSurfaceView.getHolder(); // DON'T TOUCH BEHIND THIS POINT mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mMediaPlayer.setDisplay(mHolder); mMediaPlayer.setOnPreparedListener(this); mMediaPlayer.prepare(); } @Override public void onPrepared(final MediaPlayer mp) { mSurfaceView.setVisibility(View.VISIBLE); // THIS WILL CAUSE THE ERROR mp.start(); } ```
Overriding the `onpause` and `onresume` callbacks seemed to fix it for me and it's ONLY for the NEXUS Galaxy that has this problem.
9,812,067
I have an application thats main goal is to play a specific video file. it plays the video correctly sometimes. But other times it gives me this error: ``` 03-21 14:52:36.181: I/AwesomePlayer(119): setDataSource_l('/data/data/my.package.name/files/MyMovie.mp4') 03-21 14:52:36.196: W/VideoView(26612): Unable to open content: /data/data/my.package.name/files/MyMovie.mp4 03-21 14:52:36.196: W/VideoView(26612): java.lang.IllegalArgumentException: The surface has been released 03-21 14:52:36.196: W/VideoView(26612): at android.media.MediaPlayer._setVideoSurface(Native Method) 03-21 14:52:36.196: W/VideoView(26612): at android.media.MediaPlayer.setDisplay(MediaPlayer.java:633) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView.openVideo(VideoView.java:222) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView.access$2000(VideoView.java:49) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView$6.surfaceCreated(VideoView.java:465) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView.updateWindow(SurfaceView.java:533) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView.access$000(SurfaceView.java:81) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:169) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:590) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1617) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2442) 03-21 14:52:36.196: W/VideoView(26612): at android.os.Handler.dispatchMessage(Handler.java:99) 03-21 14:52:36.196: W/VideoView(26612): at android.os.Looper.loop(Looper.java:137) 03-21 14:52:36.196: W/VideoView(26612): at android.app.ActivityThread.main(ActivityThread.java:4424) 03-21 14:52:36.196: W/VideoView(26612): at java.lang.reflect.Method.invokeNative(Native Method) 03-21 14:52:36.196: W/VideoView(26612): at java.lang.reflect.Method.invoke(Method.java:511) 03-21 14:52:36.196: W/VideoView(26612): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 03-21 14:52:36.196: W/VideoView(26612): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 03-21 14:52:36.196: W/VideoView(26612): at dalvik.system.NativeStart.main(Native Method) 03-21 14:52:36.196: D/VideoView(26612): Error: 1,0 ``` I am using the prepared listener to call start like this: ``` mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer arg0) { mVideoView.start(); } }); ``` And I set the data source with this: ``` file = new File(this.getFilesDir() + File.separator + VIDEO_FILE_NAME); mVideoView.setVideoPath(file.getAbsolutePath()); ``` I know for certain that the file does exist and is the proper format. My application has the ability to be launched from an alarm trigger. It seems to only be a problem when the trigger fires and launches my app while the devices screen is turned off(my app will turn the screen on with a wake lock). If I manually launch the app, or the trigger happens with the screen on the video plays fine. This error is also only occuring on the Galaxy Nexus. I can run the exact same code on a Nexus S(as well as a long list of others) and it starts fine every time. Does anyone know of anything specific to the Galaxy Nexus or ICS that could cause this behavior? And are there any suggestions for what I could try to fix?
2012/03/21
[ "https://Stackoverflow.com/questions/9812067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/507810/" ]
UThis is connected to your SurfaceView. Make sure you don't touch the SurfaceView after you have called prepare on you MediaPlayer and that it is visible. In your case where you try to wake up the screen make sure that everything happens in the correct order. So preparing the MediaPlayer for playback is the very last thing which your app should do. It could be that the prepare/playback is initiated prior to the app being fully awake, causing the app to attempt to manipulate the SurfaceView. The follow code example illustrates how to trigger that kind of exception: ``` private void setupVideo(String file){ ... mSurfaceView = (SurfaceView) findViewById(R.id.surface); mHolder = mSurfaceView.getHolder(); // DON'T TOUCH BEHIND THIS POINT mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mMediaPlayer.setDisplay(mHolder); mMediaPlayer.setOnPreparedListener(this); mMediaPlayer.prepare(); } @Override public void onPrepared(final MediaPlayer mp) { mSurfaceView.setVisibility(View.VISIBLE); // THIS WILL CAUSE THE ERROR mp.start(); } ```
I had the same problem with an ICS no name tablet. SurfaceHolder isn't created when setDisplay method is called, which cause: ``` 03-21 14:52:36.196: W/VideoView(26612): java.lang.IllegalArgumentException: The surface has been released ``` To fix it, I use: ``` private void setupVideo(String file){ ... mMediaPlayer.setOnPreparedListener(this); mHolder=mSurfaceView.getHolder(); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mHolder.setKeepScreenOn(true); mHolder.addCallback(new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder holder) { mHolder=holder; mMediaPlayer.setDisplay(mHolder); ... mMediaPlayer.prepare(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { ... } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { ... } }); } @Override public void onPrepared(final MediaPlayer mp) { ... mMediaPlayer.start(); } ```
9,812,067
I have an application thats main goal is to play a specific video file. it plays the video correctly sometimes. But other times it gives me this error: ``` 03-21 14:52:36.181: I/AwesomePlayer(119): setDataSource_l('/data/data/my.package.name/files/MyMovie.mp4') 03-21 14:52:36.196: W/VideoView(26612): Unable to open content: /data/data/my.package.name/files/MyMovie.mp4 03-21 14:52:36.196: W/VideoView(26612): java.lang.IllegalArgumentException: The surface has been released 03-21 14:52:36.196: W/VideoView(26612): at android.media.MediaPlayer._setVideoSurface(Native Method) 03-21 14:52:36.196: W/VideoView(26612): at android.media.MediaPlayer.setDisplay(MediaPlayer.java:633) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView.openVideo(VideoView.java:222) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView.access$2000(VideoView.java:49) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView$6.surfaceCreated(VideoView.java:465) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView.updateWindow(SurfaceView.java:533) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView.access$000(SurfaceView.java:81) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:169) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:590) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1617) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2442) 03-21 14:52:36.196: W/VideoView(26612): at android.os.Handler.dispatchMessage(Handler.java:99) 03-21 14:52:36.196: W/VideoView(26612): at android.os.Looper.loop(Looper.java:137) 03-21 14:52:36.196: W/VideoView(26612): at android.app.ActivityThread.main(ActivityThread.java:4424) 03-21 14:52:36.196: W/VideoView(26612): at java.lang.reflect.Method.invokeNative(Native Method) 03-21 14:52:36.196: W/VideoView(26612): at java.lang.reflect.Method.invoke(Method.java:511) 03-21 14:52:36.196: W/VideoView(26612): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 03-21 14:52:36.196: W/VideoView(26612): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 03-21 14:52:36.196: W/VideoView(26612): at dalvik.system.NativeStart.main(Native Method) 03-21 14:52:36.196: D/VideoView(26612): Error: 1,0 ``` I am using the prepared listener to call start like this: ``` mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer arg0) { mVideoView.start(); } }); ``` And I set the data source with this: ``` file = new File(this.getFilesDir() + File.separator + VIDEO_FILE_NAME); mVideoView.setVideoPath(file.getAbsolutePath()); ``` I know for certain that the file does exist and is the proper format. My application has the ability to be launched from an alarm trigger. It seems to only be a problem when the trigger fires and launches my app while the devices screen is turned off(my app will turn the screen on with a wake lock). If I manually launch the app, or the trigger happens with the screen on the video plays fine. This error is also only occuring on the Galaxy Nexus. I can run the exact same code on a Nexus S(as well as a long list of others) and it starts fine every time. Does anyone know of anything specific to the Galaxy Nexus or ICS that could cause this behavior? And are there any suggestions for what I could try to fix?
2012/03/21
[ "https://Stackoverflow.com/questions/9812067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/507810/" ]
I got around this issue with the below implementation. ``` @Override protected void onPause() { Log.v("MediaVideo", "onPause"); super.onPause(); this.mVideoView.pause(); this.mVideoView.setVisibility(View.GONE); } @Override protected void onDestroy() { Log.v("MediaVideo", "onDestroy"); super.onDestroy(); } @Override protected void onResume() { Log.v("MediaVideo", "onResume"); super.onResume(); this.mVideoView.resume(); } ``` Override the OnPause and call mVideoView.pause() and the set visibility to GONE. This way I could resolve the "Activity has leaked window" log error issue.
Is your Galaxy Nexus by any chance rooted and running the Keyboard Manager app? I saw the exact same stack trace as you when testing my app out and kept noticing the following line in my logcat dumps: ``` 06-26 08:42:49.511 I/ActivityManager( 218): START {flg=0x10050000 cmp=com.ne0fhykLabs.android.utility.km/.TransitionDialog} from pid 11150 ``` This is the Keyboard Manager app kicking in as soon as the screen orientation changed. As soon as I disabled the Keyboard Manager service, everything started working again with my video. As far as I can tell, they were both using the same SurfaceHolder, and when Keyboard Manager was done with it, it was released, causing that exception when the VideoView tried to use it. In order to get around this, you could try what is mentioned [here](http://translate.google.com/translate?hl=en&sl=zh-CN&u=http://dingran.iteye.com/blog/1442502&prev=/search?q=IllegalArgumentException%2b%2522The%2bsurface%2bhas%2bbeen%2breleased%2522&hl=en&safe=off&client=firefox-a&rls=org.mozilla%3aen-US%3aofficial&biw=1600&bih=753&prmd=imvns&sa=X&ei=pyHrT8DGLZTW2wW-kYnYAQ&sqi=2&ved=0CGYQ7gEwAw) (the site is in Chinese, but the link is translated). I haven't tried it yet, but hopefully it will work since it's using its own dedicated SurfaceView.
9,812,067
I have an application thats main goal is to play a specific video file. it plays the video correctly sometimes. But other times it gives me this error: ``` 03-21 14:52:36.181: I/AwesomePlayer(119): setDataSource_l('/data/data/my.package.name/files/MyMovie.mp4') 03-21 14:52:36.196: W/VideoView(26612): Unable to open content: /data/data/my.package.name/files/MyMovie.mp4 03-21 14:52:36.196: W/VideoView(26612): java.lang.IllegalArgumentException: The surface has been released 03-21 14:52:36.196: W/VideoView(26612): at android.media.MediaPlayer._setVideoSurface(Native Method) 03-21 14:52:36.196: W/VideoView(26612): at android.media.MediaPlayer.setDisplay(MediaPlayer.java:633) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView.openVideo(VideoView.java:222) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView.access$2000(VideoView.java:49) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView$6.surfaceCreated(VideoView.java:465) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView.updateWindow(SurfaceView.java:533) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView.access$000(SurfaceView.java:81) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:169) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:590) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1617) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2442) 03-21 14:52:36.196: W/VideoView(26612): at android.os.Handler.dispatchMessage(Handler.java:99) 03-21 14:52:36.196: W/VideoView(26612): at android.os.Looper.loop(Looper.java:137) 03-21 14:52:36.196: W/VideoView(26612): at android.app.ActivityThread.main(ActivityThread.java:4424) 03-21 14:52:36.196: W/VideoView(26612): at java.lang.reflect.Method.invokeNative(Native Method) 03-21 14:52:36.196: W/VideoView(26612): at java.lang.reflect.Method.invoke(Method.java:511) 03-21 14:52:36.196: W/VideoView(26612): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 03-21 14:52:36.196: W/VideoView(26612): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 03-21 14:52:36.196: W/VideoView(26612): at dalvik.system.NativeStart.main(Native Method) 03-21 14:52:36.196: D/VideoView(26612): Error: 1,0 ``` I am using the prepared listener to call start like this: ``` mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer arg0) { mVideoView.start(); } }); ``` And I set the data source with this: ``` file = new File(this.getFilesDir() + File.separator + VIDEO_FILE_NAME); mVideoView.setVideoPath(file.getAbsolutePath()); ``` I know for certain that the file does exist and is the proper format. My application has the ability to be launched from an alarm trigger. It seems to only be a problem when the trigger fires and launches my app while the devices screen is turned off(my app will turn the screen on with a wake lock). If I manually launch the app, or the trigger happens with the screen on the video plays fine. This error is also only occuring on the Galaxy Nexus. I can run the exact same code on a Nexus S(as well as a long list of others) and it starts fine every time. Does anyone know of anything specific to the Galaxy Nexus or ICS that could cause this behavior? And are there any suggestions for what I could try to fix?
2012/03/21
[ "https://Stackoverflow.com/questions/9812067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/507810/" ]
I got around this issue with the below implementation. ``` @Override protected void onPause() { Log.v("MediaVideo", "onPause"); super.onPause(); this.mVideoView.pause(); this.mVideoView.setVisibility(View.GONE); } @Override protected void onDestroy() { Log.v("MediaVideo", "onDestroy"); super.onDestroy(); } @Override protected void onResume() { Log.v("MediaVideo", "onResume"); super.onResume(); this.mVideoView.resume(); } ``` Override the OnPause and call mVideoView.pause() and the set visibility to GONE. This way I could resolve the "Activity has leaked window" log error issue.
Overriding the `onpause` and `onresume` callbacks seemed to fix it for me and it's ONLY for the NEXUS Galaxy that has this problem.
9,812,067
I have an application thats main goal is to play a specific video file. it plays the video correctly sometimes. But other times it gives me this error: ``` 03-21 14:52:36.181: I/AwesomePlayer(119): setDataSource_l('/data/data/my.package.name/files/MyMovie.mp4') 03-21 14:52:36.196: W/VideoView(26612): Unable to open content: /data/data/my.package.name/files/MyMovie.mp4 03-21 14:52:36.196: W/VideoView(26612): java.lang.IllegalArgumentException: The surface has been released 03-21 14:52:36.196: W/VideoView(26612): at android.media.MediaPlayer._setVideoSurface(Native Method) 03-21 14:52:36.196: W/VideoView(26612): at android.media.MediaPlayer.setDisplay(MediaPlayer.java:633) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView.openVideo(VideoView.java:222) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView.access$2000(VideoView.java:49) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView$6.surfaceCreated(VideoView.java:465) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView.updateWindow(SurfaceView.java:533) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView.access$000(SurfaceView.java:81) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:169) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:590) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1617) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2442) 03-21 14:52:36.196: W/VideoView(26612): at android.os.Handler.dispatchMessage(Handler.java:99) 03-21 14:52:36.196: W/VideoView(26612): at android.os.Looper.loop(Looper.java:137) 03-21 14:52:36.196: W/VideoView(26612): at android.app.ActivityThread.main(ActivityThread.java:4424) 03-21 14:52:36.196: W/VideoView(26612): at java.lang.reflect.Method.invokeNative(Native Method) 03-21 14:52:36.196: W/VideoView(26612): at java.lang.reflect.Method.invoke(Method.java:511) 03-21 14:52:36.196: W/VideoView(26612): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 03-21 14:52:36.196: W/VideoView(26612): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 03-21 14:52:36.196: W/VideoView(26612): at dalvik.system.NativeStart.main(Native Method) 03-21 14:52:36.196: D/VideoView(26612): Error: 1,0 ``` I am using the prepared listener to call start like this: ``` mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer arg0) { mVideoView.start(); } }); ``` And I set the data source with this: ``` file = new File(this.getFilesDir() + File.separator + VIDEO_FILE_NAME); mVideoView.setVideoPath(file.getAbsolutePath()); ``` I know for certain that the file does exist and is the proper format. My application has the ability to be launched from an alarm trigger. It seems to only be a problem when the trigger fires and launches my app while the devices screen is turned off(my app will turn the screen on with a wake lock). If I manually launch the app, or the trigger happens with the screen on the video plays fine. This error is also only occuring on the Galaxy Nexus. I can run the exact same code on a Nexus S(as well as a long list of others) and it starts fine every time. Does anyone know of anything specific to the Galaxy Nexus or ICS that could cause this behavior? And are there any suggestions for what I could try to fix?
2012/03/21
[ "https://Stackoverflow.com/questions/9812067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/507810/" ]
I had the same problem with an ICS no name tablet. SurfaceHolder isn't created when setDisplay method is called, which cause: ``` 03-21 14:52:36.196: W/VideoView(26612): java.lang.IllegalArgumentException: The surface has been released ``` To fix it, I use: ``` private void setupVideo(String file){ ... mMediaPlayer.setOnPreparedListener(this); mHolder=mSurfaceView.getHolder(); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mHolder.setKeepScreenOn(true); mHolder.addCallback(new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder holder) { mHolder=holder; mMediaPlayer.setDisplay(mHolder); ... mMediaPlayer.prepare(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { ... } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { ... } }); } @Override public void onPrepared(final MediaPlayer mp) { ... mMediaPlayer.start(); } ```
I got around this issue with the below implementation. ``` @Override protected void onPause() { Log.v("MediaVideo", "onPause"); super.onPause(); this.mVideoView.pause(); this.mVideoView.setVisibility(View.GONE); } @Override protected void onDestroy() { Log.v("MediaVideo", "onDestroy"); super.onDestroy(); } @Override protected void onResume() { Log.v("MediaVideo", "onResume"); super.onResume(); this.mVideoView.resume(); } ``` Override the OnPause and call mVideoView.pause() and the set visibility to GONE. This way I could resolve the "Activity has leaked window" log error issue.
9,812,067
I have an application thats main goal is to play a specific video file. it plays the video correctly sometimes. But other times it gives me this error: ``` 03-21 14:52:36.181: I/AwesomePlayer(119): setDataSource_l('/data/data/my.package.name/files/MyMovie.mp4') 03-21 14:52:36.196: W/VideoView(26612): Unable to open content: /data/data/my.package.name/files/MyMovie.mp4 03-21 14:52:36.196: W/VideoView(26612): java.lang.IllegalArgumentException: The surface has been released 03-21 14:52:36.196: W/VideoView(26612): at android.media.MediaPlayer._setVideoSurface(Native Method) 03-21 14:52:36.196: W/VideoView(26612): at android.media.MediaPlayer.setDisplay(MediaPlayer.java:633) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView.openVideo(VideoView.java:222) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView.access$2000(VideoView.java:49) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView$6.surfaceCreated(VideoView.java:465) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView.updateWindow(SurfaceView.java:533) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView.access$000(SurfaceView.java:81) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:169) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:590) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1617) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2442) 03-21 14:52:36.196: W/VideoView(26612): at android.os.Handler.dispatchMessage(Handler.java:99) 03-21 14:52:36.196: W/VideoView(26612): at android.os.Looper.loop(Looper.java:137) 03-21 14:52:36.196: W/VideoView(26612): at android.app.ActivityThread.main(ActivityThread.java:4424) 03-21 14:52:36.196: W/VideoView(26612): at java.lang.reflect.Method.invokeNative(Native Method) 03-21 14:52:36.196: W/VideoView(26612): at java.lang.reflect.Method.invoke(Method.java:511) 03-21 14:52:36.196: W/VideoView(26612): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 03-21 14:52:36.196: W/VideoView(26612): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 03-21 14:52:36.196: W/VideoView(26612): at dalvik.system.NativeStart.main(Native Method) 03-21 14:52:36.196: D/VideoView(26612): Error: 1,0 ``` I am using the prepared listener to call start like this: ``` mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer arg0) { mVideoView.start(); } }); ``` And I set the data source with this: ``` file = new File(this.getFilesDir() + File.separator + VIDEO_FILE_NAME); mVideoView.setVideoPath(file.getAbsolutePath()); ``` I know for certain that the file does exist and is the proper format. My application has the ability to be launched from an alarm trigger. It seems to only be a problem when the trigger fires and launches my app while the devices screen is turned off(my app will turn the screen on with a wake lock). If I manually launch the app, or the trigger happens with the screen on the video plays fine. This error is also only occuring on the Galaxy Nexus. I can run the exact same code on a Nexus S(as well as a long list of others) and it starts fine every time. Does anyone know of anything specific to the Galaxy Nexus or ICS that could cause this behavior? And are there any suggestions for what I could try to fix?
2012/03/21
[ "https://Stackoverflow.com/questions/9812067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/507810/" ]
I had the same problem with an ICS no name tablet. SurfaceHolder isn't created when setDisplay method is called, which cause: ``` 03-21 14:52:36.196: W/VideoView(26612): java.lang.IllegalArgumentException: The surface has been released ``` To fix it, I use: ``` private void setupVideo(String file){ ... mMediaPlayer.setOnPreparedListener(this); mHolder=mSurfaceView.getHolder(); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mHolder.setKeepScreenOn(true); mHolder.addCallback(new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder holder) { mHolder=holder; mMediaPlayer.setDisplay(mHolder); ... mMediaPlayer.prepare(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { ... } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { ... } }); } @Override public void onPrepared(final MediaPlayer mp) { ... mMediaPlayer.start(); } ```
Is your Galaxy Nexus by any chance rooted and running the Keyboard Manager app? I saw the exact same stack trace as you when testing my app out and kept noticing the following line in my logcat dumps: ``` 06-26 08:42:49.511 I/ActivityManager( 218): START {flg=0x10050000 cmp=com.ne0fhykLabs.android.utility.km/.TransitionDialog} from pid 11150 ``` This is the Keyboard Manager app kicking in as soon as the screen orientation changed. As soon as I disabled the Keyboard Manager service, everything started working again with my video. As far as I can tell, they were both using the same SurfaceHolder, and when Keyboard Manager was done with it, it was released, causing that exception when the VideoView tried to use it. In order to get around this, you could try what is mentioned [here](http://translate.google.com/translate?hl=en&sl=zh-CN&u=http://dingran.iteye.com/blog/1442502&prev=/search?q=IllegalArgumentException%2b%2522The%2bsurface%2bhas%2bbeen%2breleased%2522&hl=en&safe=off&client=firefox-a&rls=org.mozilla%3aen-US%3aofficial&biw=1600&bih=753&prmd=imvns&sa=X&ei=pyHrT8DGLZTW2wW-kYnYAQ&sqi=2&ved=0CGYQ7gEwAw) (the site is in Chinese, but the link is translated). I haven't tried it yet, but hopefully it will work since it's using its own dedicated SurfaceView.
9,812,067
I have an application thats main goal is to play a specific video file. it plays the video correctly sometimes. But other times it gives me this error: ``` 03-21 14:52:36.181: I/AwesomePlayer(119): setDataSource_l('/data/data/my.package.name/files/MyMovie.mp4') 03-21 14:52:36.196: W/VideoView(26612): Unable to open content: /data/data/my.package.name/files/MyMovie.mp4 03-21 14:52:36.196: W/VideoView(26612): java.lang.IllegalArgumentException: The surface has been released 03-21 14:52:36.196: W/VideoView(26612): at android.media.MediaPlayer._setVideoSurface(Native Method) 03-21 14:52:36.196: W/VideoView(26612): at android.media.MediaPlayer.setDisplay(MediaPlayer.java:633) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView.openVideo(VideoView.java:222) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView.access$2000(VideoView.java:49) 03-21 14:52:36.196: W/VideoView(26612): at android.widget.VideoView$6.surfaceCreated(VideoView.java:465) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView.updateWindow(SurfaceView.java:533) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView.access$000(SurfaceView.java:81) 03-21 14:52:36.196: W/VideoView(26612): at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:169) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:590) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1617) 03-21 14:52:36.196: W/VideoView(26612): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2442) 03-21 14:52:36.196: W/VideoView(26612): at android.os.Handler.dispatchMessage(Handler.java:99) 03-21 14:52:36.196: W/VideoView(26612): at android.os.Looper.loop(Looper.java:137) 03-21 14:52:36.196: W/VideoView(26612): at android.app.ActivityThread.main(ActivityThread.java:4424) 03-21 14:52:36.196: W/VideoView(26612): at java.lang.reflect.Method.invokeNative(Native Method) 03-21 14:52:36.196: W/VideoView(26612): at java.lang.reflect.Method.invoke(Method.java:511) 03-21 14:52:36.196: W/VideoView(26612): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 03-21 14:52:36.196: W/VideoView(26612): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 03-21 14:52:36.196: W/VideoView(26612): at dalvik.system.NativeStart.main(Native Method) 03-21 14:52:36.196: D/VideoView(26612): Error: 1,0 ``` I am using the prepared listener to call start like this: ``` mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer arg0) { mVideoView.start(); } }); ``` And I set the data source with this: ``` file = new File(this.getFilesDir() + File.separator + VIDEO_FILE_NAME); mVideoView.setVideoPath(file.getAbsolutePath()); ``` I know for certain that the file does exist and is the proper format. My application has the ability to be launched from an alarm trigger. It seems to only be a problem when the trigger fires and launches my app while the devices screen is turned off(my app will turn the screen on with a wake lock). If I manually launch the app, or the trigger happens with the screen on the video plays fine. This error is also only occuring on the Galaxy Nexus. I can run the exact same code on a Nexus S(as well as a long list of others) and it starts fine every time. Does anyone know of anything specific to the Galaxy Nexus or ICS that could cause this behavior? And are there any suggestions for what I could try to fix?
2012/03/21
[ "https://Stackoverflow.com/questions/9812067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/507810/" ]
I had the same problem with an ICS no name tablet. SurfaceHolder isn't created when setDisplay method is called, which cause: ``` 03-21 14:52:36.196: W/VideoView(26612): java.lang.IllegalArgumentException: The surface has been released ``` To fix it, I use: ``` private void setupVideo(String file){ ... mMediaPlayer.setOnPreparedListener(this); mHolder=mSurfaceView.getHolder(); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mHolder.setKeepScreenOn(true); mHolder.addCallback(new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder holder) { mHolder=holder; mMediaPlayer.setDisplay(mHolder); ... mMediaPlayer.prepare(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { ... } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { ... } }); } @Override public void onPrepared(final MediaPlayer mp) { ... mMediaPlayer.start(); } ```
Overriding the `onpause` and `onresume` callbacks seemed to fix it for me and it's ONLY for the NEXUS Galaxy that has this problem.
5,869
I have a few function. For both of them need javascript code. I need to add javascript code in header only when function is active. At this time I have all my javascript code in header for all my function and newermind which one of them is active. I tried to make this code but nothing is changed: All I have in **scripts.php** ``` function my_scripts() { if (!is_admin()) { wp_enqueue_script('jquery'); wp_enqueue_script( 'custom', get_bloginfo('template_directory').'/js/custom.js', array( 'jquery' ), '', true ); if (is_front_page()) { if (function_exists('function_one')) wp_enqueue_script( 'jquery1', get_bloginfo('template_directory').'/js/jquery.plugin.js', array( 'jquery' )); else if (function_exists('function_two')) wp_enqueue_script('jquery2', get_bloginfo('template_directory').'/js/jquery.plugin2.js', array( 'jquery' )); else if (function_exists('function_three')) wp_enqueue_script( 'jquery3', get_bloginfo('template_directory').'/js/jquery.plugin3.js', array( 'jquery' )); } } } add_action('wp_print_scripts', 'my_scripts'); ``` **mycode.php** This code include all my three functions. Looks like: ``` function function_one() { ?> ...code.. <?php } function function_two() { ?> ...code.. <?php } function function_three() { ?> ...code.. <?php } ``` This two files are defined in `functions.php`. I'm new in php, please help me how should I need to do? Thank you! --- **UPDATE** Function for choosing slider's looks like this ``` function sliders { $sliders = get_option('src_switcher'); // array in theme options with sliders name if($sliders == 'First slider') { function_one(); } if($sliders == 'Second slider') { function_two(); } if($sliders == 'Third slider') { function_three(); } } ```
2010/12/23
[ "https://wordpress.stackexchange.com/questions/5869", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1752/" ]
Basically your approach fails because `function_exist()` simply check for function definition. It doesn't care if function is ever run or anything like that. In your case I think it makes sense to handle enqueue in same way as your slider choice, something like this: ``` $sliders = get_option('src_switcher'); if($sliders == 'First slider') $plugin = 'jquery.plugin.js'; elseif($sliders == 'Second slider') $plugin = 'jquery.plugin2.js'; elseif($sliders == 'Third slider') $plugin = 'jquery.plugin3.js'; wp_enqueue_script( 'jquery-slider', get_bloginfo('template_directory').'/js/'.$plugin , array( 'jquery' )); ```
Check your logic... You say that you have 3 functions defined in a file. ``` if(condition_1_true) // in your case it is execute_function_1 elseif(condition_2_true) // this one is true also, but never gets executed because first one was true too execute_function_2 elseif(condition_3_true) // same here execute_function_3 ``` So remove "else", use "if". And what's the point of using function\_exists() if you know you have 3 functions somewhere in your app?
5,869
I have a few function. For both of them need javascript code. I need to add javascript code in header only when function is active. At this time I have all my javascript code in header for all my function and newermind which one of them is active. I tried to make this code but nothing is changed: All I have in **scripts.php** ``` function my_scripts() { if (!is_admin()) { wp_enqueue_script('jquery'); wp_enqueue_script( 'custom', get_bloginfo('template_directory').'/js/custom.js', array( 'jquery' ), '', true ); if (is_front_page()) { if (function_exists('function_one')) wp_enqueue_script( 'jquery1', get_bloginfo('template_directory').'/js/jquery.plugin.js', array( 'jquery' )); else if (function_exists('function_two')) wp_enqueue_script('jquery2', get_bloginfo('template_directory').'/js/jquery.plugin2.js', array( 'jquery' )); else if (function_exists('function_three')) wp_enqueue_script( 'jquery3', get_bloginfo('template_directory').'/js/jquery.plugin3.js', array( 'jquery' )); } } } add_action('wp_print_scripts', 'my_scripts'); ``` **mycode.php** This code include all my three functions. Looks like: ``` function function_one() { ?> ...code.. <?php } function function_two() { ?> ...code.. <?php } function function_three() { ?> ...code.. <?php } ``` This two files are defined in `functions.php`. I'm new in php, please help me how should I need to do? Thank you! --- **UPDATE** Function for choosing slider's looks like this ``` function sliders { $sliders = get_option('src_switcher'); // array in theme options with sliders name if($sliders == 'First slider') { function_one(); } if($sliders == 'Second slider') { function_two(); } if($sliders == 'Third slider') { function_three(); } } ```
2010/12/23
[ "https://wordpress.stackexchange.com/questions/5869", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1752/" ]
Hi **@Denis Belousov:** Okay, based on your responses I'm going to ask why tie it to the function existing, why not just test the return value of `get_option('src_switcher')` like this? ``` function my_scripts() { if (!is_admin()) { wp_enqueue_script('jquery'); wp_enqueue_script( 'custom', get_bloginfo('template_directory').'/js/custom.js', array( 'jquery' ), '', true ); if (is_front_page()) { $sliders = get_option('src_switcher'); if ($sliders == 'First slider') wp_enqueue_script( 'jquery1', get_bloginfo('template_directory').'/js/jquery.plugin.js', array( 'jquery' )); else if ($sliders == 'Second slider') wp_enqueue_script('jquery2', get_bloginfo('template_directory').'/js/jquery.plugin2.js', array( 'jquery' )); else if ($sliders == 'Third slider') wp_enqueue_script( 'jquery3', get_bloginfo('template_directory').'/js/jquery.plugin3.js', array( 'jquery' )); } } } add_action('wp_print_scripts', 'my_scripts'); ``` Alternately if you must use the function testing you'll want the code that defines your functions to look like this: ``` $sliders = get_option('src_switcher'); if ($sliders == 'First slider') function function_one() { ...code.. } else if($sliders == 'Second slider') function function_two() { ...code.. } else if($sliders == 'Third slider') function function_three() { ...code.. } ```
Check your logic... You say that you have 3 functions defined in a file. ``` if(condition_1_true) // in your case it is execute_function_1 elseif(condition_2_true) // this one is true also, but never gets executed because first one was true too execute_function_2 elseif(condition_3_true) // same here execute_function_3 ``` So remove "else", use "if". And what's the point of using function\_exists() if you know you have 3 functions somewhere in your app?
5,869
I have a few function. For both of them need javascript code. I need to add javascript code in header only when function is active. At this time I have all my javascript code in header for all my function and newermind which one of them is active. I tried to make this code but nothing is changed: All I have in **scripts.php** ``` function my_scripts() { if (!is_admin()) { wp_enqueue_script('jquery'); wp_enqueue_script( 'custom', get_bloginfo('template_directory').'/js/custom.js', array( 'jquery' ), '', true ); if (is_front_page()) { if (function_exists('function_one')) wp_enqueue_script( 'jquery1', get_bloginfo('template_directory').'/js/jquery.plugin.js', array( 'jquery' )); else if (function_exists('function_two')) wp_enqueue_script('jquery2', get_bloginfo('template_directory').'/js/jquery.plugin2.js', array( 'jquery' )); else if (function_exists('function_three')) wp_enqueue_script( 'jquery3', get_bloginfo('template_directory').'/js/jquery.plugin3.js', array( 'jquery' )); } } } add_action('wp_print_scripts', 'my_scripts'); ``` **mycode.php** This code include all my three functions. Looks like: ``` function function_one() { ?> ...code.. <?php } function function_two() { ?> ...code.. <?php } function function_three() { ?> ...code.. <?php } ``` This two files are defined in `functions.php`. I'm new in php, please help me how should I need to do? Thank you! --- **UPDATE** Function for choosing slider's looks like this ``` function sliders { $sliders = get_option('src_switcher'); // array in theme options with sliders name if($sliders == 'First slider') { function_one(); } if($sliders == 'Second slider') { function_two(); } if($sliders == 'Third slider') { function_three(); } } ```
2010/12/23
[ "https://wordpress.stackexchange.com/questions/5869", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1752/" ]
Hi **@Denis Belousov:** Okay, based on your responses I'm going to ask why tie it to the function existing, why not just test the return value of `get_option('src_switcher')` like this? ``` function my_scripts() { if (!is_admin()) { wp_enqueue_script('jquery'); wp_enqueue_script( 'custom', get_bloginfo('template_directory').'/js/custom.js', array( 'jquery' ), '', true ); if (is_front_page()) { $sliders = get_option('src_switcher'); if ($sliders == 'First slider') wp_enqueue_script( 'jquery1', get_bloginfo('template_directory').'/js/jquery.plugin.js', array( 'jquery' )); else if ($sliders == 'Second slider') wp_enqueue_script('jquery2', get_bloginfo('template_directory').'/js/jquery.plugin2.js', array( 'jquery' )); else if ($sliders == 'Third slider') wp_enqueue_script( 'jquery3', get_bloginfo('template_directory').'/js/jquery.plugin3.js', array( 'jquery' )); } } } add_action('wp_print_scripts', 'my_scripts'); ``` Alternately if you must use the function testing you'll want the code that defines your functions to look like this: ``` $sliders = get_option('src_switcher'); if ($sliders == 'First slider') function function_one() { ...code.. } else if($sliders == 'Second slider') function function_two() { ...code.. } else if($sliders == 'Third slider') function function_three() { ...code.. } ```
Basically your approach fails because `function_exist()` simply check for function definition. It doesn't care if function is ever run or anything like that. In your case I think it makes sense to handle enqueue in same way as your slider choice, something like this: ``` $sliders = get_option('src_switcher'); if($sliders == 'First slider') $plugin = 'jquery.plugin.js'; elseif($sliders == 'Second slider') $plugin = 'jquery.plugin2.js'; elseif($sliders == 'Third slider') $plugin = 'jquery.plugin3.js'; wp_enqueue_script( 'jquery-slider', get_bloginfo('template_directory').'/js/'.$plugin , array( 'jquery' )); ```
64,307
Can you tell me? The less you have, the more likely is it for you to lose it. What am I thinking about?
2018/04/18
[ "https://puzzling.stackexchange.com/questions/64307", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/31496/" ]
Are you > > patience? > > > Because > > If you are not that patient, you will lose patience easily > > >
Let's give it a noteworthy shot. > > Chess/checkers pieces. > > > The less you have, the more likely is it for you to lose it. > > With fewer pieces, it might be harder to prevent the opponent from taking them. > > If you don't believe me, try defending your 5 remaining pawns from a bloodthirsty queen. > > >
64,307
Can you tell me? The less you have, the more likely is it for you to lose it. What am I thinking about?
2018/04/18
[ "https://puzzling.stackexchange.com/questions/64307", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/31496/" ]
Are you > > patience? > > > Because > > If you are not that patient, you will lose patience easily > > >
> > **Balance** > > Since, the less balance you have, more likely to lose it. > > >
64,307
Can you tell me? The less you have, the more likely is it for you to lose it. What am I thinking about?
2018/04/18
[ "https://puzzling.stackexchange.com/questions/64307", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/31496/" ]
Are you > > patience? > > > Because > > If you are not that patient, you will lose patience easily > > >
It could be > > Poker Chips because you will lose them to the beginning pot and you cannot take risky bets. > > >
64,307
Can you tell me? The less you have, the more likely is it for you to lose it. What am I thinking about?
2018/04/18
[ "https://puzzling.stackexchange.com/questions/64307", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/31496/" ]
Are you > > patience? > > > Because > > If you are not that patient, you will lose patience easily > > >
This could be a lot of things, like: > > Hope, Focus, Confidence, Trust - the less you have of each of these, the easier it is to lose them. > > > In addition to all the other good answers already posted.
64,307
Can you tell me? The less you have, the more likely is it for you to lose it. What am I thinking about?
2018/04/18
[ "https://puzzling.stackexchange.com/questions/64307", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/31496/" ]
Let's give it a noteworthy shot. > > Chess/checkers pieces. > > > The less you have, the more likely is it for you to lose it. > > With fewer pieces, it might be harder to prevent the opponent from taking them. > > If you don't believe me, try defending your 5 remaining pawns from a bloodthirsty queen. > > >
It could be > > Poker Chips because you will lose them to the beginning pot and you cannot take risky bets. > > >
64,307
Can you tell me? The less you have, the more likely is it for you to lose it. What am I thinking about?
2018/04/18
[ "https://puzzling.stackexchange.com/questions/64307", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/31496/" ]
Let's give it a noteworthy shot. > > Chess/checkers pieces. > > > The less you have, the more likely is it for you to lose it. > > With fewer pieces, it might be harder to prevent the opponent from taking them. > > If you don't believe me, try defending your 5 remaining pawns from a bloodthirsty queen. > > >
This could be a lot of things, like: > > Hope, Focus, Confidence, Trust - the less you have of each of these, the easier it is to lose them. > > > In addition to all the other good answers already posted.
64,307
Can you tell me? The less you have, the more likely is it for you to lose it. What am I thinking about?
2018/04/18
[ "https://puzzling.stackexchange.com/questions/64307", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/31496/" ]
> > **Balance** > > Since, the less balance you have, more likely to lose it. > > >
It could be > > Poker Chips because you will lose them to the beginning pot and you cannot take risky bets. > > >
64,307
Can you tell me? The less you have, the more likely is it for you to lose it. What am I thinking about?
2018/04/18
[ "https://puzzling.stackexchange.com/questions/64307", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/31496/" ]
> > **Balance** > > Since, the less balance you have, more likely to lose it. > > >
This could be a lot of things, like: > > Hope, Focus, Confidence, Trust - the less you have of each of these, the easier it is to lose them. > > > In addition to all the other good answers already posted.
16,269,084
My code is here: <http://jsfiddle.net/GwUmb/4/> ``` $(document).ready(function(){ $(".trigger,.trigger-2").click(function(){ $(".panel,.panel-2").toggle("fast"); $(this).toggleClass("active"); return false; }); }); ``` I've been struggling to load panel-2 from trigger-2...I notice that .trigger and .panel behave (somewhat) as expected (I notice some css-style weirdness). If I remove the .panel-2 and the .trigger-2 the code behaves perfectly...but otherwise it doesn't. I was trying to replicate what I read here: <http://www.w3schools.com/jquery/sel_multiple_classes.asp> .
2013/04/28
[ "https://Stackoverflow.com/questions/16269084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2023783/" ]
The issue here is that no matter which trigger you click, *both* (or all) panels will be activated because you are selecting them both and calling `.toggle` on them. There are many ways to solve this such as storing the corresponding index of the panel on the trigger as `data`, or using the index. The latter may work well for you. ``` $(".trigger").click(function(e) { $(".panel").eq($(this).index(".trigger")).toggle("fast"); $(this).toggleClass("active"); e.preventDefault(); }); ``` <http://jsfiddle.net/GwUmb/6/>
Another option for you is to use a single class name for your links/containers. I have cleaned up your code a little bit and provided a hover function to display your links. It should be a good starting point for you. A CSS approach using lists may be an even easier approach... working example is here <http://jsfiddle.net/GwUmb/11/> updated jQuery: ``` $(document).ready(function() { //global var to hold the current selected link var $link; $('.trigger').hover(function() { $link = $(this); //get position of clicked link var linkPos = $link.position(); //position & display this links panel $link.toggleClass("active"); $link.siblings('.panel').css({ 'top' : linkPos.top }).fadeIn(600); }, function() {//hide the panel on mouseout $link.siblings('.panel').slideUp(600); $link.removeClass('active'); }); }); // end ready ```
453,464
I have tmux installed with iTerm2 on OS X. While I can do `Cmd+left/right` to switch between tabs, I cannot seem to be able to switch between panes under the same tab using `Ctl+b o` (that is, `Control` and `b` together, followed by an `o`?) as suggested by others. I don't think I've touched any default key binding for tmux, so what is the correct keyboard shortcut for this operation?
2012/07/25
[ "https://superuser.com/questions/453464", "https://superuser.com", "https://superuser.com/users/140701/" ]
`Cmd` + `Opt` + `Up` or `Down` or `Left` or `Right` works for me.
You can see a list of all your bindings using `Ctl+b ?`. You're looking for the following line: ``` bind-key o select-pane -t :.+ ``` although it sounds as if you may have a key other than 'o' bound to it.
22,683,269
I am new to shell script. I have a file `app.conf` as : ``` [MySql] user = root password = root123 domain = localhost database = db_name port = 3306 [Logs] level = logging.DEBUG [Server] port = 8080 ``` I want to parse this file in shell script and want to extract mysql credentials from the same. How can I achieve that?
2014/03/27
[ "https://Stackoverflow.com/questions/22683269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2745266/" ]
I'd do this: ``` pw=$(awk '/^password/{print $3}' app.conf) user=$(awk '/^user/{print $3}' app.conf) echo $pw root123 echo $user root ``` The `$()` sets the variable `pw` to the output of the command inside. The command inside looks through your app.conf file for a line starting `password` and then prints the 3rd field in that line. **EDITED** If you are going to parse a bunch of values out of your config file, I would make a variable for the config file name: ``` CONFIG=app.conf pw=$(awk '/^password/{print $3}' "${CONFIG}") user=$(awk '/^user/{print $3}' "${CONFIG}") ``` Here's how to do the two different ports... by setting a flag to 1 when you come to the right section and exiting when you find the port. ``` mport=$(awk '/^\[MySQL\]/{f=1} f==1&&/^port/{print $3;exit}' "${CONFIG}") sport=$(awk '/^\[Server\]/{f=1} f==1&&/^port/{print $3;exit}' "${CONFIG}") ```
Using awk: ``` awk -F ' *= *' '$1=="user"||$1=="password"{print $2}' my.cnf root gogslab ```
22,683,269
I am new to shell script. I have a file `app.conf` as : ``` [MySql] user = root password = root123 domain = localhost database = db_name port = 3306 [Logs] level = logging.DEBUG [Server] port = 8080 ``` I want to parse this file in shell script and want to extract mysql credentials from the same. How can I achieve that?
2014/03/27
[ "https://Stackoverflow.com/questions/22683269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2745266/" ]
Using awk: ``` awk -F ' *= *' '$1=="user"||$1=="password"{print $2}' my.cnf root gogslab ```
I ran in a similar problem yesterday and thought the best solution might be, if you get an associative array like "key - value" after parsing the file. I you like to see a running example have a look at <https://github.com/philippkemmeter/set-resolution/blob/master/set-resolution>. Adapted to your problem, this might work: ``` function receive_assoc_declare_statement { awk -F '=' 'BEGIN {ORS=" "} { gsub(/[ \t]+/, "", $1); gsub(/[ \t]+/, "", $2); print "[" $1 "]=" $2 }' app.conf } eval 'declare -A CONF=('`receive_assoc_declare_statement`')' ``` You then have access to for instance user via `${CONF[user]}`. The gsub is trimming keys and values, so that you can use tab etc. to format your config file. It's lacking sections, but you could add this functionality using sed to create one config array per section: ``` sed -n '/\[MySql\]/, /\[/ {p}' test.removeme | sed '1 d; $ d' ``` --- So answering your question in total, this script might work: ``` MYSQL=`sed -n '/\[MySql\]/, /\[/ {p}' app.conf | sed '1 d; $ d' | awk -F '=' 'BEGIN {ORS=" "} { gsub(/[ \t]+/, "", $1); gsub(/[ \t]+/, "", $2); print "[" $1 "]=" $2 }' ` eval 'declare -A MYSQL=('$MYSQL')' ``` The other sections correspondingly.
22,683,269
I am new to shell script. I have a file `app.conf` as : ``` [MySql] user = root password = root123 domain = localhost database = db_name port = 3306 [Logs] level = logging.DEBUG [Server] port = 8080 ``` I want to parse this file in shell script and want to extract mysql credentials from the same. How can I achieve that?
2014/03/27
[ "https://Stackoverflow.com/questions/22683269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2745266/" ]
I'd do this: ``` pw=$(awk '/^password/{print $3}' app.conf) user=$(awk '/^user/{print $3}' app.conf) echo $pw root123 echo $user root ``` The `$()` sets the variable `pw` to the output of the command inside. The command inside looks through your app.conf file for a line starting `password` and then prints the 3rd field in that line. **EDITED** If you are going to parse a bunch of values out of your config file, I would make a variable for the config file name: ``` CONFIG=app.conf pw=$(awk '/^password/{print $3}' "${CONFIG}") user=$(awk '/^user/{print $3}' "${CONFIG}") ``` Here's how to do the two different ports... by setting a flag to 1 when you come to the right section and exiting when you find the port. ``` mport=$(awk '/^\[MySQL\]/{f=1} f==1&&/^port/{print $3;exit}' "${CONFIG}") sport=$(awk '/^\[Server\]/{f=1} f==1&&/^port/{print $3;exit}' "${CONFIG}") ```
You will want to search for "shell ini file parser". I would start with something like this: ``` ini_get () { awk -v section="$2" -v variable="$3" ' $0 == "[" section "]" { in_section = 1; next } in_section && $1 == variable { $1="" $2="" sub(/^[[:space:]]+/, "") print exit } in_section && $1 == "" { # we are at a blank line without finding the var in the section print "not found" > "/dev/stderr" exit 1 } ' "$1" } mysql_user=$( ini_get app.conf MySql user ) ```
22,683,269
I am new to shell script. I have a file `app.conf` as : ``` [MySql] user = root password = root123 domain = localhost database = db_name port = 3306 [Logs] level = logging.DEBUG [Server] port = 8080 ``` I want to parse this file in shell script and want to extract mysql credentials from the same. How can I achieve that?
2014/03/27
[ "https://Stackoverflow.com/questions/22683269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2745266/" ]
I'd do this: ``` pw=$(awk '/^password/{print $3}' app.conf) user=$(awk '/^user/{print $3}' app.conf) echo $pw root123 echo $user root ``` The `$()` sets the variable `pw` to the output of the command inside. The command inside looks through your app.conf file for a line starting `password` and then prints the 3rd field in that line. **EDITED** If you are going to parse a bunch of values out of your config file, I would make a variable for the config file name: ``` CONFIG=app.conf pw=$(awk '/^password/{print $3}' "${CONFIG}") user=$(awk '/^user/{print $3}' "${CONFIG}") ``` Here's how to do the two different ports... by setting a flag to 1 when you come to the right section and exiting when you find the port. ``` mport=$(awk '/^\[MySQL\]/{f=1} f==1&&/^port/{print $3;exit}' "${CONFIG}") sport=$(awk '/^\[Server\]/{f=1} f==1&&/^port/{print $3;exit}' "${CONFIG}") ```
I ran in a similar problem yesterday and thought the best solution might be, if you get an associative array like "key - value" after parsing the file. I you like to see a running example have a look at <https://github.com/philippkemmeter/set-resolution/blob/master/set-resolution>. Adapted to your problem, this might work: ``` function receive_assoc_declare_statement { awk -F '=' 'BEGIN {ORS=" "} { gsub(/[ \t]+/, "", $1); gsub(/[ \t]+/, "", $2); print "[" $1 "]=" $2 }' app.conf } eval 'declare -A CONF=('`receive_assoc_declare_statement`')' ``` You then have access to for instance user via `${CONF[user]}`. The gsub is trimming keys and values, so that you can use tab etc. to format your config file. It's lacking sections, but you could add this functionality using sed to create one config array per section: ``` sed -n '/\[MySql\]/, /\[/ {p}' test.removeme | sed '1 d; $ d' ``` --- So answering your question in total, this script might work: ``` MYSQL=`sed -n '/\[MySql\]/, /\[/ {p}' app.conf | sed '1 d; $ d' | awk -F '=' 'BEGIN {ORS=" "} { gsub(/[ \t]+/, "", $1); gsub(/[ \t]+/, "", $2); print "[" $1 "]=" $2 }' ` eval 'declare -A MYSQL=('$MYSQL')' ``` The other sections correspondingly.
22,683,269
I am new to shell script. I have a file `app.conf` as : ``` [MySql] user = root password = root123 domain = localhost database = db_name port = 3306 [Logs] level = logging.DEBUG [Server] port = 8080 ``` I want to parse this file in shell script and want to extract mysql credentials from the same. How can I achieve that?
2014/03/27
[ "https://Stackoverflow.com/questions/22683269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2745266/" ]
You will want to search for "shell ini file parser". I would start with something like this: ``` ini_get () { awk -v section="$2" -v variable="$3" ' $0 == "[" section "]" { in_section = 1; next } in_section && $1 == variable { $1="" $2="" sub(/^[[:space:]]+/, "") print exit } in_section && $1 == "" { # we are at a blank line without finding the var in the section print "not found" > "/dev/stderr" exit 1 } ' "$1" } mysql_user=$( ini_get app.conf MySql user ) ```
I ran in a similar problem yesterday and thought the best solution might be, if you get an associative array like "key - value" after parsing the file. I you like to see a running example have a look at <https://github.com/philippkemmeter/set-resolution/blob/master/set-resolution>. Adapted to your problem, this might work: ``` function receive_assoc_declare_statement { awk -F '=' 'BEGIN {ORS=" "} { gsub(/[ \t]+/, "", $1); gsub(/[ \t]+/, "", $2); print "[" $1 "]=" $2 }' app.conf } eval 'declare -A CONF=('`receive_assoc_declare_statement`')' ``` You then have access to for instance user via `${CONF[user]}`. The gsub is trimming keys and values, so that you can use tab etc. to format your config file. It's lacking sections, but you could add this functionality using sed to create one config array per section: ``` sed -n '/\[MySql\]/, /\[/ {p}' test.removeme | sed '1 d; $ d' ``` --- So answering your question in total, this script might work: ``` MYSQL=`sed -n '/\[MySql\]/, /\[/ {p}' app.conf | sed '1 d; $ d' | awk -F '=' 'BEGIN {ORS=" "} { gsub(/[ \t]+/, "", $1); gsub(/[ \t]+/, "", $2); print "[" $1 "]=" $2 }' ` eval 'declare -A MYSQL=('$MYSQL')' ``` The other sections correspondingly.
23,142,155
I posted this question yesterday: <https://stackoverflow.com/questions/23119494/what-is-the-best-way-to-dynamically-change-the-style-of-a-uicollectionview> and received 0 responses. I decided to experiment a bit. What I'm trying to do is have a grid style default collection view display change to a single file display when a UISegmentedControl is clicked. **Grid style as default:** ![enter image description here](https://i.stack.imgur.com/7d4G7.png) **After tapping button left segment a single item view is displayed:** ![enter image description here](https://i.stack.imgur.com/dMt90.png) I have a method ready that responds to the tap of each segment. I now hide the collectionView when the segment control is tapped and unhide it when it is tapped again.: ``` - (void)displayTypeSegmentSelected { _selectedDisplayTypeIndex = [_displayTypeControl selectedSegmentIndex]; if (_selectedDisplayTypeIndex == 0) { NSLog(@"Single file item view selected"); [_collectionView setHidden:YES]; } else { NSLog(@"Grid style view selected"); [_collectionView setHidden:NO]; } } ``` This works perfectly to show and hide my default collectionView and the functionality of the rest of this controller isn't affected. **Possible solutions:** Now I was wondering if there is a way to create another collectionView with the single file design and have it display whenever the default collectionView is hidden. It will use the exact same datasource and sort of plug in to the controller and just work. **Can this be done view interface builder? If so how do I do this?** **Can this be done programmatically? If so how do I go about doing this?** I was wonder if I should have both collectionViews created initially rather than the default at the start and the single file only when segmentControl is clicked. Would appreciate some examples or clear explanation. Been researching all day with no luck on how to do this. Regards
2014/04/17
[ "https://Stackoverflow.com/questions/23142155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439688/" ]
You might want to look into [RMQ](https://github.com/infinitered/rmq) if you are going to be doing much of this. The code would be far simpler. Example: ``` view.parent.find(UILabel).attr(text: '') # Sets all UILabels below parent to blank ``` or, if you're bent on removing the labels: ``` view.parent.find(UILabel).remove # Removes all UILabels below parent ``` If you really want to know whether there was a `UILabel` present in the first place, just use the selector: ``` view.parent.find(UILabel).length ``` That will come up zero if none are there, otherwise you'll have a count of labels in the parent view. This is not an exact answer to your question, but rather an alternative way to accomplish the task you're describing. Using stylesheets, you can clear a bunch of setup stuff out of your controller code and put it in styles. Then you can act by hiding, showing, inserting, or removing various UI elements.
I think it is better to clear the text of the label or you can hide and then make it visible instead of adding and removing the view.
10,410,030
I have a database of documents which are tagged with keywords. I am trying to find (and then count) the unique tags which are used alongside each other. So for any given tag, I want to know what tags have been used alongside that tag. For example, if I had one document which had the tags `[fruit, apple, plant]` then when I query `[apple]` I should get `[fruit, plant]`. If another document has tags `[apple, banana]` then my query for `[apple]` would give me `[fruit, plant, banana]` instead. This is my map function which emits all the tags and their neighbours: ``` function(doc) { if(doc.tags) { doc.tags.forEach(function(tag1) { doc.tags.forEach(function(tag2) { emit(tag1, tag2); }); }); } } ``` So in my example above, it would emit ``` apple -- fruit apple -- plant apple -- banana fruit -- apple fruit -- plant ... ``` My question is: what should my reduce function be? The reduce function should essentially filter out the duplicates and group them all together. I have tried a number of different attempts, but my database server (CouchDB) keeps giving me a **Error: reduce\_overflow\_error. Reduce output must shrink more rapidly**. --- **EDIT: I've found something that seems to work, but I'm not sure why.** I see there is an optional "rereduce" parameter to the reduce function call. If I ignore these special cases, then it stops throwing reduce\_overflow\_errors. Can anyone explain why? And also, should I just be ignoring these, or will this bite me in the ass later? ``` function(keys, values, rereduce) { if(rereduce) return null; // Throws error without this. var a = []; values.forEach(function(tag) { if(a.indexOf(tag) < 0) a.push(tag); }); return a; } ```
2012/05/02
[ "https://Stackoverflow.com/questions/10410030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/307614/" ]
Your answer is nice, and as I said in the comments, if it works for you, that's all you should care about. Here is an alternative implementation in case you ever bump into performance problems. CouchDB likes tall lists, not fat lists. Instead of view rows keeping an array with every previous tag ever seen, this solution keeps the "sibling" tags in the **key** of the view rows, and then [group them together](http://wiki.apache.org/couchdb/Introduction_to_CouchDB_views#Grouping) to guarantee one unique sibling tag per row. Every row is just two tags, but there could be thousands or millions of rows: a tall list, which CouchDB prefers. The main idea is to emit a 2-array of tag pairs. Suppose we have one doc, tagged `fruit, apple, plant`. ``` // Pseudo-code visualization of view rows (before reduce) // Key , Value [apple, fruit ], 1 [apple, plant ], 1 // Basically this is every combination of 2 tags in the set. [fruit, apple ], 1 [fruit, plant ], 1 [plant, apple ], 1 [plant, fruit ], 1 ``` Next I tag something `apple, banana`. ``` // Pseudo-code visualization of view rows (before reduce) // Key , Value [apple, banana], 1 // This is from my new doc [apple, fruit ], 1 [apple, plant ], 1 // This is also from my new doc [banana, apple], 1 [fruit, apple ], 1 [fruit, plant ], 1 [plant, apple ], 1 [plant, fruit ], 1 ``` Why is the value always `1`? Because I can make a very simple built-in reduce function: `_sum` to tell me the count of all tag pairs. Next, query with `?group_level=2` and CouchDB will give you unique pairs, with a count of their total. A map function to produce this kind of view might look like this: ``` function(doc) { // Emit "sibling" tags, keyed on tag pairs. var tags = doc.tags || [] tags.forEach(function(tag1) { tags.forEach(function(tag2) { if(tag1 != tag2) emit([tag1, tag2], 1) }) }) } ```
I have found a correct solution I am much happier with. The trick was that CouchDB must be set to `reduce_limit = false` so that it stops checking its heuristic against your query. You can set this via Futon on <http://localhost:5984/_utils/config.html> under the **query\_server\_config** settings, by double clicking on the value. Once that's done, here is my new map function which works better with the "re-reducing" part of the reduce function: ``` function(doc) { if(doc.tags) { doc.tags.forEach(function(tag1) { doc.tags.forEach(function(tag2) { emit(tag1, [tag2]); // Array with single value }); }); } } ``` And here is the reduce function: ``` function(keys, values) { var a = []; values.forEach(function(tags) { tags.forEach(function(tag) { if(a.indexOf(tag) < 0) a.push(tag); }); }); return a; } ``` Hope this helps someone!
14,128,787
I'm looking for a way to specify where a line should break ***if*** it cannot fit on its line in a way similar to `&shy;` (soft/discretionary hyphen), but with a space. I tried googling it but didn't get many relevant hits (mostly for InDesign despite specifying "html"), and what I did get was a few people saying they didn't know of a way. Ex. > > Hello, my name > > is foo. > > **vs.** > > Hello, > > my name is foo. > > **but if space is available:** > > Hello, my name is foo. > > > For specificity, I do not mean `white-space: normal/nowrap/pre/…` and I don't want to force a break like with `<br />`. I'm using AngularJS, so most everything is processed thru JavaScript, so if there's an easy/efficient/clever way to do it with that, I'd be open to it.
2013/01/02
[ "https://Stackoverflow.com/questions/14128787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/758177/" ]
You could use the [`<wbr>`](http://www.w3.org/TR/html5/text-level-semantics.html#the-wbr-element) tag. EDIT: As mentioned in the comments, you could use a [zero-width space](http://en.wikipedia.org/wiki/Zero-width_space): `&#8203;` (See also: [What's the opposite of a nbsp?](https://stackoverflow.com/questions/2046530/whats-the-opposite-of-a-nbsp))
I don't think there's any native way to do that, but here's a hack I've been using whenever I really need this sort of thing: ``` var str = "Hello,<br>My name is foo."; str = str.replace(/ /g, '&nbsp;').replace(/<br>/g, ' '); ``` Basically, use a non-breaking space to separate the words you don't want to break at. See it here in action: <http://jsfiddle.net/5xmt6/> (resize the window to see how it reacts). --- **Note:** this is *very* hacky, and introduces its own set of problems; namely: if the viewport becomes extremely narrow, the rest of the text won't wrap.
14,128,787
I'm looking for a way to specify where a line should break ***if*** it cannot fit on its line in a way similar to `&shy;` (soft/discretionary hyphen), but with a space. I tried googling it but didn't get many relevant hits (mostly for InDesign despite specifying "html"), and what I did get was a few people saying they didn't know of a way. Ex. > > Hello, my name > > is foo. > > **vs.** > > Hello, > > my name is foo. > > **but if space is available:** > > Hello, my name is foo. > > > For specificity, I do not mean `white-space: normal/nowrap/pre/…` and I don't want to force a break like with `<br />`. I'm using AngularJS, so most everything is processed thru JavaScript, so if there's an easy/efficient/clever way to do it with that, I'd be open to it.
2013/01/02
[ "https://Stackoverflow.com/questions/14128787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/758177/" ]
To indicate where line break should *not* appear between words, use a NO-BREAK SPACE, or ' `, between words. Any normal space *is* breakable. So you can write e.g. ``` Hello,&nbsp;my&nbsp;name is&nbsp;foo. ``` If you would rather indicate the allowed breaks (as per your comment below), you can wrap the text inside a `nobr` element (nonstandard, but works like a charm) or inside any element for which you set `white-space: nowrap`, thereby disallowing line breaks except when explicitly forced or allowed. You would then use the `<wbr>` tag (nonstandard, but...) or the character reference `&#8203;` or `&#x200b;` (for ice ZERO WIDTH SPACE) *after* a space to allow a line break, e.g. ``` <nobr>Hello, <wbr>my name <wbr>is foo.</nobr> ``` The choice between `<wbr>` and ZERO WIDTH SPACE is a [tricky issue](http://www.cs.tut.fi/~jkorpela/html/nobr.html), mainly due to IE oddities.
I don't think there's any native way to do that, but here's a hack I've been using whenever I really need this sort of thing: ``` var str = "Hello,<br>My name is foo."; str = str.replace(/ /g, '&nbsp;').replace(/<br>/g, ' '); ``` Basically, use a non-breaking space to separate the words you don't want to break at. See it here in action: <http://jsfiddle.net/5xmt6/> (resize the window to see how it reacts). --- **Note:** this is *very* hacky, and introduces its own set of problems; namely: if the viewport becomes extremely narrow, the rest of the text won't wrap.
14,128,787
I'm looking for a way to specify where a line should break ***if*** it cannot fit on its line in a way similar to `&shy;` (soft/discretionary hyphen), but with a space. I tried googling it but didn't get many relevant hits (mostly for InDesign despite specifying "html"), and what I did get was a few people saying they didn't know of a way. Ex. > > Hello, my name > > is foo. > > **vs.** > > Hello, > > my name is foo. > > **but if space is available:** > > Hello, my name is foo. > > > For specificity, I do not mean `white-space: normal/nowrap/pre/…` and I don't want to force a break like with `<br />`. I'm using AngularJS, so most everything is processed thru JavaScript, so if there's an easy/efficient/clever way to do it with that, I'd be open to it.
2013/01/02
[ "https://Stackoverflow.com/questions/14128787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/758177/" ]
You could use the [`<wbr>`](http://www.w3.org/TR/html5/text-level-semantics.html#the-wbr-element) tag. EDIT: As mentioned in the comments, you could use a [zero-width space](http://en.wikipedia.org/wiki/Zero-width_space): `&#8203;` (See also: [What's the opposite of a nbsp?](https://stackoverflow.com/questions/2046530/whats-the-opposite-of-a-nbsp))
Here's a technique that still works: break text into groups using spans of `inline-block`. <https://jsfiddle.net/mindplay/7aeyp3hs/> [![example](https://i.stack.imgur.com/ojdKv.gif)](https://i.stack.imgur.com/ojdKv.gif) Note that I'm using an `@media` rule to turn off this effect on very small devices, where the text will just flow as text normally flows.
14,128,787
I'm looking for a way to specify where a line should break ***if*** it cannot fit on its line in a way similar to `&shy;` (soft/discretionary hyphen), but with a space. I tried googling it but didn't get many relevant hits (mostly for InDesign despite specifying "html"), and what I did get was a few people saying they didn't know of a way. Ex. > > Hello, my name > > is foo. > > **vs.** > > Hello, > > my name is foo. > > **but if space is available:** > > Hello, my name is foo. > > > For specificity, I do not mean `white-space: normal/nowrap/pre/…` and I don't want to force a break like with `<br />`. I'm using AngularJS, so most everything is processed thru JavaScript, so if there's an easy/efficient/clever way to do it with that, I'd be open to it.
2013/01/02
[ "https://Stackoverflow.com/questions/14128787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/758177/" ]
To indicate where line break should *not* appear between words, use a NO-BREAK SPACE, or ' `, between words. Any normal space *is* breakable. So you can write e.g. ``` Hello,&nbsp;my&nbsp;name is&nbsp;foo. ``` If you would rather indicate the allowed breaks (as per your comment below), you can wrap the text inside a `nobr` element (nonstandard, but works like a charm) or inside any element for which you set `white-space: nowrap`, thereby disallowing line breaks except when explicitly forced or allowed. You would then use the `<wbr>` tag (nonstandard, but...) or the character reference `&#8203;` or `&#x200b;` (for ice ZERO WIDTH SPACE) *after* a space to allow a line break, e.g. ``` <nobr>Hello, <wbr>my name <wbr>is foo.</nobr> ``` The choice between `<wbr>` and ZERO WIDTH SPACE is a [tricky issue](http://www.cs.tut.fi/~jkorpela/html/nobr.html), mainly due to IE oddities.
Here's a technique that still works: break text into groups using spans of `inline-block`. <https://jsfiddle.net/mindplay/7aeyp3hs/> [![example](https://i.stack.imgur.com/ojdKv.gif)](https://i.stack.imgur.com/ojdKv.gif) Note that I'm using an `@media` rule to turn off this effect on very small devices, where the text will just flow as text normally flows.
2,325,824
Basically I'm modifying a parser to handle additional operators. Before my changes, one part of the parser looked like this: ``` parseExpRec e1 (op : ts) = let (e2, ts') = parsePrimExp ts in case op of T_Plus -> parseExpRec (BinOpApp Plus e1 e2) ts' T_Minus -> parseExpRec (BinOpApp Minus e1 e2) ts' T_Times -> parseExpRec (BinOpApp Times e1 e2) ts' T_Divide -> parseExpRec (BinOpApp Divide e1 e2) ts' _ -> (e1, op : ts) ``` T\_Plus etc. are members of the Token datatype, and Plus, Minus etc. are part of BinOp which BinOpApp applies to two operands. I have updated the Token and BinOpApp datatypes to handle the Power (exponentiation) token. This is the resulting code: ``` parseExpRec e1 (op : ts) = let (e2, ts') = parsePrimExp ts in case op of T_Plus -> parseExpRec (BinOpApp Plus e1 e2) ts' T_Minus -> parseExpRec (BinOpApp Minus e1 e2) ts' T_Times -> parseExpRec (BinOpApp Times e1 e2) ts' T_Divide -> parseExpRec (BinOpApp Divide e1 e2) ts' T_Power -> parseExpRec (BinOpApp Power e1 e2) ts' _ -> (e1, op : ts) ``` This seems simple but it's now giving the following error: > > TXL.hs:182:13: parse error on input '->' > > > Line 182 is the line where I added "T\_Power -> parseExpRec..." - I don't see how it's any different from the other lines, which parse fine. I'm using GHCi as my environment.
2010/02/24
[ "https://Stackoverflow.com/questions/2325824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49128/" ]
Have you indented the new line with the same space-delimiters as the previous ones? Or, has a tab character snuck in there?
Maybe you still need to setup T\_Power in the lexer? For example, what symbol are you using for exponentiation (e.g. ^), and where is that associated with T\_Power? I don't know if [this](http://www.cs.nott.ac.uk/~nhn/G52CMP/LectureNotes-2009/lecture03+04-handout.pdf) (or something similar) is what you're working from, but maybe something like: ``` scanner (’^’ : cs) = T_Power : scanner cs ```
2,325,824
Basically I'm modifying a parser to handle additional operators. Before my changes, one part of the parser looked like this: ``` parseExpRec e1 (op : ts) = let (e2, ts') = parsePrimExp ts in case op of T_Plus -> parseExpRec (BinOpApp Plus e1 e2) ts' T_Minus -> parseExpRec (BinOpApp Minus e1 e2) ts' T_Times -> parseExpRec (BinOpApp Times e1 e2) ts' T_Divide -> parseExpRec (BinOpApp Divide e1 e2) ts' _ -> (e1, op : ts) ``` T\_Plus etc. are members of the Token datatype, and Plus, Minus etc. are part of BinOp which BinOpApp applies to two operands. I have updated the Token and BinOpApp datatypes to handle the Power (exponentiation) token. This is the resulting code: ``` parseExpRec e1 (op : ts) = let (e2, ts') = parsePrimExp ts in case op of T_Plus -> parseExpRec (BinOpApp Plus e1 e2) ts' T_Minus -> parseExpRec (BinOpApp Minus e1 e2) ts' T_Times -> parseExpRec (BinOpApp Times e1 e2) ts' T_Divide -> parseExpRec (BinOpApp Divide e1 e2) ts' T_Power -> parseExpRec (BinOpApp Power e1 e2) ts' _ -> (e1, op : ts) ``` This seems simple but it's now giving the following error: > > TXL.hs:182:13: parse error on input '->' > > > Line 182 is the line where I added "T\_Power -> parseExpRec..." - I don't see how it's any different from the other lines, which parse fine. I'm using GHCi as my environment.
2010/02/24
[ "https://Stackoverflow.com/questions/2325824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49128/" ]
This is almost with 100% certainty an indentation error. I've had similar problems in the past, also when writing a parser. What's probably happened is the lines before the problematic line are indented with tabs, and you've used spaces on the T\_Power line (or something similar). Can you turn on non-printed characters in your editor?
Maybe you still need to setup T\_Power in the lexer? For example, what symbol are you using for exponentiation (e.g. ^), and where is that associated with T\_Power? I don't know if [this](http://www.cs.nott.ac.uk/~nhn/G52CMP/LectureNotes-2009/lecture03+04-handout.pdf) (or something similar) is what you're working from, but maybe something like: ``` scanner (’^’ : cs) = T_Power : scanner cs ```
2,325,824
Basically I'm modifying a parser to handle additional operators. Before my changes, one part of the parser looked like this: ``` parseExpRec e1 (op : ts) = let (e2, ts') = parsePrimExp ts in case op of T_Plus -> parseExpRec (BinOpApp Plus e1 e2) ts' T_Minus -> parseExpRec (BinOpApp Minus e1 e2) ts' T_Times -> parseExpRec (BinOpApp Times e1 e2) ts' T_Divide -> parseExpRec (BinOpApp Divide e1 e2) ts' _ -> (e1, op : ts) ``` T\_Plus etc. are members of the Token datatype, and Plus, Minus etc. are part of BinOp which BinOpApp applies to two operands. I have updated the Token and BinOpApp datatypes to handle the Power (exponentiation) token. This is the resulting code: ``` parseExpRec e1 (op : ts) = let (e2, ts') = parsePrimExp ts in case op of T_Plus -> parseExpRec (BinOpApp Plus e1 e2) ts' T_Minus -> parseExpRec (BinOpApp Minus e1 e2) ts' T_Times -> parseExpRec (BinOpApp Times e1 e2) ts' T_Divide -> parseExpRec (BinOpApp Divide e1 e2) ts' T_Power -> parseExpRec (BinOpApp Power e1 e2) ts' _ -> (e1, op : ts) ``` This seems simple but it's now giving the following error: > > TXL.hs:182:13: parse error on input '->' > > > Line 182 is the line where I added "T\_Power -> parseExpRec..." - I don't see how it's any different from the other lines, which parse fine. I'm using GHCi as my environment.
2010/02/24
[ "https://Stackoverflow.com/questions/2325824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49128/" ]
Have you indented the new line with the same space-delimiters as the previous ones? Or, has a tab character snuck in there?
This is almost with 100% certainty an indentation error. I've had similar problems in the past, also when writing a parser. What's probably happened is the lines before the problematic line are indented with tabs, and you've used spaces on the T\_Power line (or something similar). Can you turn on non-printed characters in your editor?
56,566,451
I created string that contains numbers by calling string.Join on a byte array: ``` string str = string.Join(", ", arr); ``` (arr is a byte array). How can I turn the string back to a byte array?
2019/06/12
[ "https://Stackoverflow.com/questions/56566451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11554082/" ]
You can use `String.Split` and then `Byte.Parse` to parse the string, eg : ``` var newArray = str.Split(',').Select(Byte.Parse).ToArray(); ``` `Byte.Parse` ignores whitespace so there's no need to trim If you create the array like this : ``` var str = String.Join(", ", new byte[]{0xFF,0x05,0x56}); ``` The new array produced by splitting: ``` var newArray = Split(',').Select(Byte.Parse).ToArray(); ``` Will contain the values 255, 5 and 86.
Assuming your string looks like "1,2,3,4" `var numArray = str.Split(',').Select(s => Byte.Parse(s)).ToArray();` Runnable: <https://rextester.com/XOMQ99840>
34,809,053
I have this query: ``` select id, count(1) as "visits", count(distinct visitor_id) as "visitors" from my_table where timestamp > '2016-01-14' group by id order by "visits", "visitors" ``` It works. If I change to this ``` select id, count(1) as "visits", count(distinct visitor_id) as "visitors" from my_table where timestamp > '2016-01-14' group by id order by (("visits") + ("visitors")) ``` I get > > column "visits" does not exist > > > If I change to select id, count(1) as "visits", count(distinct visitor\_id) as "visitors" from my\_table where timestamp > '2016-01-14' group by id order by count(1) + count(distinct visitor\_id) it works again. Why does it work for example 1 and 3, but not for example 2? Is there any way to order by the sum of two column using their aliases? The alternatives I could think of: * Create an outer select and order it, but that would create extra code and I would like to avoid that * Recalculate the values in the order by statement. But that would make the query more complex and maybe I would lose performance due to recalculating stuff. PS: This query is a toy-query. The real one is much more complicated. I would like to reuse the value calculated in the select statement in the order by, but all summed up together.
2016/01/15
[ "https://Stackoverflow.com/questions/34809053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/504331/" ]
Expression evaluation order is not defined. If your `visits + visitors` expression is evaluated before aliases you will get the error shown here above.
Instead of using the alias try using the actual column also try change the type to varchar or nvarchar, and by that I mean the following: ``` select id, count(1) as "visits", count(distinct visitor_id) as "visitors" from my_table where timestamp > '2016-01-14' group by id order by (CAST(count(1) AS VARCHAR) + CAST(count(distinct visitor_id) AS VARCHAR)) ```
22,416
I need to delete 200 Drupal commerce orders. Is there any way to do this in a bulk action? Orders are at: **/admin/commerce/orders** Same with Customer profiles. I need to delete them with a bulk action. Can I accomplish with this? Customer profiles are at: **/admin/commerce/customer-profiles/list**
2012/02/13
[ "https://drupal.stackexchange.com/questions/22416", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/1352/" ]
There is a module for that™ With [Commerce VBO views](http://drupal.org/project/commerce_vbo_views) you can create a view where you can mass delete orders and products. I don't know about customer profiles, but that could be a feature request if it's not added yet.
[Commerce Order Cleanup](https://www.drupal.org/project/commerce_order_cleanup) is another attempt on this front: > > Allows to cleanup the orders by various order properties like last changed, status. > > >
22,416
I need to delete 200 Drupal commerce orders. Is there any way to do this in a bulk action? Orders are at: **/admin/commerce/orders** Same with Customer profiles. I need to delete them with a bulk action. Can I accomplish with this? Customer profiles are at: **/admin/commerce/customer-profiles/list**
2012/02/13
[ "https://drupal.stackexchange.com/questions/22416", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/1352/" ]
If you've got 65,000 orders that you need to wipe, VBO isn't an option. You can try this: ``` TRUNCATE commerce_customer_profile; TRUNCATE commerce_customer_profile_revision; TRUNCATE commerce_funds_transactions; TRUNCATE commerce_funds_user_funds; TRUNCATE commerce_line_item; TRUNCATE commerce_order; TRUNCATE commerce_order_revision; TRUNCATE commerce_payment_transaction; TRUNCATE commerce_payment_transaction_revision; TRUNCATE commerce_paypal_ipn; TRUNCATE field_data_commerce_customer_address; TRUNCATE field_data_commerce_customer_billing; TRUNCATE field_data_commerce_customer_shipping; TRUNCATE field_data_commerce_line_items; TRUNCATE field_data_commerce_order_total; TRUNCATE field_data_commerce_price; TRUNCATE field_data_commerce_product; TRUNCATE field_data_commerce_shipping_service; TRUNCATE field_data_commerce_total; TRUNCATE field_data_commerce_unit_price; TRUNCATE field_data_commerce_coupon_order_reference; TRUNCATE field_data_commerce_display_path; TRUNCATE field_data_field_order_deliveryinstructions; TRUNCATE field_data_field_order_flags; TRUNCATE field_data_field_order_id; TRUNCATE field_data_field_order_notes; TRUNCATE field_data_field_supplier; TRUNCATE field_revision_commerce_customer_address; TRUNCATE field_revision_commerce_customer_billing; TRUNCATE field_revision_commerce_customer_shipping; TRUNCATE field_revision_commerce_line_items; TRUNCATE field_revision_commerce_order_total; TRUNCATE field_revision_commerce_price; TRUNCATE field_revision_commerce_product; TRUNCATE field_revision_commerce_shipping_service; TRUNCATE field_revision_commerce_total; TRUNCATE field_revision_commerce_unit_price; TRUNCATE field_revision_commerce_coupon_order_reference; TRUNCATE field_revision_commerce_display_path; TRUNCATE field_revision_field_order_deliveryinstructions; TRUNCATE field_revision_field_order_flags; TRUNCATE field_revision_field_order_id; TRUNCATE field_revision_field_order_notes; TRUNCATE field_revision_field_supplier; ```
[Commerce Order Cleanup](https://www.drupal.org/project/commerce_order_cleanup) is another attempt on this front: > > Allows to cleanup the orders by various order properties like last changed, status. > > >
26,635,976
Imagine you have a product page. On this page there are two select inputs with options in them. There is one for Size and Colour. This can change depending on the product, e.g. a curtain might have a size, length and colour (three select menus). The array is created dynamically (based on each select menu and its options): ``` var dynamicArr = [], i, j, opt, $('.select'); for (i = 0; i < select.length; i += 1) { opt = select.eq(i).find('option'); if (dynamicArr[i] === undefined) { dynamicArr[i] = []; } for (j = 0; j < opt.length; j += 1) { dynamicArr[i].push(opt.eq(j)); } } ``` Imagine the page had a size and colour drop-down. The above would create an array like this: ``` dynamicArr = [['size'], ['color']] ``` I want to loop through each of these separately (in order to get individual values and compare them). **My problem starts here. A dynamic array might have a length of 1, 2, 3, 4, 5, 6 (depending on the select options on the page). I therefore can't do this as there won't always be two selects** ``` for (i = 0; i < dynamicArr[0].length; i += 1) { } for (i = 0; i < dynamicArr[1].length; i += 1) { } ``` How would I go about finding out the length and looping individually like the above e.g. if there are three selects, it will automatically know there are this many and loop through them like above. If you are still confused, let me know. Thanks.
2014/10/29
[ "https://Stackoverflow.com/questions/26635976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3397052/" ]
You can always use [`Array.forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) ``` dynamicArr.forEach(function(el){ console.log(el); }); ```
I hope I didn't get you wrong, but here's a solution: ``` for(i = 0; i < dynamicArr.length; i++) { for(j = 0; j < dynamicArr[i].length; j++) { // do something here.. } } ```
26,635,976
Imagine you have a product page. On this page there are two select inputs with options in them. There is one for Size and Colour. This can change depending on the product, e.g. a curtain might have a size, length and colour (three select menus). The array is created dynamically (based on each select menu and its options): ``` var dynamicArr = [], i, j, opt, $('.select'); for (i = 0; i < select.length; i += 1) { opt = select.eq(i).find('option'); if (dynamicArr[i] === undefined) { dynamicArr[i] = []; } for (j = 0; j < opt.length; j += 1) { dynamicArr[i].push(opt.eq(j)); } } ``` Imagine the page had a size and colour drop-down. The above would create an array like this: ``` dynamicArr = [['size'], ['color']] ``` I want to loop through each of these separately (in order to get individual values and compare them). **My problem starts here. A dynamic array might have a length of 1, 2, 3, 4, 5, 6 (depending on the select options on the page). I therefore can't do this as there won't always be two selects** ``` for (i = 0; i < dynamicArr[0].length; i += 1) { } for (i = 0; i < dynamicArr[1].length; i += 1) { } ``` How would I go about finding out the length and looping individually like the above e.g. if there are three selects, it will automatically know there are this many and loop through them like above. If you are still confused, let me know. Thanks.
2014/10/29
[ "https://Stackoverflow.com/questions/26635976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3397052/" ]
You can always use [`Array.forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) ``` dynamicArr.forEach(function(el){ console.log(el); }); ```
you should try something like this: `dyn.forEach(function(el){//dyn is the dynamic array console.log(el); //logs to console });`
3,710,263
I have a Sqlite 3 and/or MySQL table named "clients".. Using python 2.6, How do I create a csv file named Clients100914.csv with headers? excel dialect... The Sql execute: select \* only gives table data, but I would like complete table with headers. How do I create a record set to get table headers. The table headers should come directly from sql not written in python. ``` w = csv.writer(open(Fn,'wb'),dialect='excel') #w.writelines("header_row") #Fetch into sqld w.writerows(sqld) ``` This code leaves me with file open and no headers. Also cant get figure out how to use file as log.
2010/09/14
[ "https://Stackoverflow.com/questions/3710263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428862/" ]
You can easily create it manually, writing a file with a chosen separator. You can also use [csv module](http://docs.python.org/library/csv.html). If it's from database you can alo just use a query from your sqlite client : ``` sqlite <db params> < queryfile.sql > output.csv ``` Which will create a csv file with tab separator.
unless i'm missing something, you just want to do something like so... ``` f = open("somefile.csv") f.writelines("header_row") ``` logic to write lines to file (you may need to organize values and add comms or pipes etc...) ``` f.close() ```
3,710,263
I have a Sqlite 3 and/or MySQL table named "clients".. Using python 2.6, How do I create a csv file named Clients100914.csv with headers? excel dialect... The Sql execute: select \* only gives table data, but I would like complete table with headers. How do I create a record set to get table headers. The table headers should come directly from sql not written in python. ``` w = csv.writer(open(Fn,'wb'),dialect='excel') #w.writelines("header_row") #Fetch into sqld w.writerows(sqld) ``` This code leaves me with file open and no headers. Also cant get figure out how to use file as log.
2010/09/14
[ "https://Stackoverflow.com/questions/3710263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428862/" ]
``` import csv import sqlite3 from glob import glob; from os.path import expanduser conn = sqlite3.connect( # open "places.sqlite" from one of the Firefox profiles glob(expanduser('~/.mozilla/firefox/*/places.sqlite'))[0] ) cursor = conn.cursor() cursor.execute("select * from moz_places;") with open("out.csv", "w", newline='') as csv_file: # Python 3 version #with open("out.csv", "wb") as csv_file: # Python 2 version csv_writer = csv.writer(csv_file) csv_writer.writerow([i[0] for i in cursor.description]) # write headers csv_writer.writerows(cursor) ``` [PEP 249 (DB API 2.0)](http://www.python.org/dev/peps/pep-0249/#description) has more information about `cursor.description`.
You can easily create it manually, writing a file with a chosen separator. You can also use [csv module](http://docs.python.org/library/csv.html). If it's from database you can alo just use a query from your sqlite client : ``` sqlite <db params> < queryfile.sql > output.csv ``` Which will create a csv file with tab separator.
3,710,263
I have a Sqlite 3 and/or MySQL table named "clients".. Using python 2.6, How do I create a csv file named Clients100914.csv with headers? excel dialect... The Sql execute: select \* only gives table data, but I would like complete table with headers. How do I create a record set to get table headers. The table headers should come directly from sql not written in python. ``` w = csv.writer(open(Fn,'wb'),dialect='excel') #w.writelines("header_row") #Fetch into sqld w.writerows(sqld) ``` This code leaves me with file open and no headers. Also cant get figure out how to use file as log.
2010/09/14
[ "https://Stackoverflow.com/questions/3710263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428862/" ]
Using the [csv module](http://docs.python.org/library/csv.html) is very straight forward and made for this task. ``` import csv writer = csv.writer(open("out.csv", 'w')) writer.writerow(['name', 'address', 'phone', 'etc']) writer.writerow(['bob', '2 main st', '703', 'yada']) writer.writerow(['mary', '3 main st', '704', 'yada']) ``` Creates exactly the format you're expecting.
It can be easily done using pandas and sqlite3. In extension to the answer from Cristian Ciupitu. ``` import sqlite3 from glob import glob; from os.path import expanduser conn = sqlite3.connect(glob(expanduser('data/clients_data.sqlite'))[0]) cursor = conn.cursor() ``` Now use pandas to read the table and write to csv. ``` clients = pd.read_sql('SELECT * FROM clients' ,conn) clients.to_csv('data/Clients100914.csv', index=False) ``` This is more direct and works all the time.
3,710,263
I have a Sqlite 3 and/or MySQL table named "clients".. Using python 2.6, How do I create a csv file named Clients100914.csv with headers? excel dialect... The Sql execute: select \* only gives table data, but I would like complete table with headers. How do I create a record set to get table headers. The table headers should come directly from sql not written in python. ``` w = csv.writer(open(Fn,'wb'),dialect='excel') #w.writelines("header_row") #Fetch into sqld w.writerows(sqld) ``` This code leaves me with file open and no headers. Also cant get figure out how to use file as log.
2010/09/14
[ "https://Stackoverflow.com/questions/3710263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428862/" ]
You can easily create it manually, writing a file with a chosen separator. You can also use [csv module](http://docs.python.org/library/csv.html). If it's from database you can alo just use a query from your sqlite client : ``` sqlite <db params> < queryfile.sql > output.csv ``` Which will create a csv file with tab separator.
**How to extract the column headings from an existing table:** *You don't need to parse an SQL "create table" statement.* This is fortunate, as the "create table" syntax is neither nice nor clean, it is warthog-ugly. You can use the [`table_info`](http://www.sqlite.org/pragma.html#pragma_table_info) pragma. It gives you useful information about each column in a table, including the name of the column. Example: ``` >>> #coding: ascii ... import sqlite3 >>> >>> def get_col_names(cursor, table_name): ... results = cursor.execute("PRAGMA table_info(%s);" % table_name) ... return [row[1] for row in results] ... >>> def wrong_way(cur, table): ... import re ... cur.execute("SELECT sql FROM sqlite_master WHERE name=?;", (table, )) ... sql = cur.fetchone()[0] ... column_defs = re.findall("[(](.*)[)]", sql)[0] ... first_words = (line.split()[0].strip() for line in column_defs.split(',')) ... columns = [word for word in first_words if word.upper() != "CONSTRAINT"] ... return columns ... >>> conn = sqlite3.connect(":memory:") >>> curs = conn.cursor() >>> _ignored = curs.execute( ... "create table foo (id integer, name text, [haha gotcha] text);" ... ) >>> print get_col_names(curs, "foo") [u'id', u'name', u'haha gotcha'] >>> print wrong_way(curs, "foo") [u'id', u'name', u'[haha'] <<<<<===== WHOOPS! >>> ``` Other problems with the now-deleted "parse the create table SQL" answer: 1. Stuffs up with e.g. `create table test (id1 text, id2 int, msg text, primary key(id1, id2))` ... needs to ignore not only `CONSTRAINT`, but also keywords `PRIMARY`, `UNIQUE`, `CHECK` and `FOREIGN` (see the [`create table`](http://www.sqlite.org/lang_createtable.html) docs). 2. Needs to specify [`re.DOTALL`](https://docs.python.org/library/re.html#re.DOTALL) in case there are newlines in the SQL. 3. In `line.split()[0].strip()` the `strip` is redundant.
3,710,263
I have a Sqlite 3 and/or MySQL table named "clients".. Using python 2.6, How do I create a csv file named Clients100914.csv with headers? excel dialect... The Sql execute: select \* only gives table data, but I would like complete table with headers. How do I create a record set to get table headers. The table headers should come directly from sql not written in python. ``` w = csv.writer(open(Fn,'wb'),dialect='excel') #w.writelines("header_row") #Fetch into sqld w.writerows(sqld) ``` This code leaves me with file open and no headers. Also cant get figure out how to use file as log.
2010/09/14
[ "https://Stackoverflow.com/questions/3710263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428862/" ]
You can easily create it manually, writing a file with a chosen separator. You can also use [csv module](http://docs.python.org/library/csv.html). If it's from database you can alo just use a query from your sqlite client : ``` sqlite <db params> < queryfile.sql > output.csv ``` Which will create a csv file with tab separator.
It can be easily done using pandas and sqlite3. In extension to the answer from Cristian Ciupitu. ``` import sqlite3 from glob import glob; from os.path import expanduser conn = sqlite3.connect(glob(expanduser('data/clients_data.sqlite'))[0]) cursor = conn.cursor() ``` Now use pandas to read the table and write to csv. ``` clients = pd.read_sql('SELECT * FROM clients' ,conn) clients.to_csv('data/Clients100914.csv', index=False) ``` This is more direct and works all the time.
3,710,263
I have a Sqlite 3 and/or MySQL table named "clients".. Using python 2.6, How do I create a csv file named Clients100914.csv with headers? excel dialect... The Sql execute: select \* only gives table data, but I would like complete table with headers. How do I create a record set to get table headers. The table headers should come directly from sql not written in python. ``` w = csv.writer(open(Fn,'wb'),dialect='excel') #w.writelines("header_row") #Fetch into sqld w.writerows(sqld) ``` This code leaves me with file open and no headers. Also cant get figure out how to use file as log.
2010/09/14
[ "https://Stackoverflow.com/questions/3710263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428862/" ]
Using the [csv module](http://docs.python.org/library/csv.html) is very straight forward and made for this task. ``` import csv writer = csv.writer(open("out.csv", 'w')) writer.writerow(['name', 'address', 'phone', 'etc']) writer.writerow(['bob', '2 main st', '703', 'yada']) writer.writerow(['mary', '3 main st', '704', 'yada']) ``` Creates exactly the format you're expecting.
This is simple and works fine for me. Lets say you have already connected to your database table and also got a cursor object. So following on on from that point. ``` import csv curs = conn.cursor() curs.execute("select * from oders") m_dict = list(curs.fetchall()) with open("mycsvfile.csv", "wb") as f: w = csv.DictWriter(f, m_dict[0].keys()) w.writerow(dict((fn,fn) for fn in m_dict[0].keys())) w.writerows(m_dict) ```
3,710,263
I have a Sqlite 3 and/or MySQL table named "clients".. Using python 2.6, How do I create a csv file named Clients100914.csv with headers? excel dialect... The Sql execute: select \* only gives table data, but I would like complete table with headers. How do I create a record set to get table headers. The table headers should come directly from sql not written in python. ``` w = csv.writer(open(Fn,'wb'),dialect='excel') #w.writelines("header_row") #Fetch into sqld w.writerows(sqld) ``` This code leaves me with file open and no headers. Also cant get figure out how to use file as log.
2010/09/14
[ "https://Stackoverflow.com/questions/3710263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428862/" ]
``` import csv import sqlite3 from glob import glob; from os.path import expanduser conn = sqlite3.connect( # open "places.sqlite" from one of the Firefox profiles glob(expanduser('~/.mozilla/firefox/*/places.sqlite'))[0] ) cursor = conn.cursor() cursor.execute("select * from moz_places;") with open("out.csv", "w", newline='') as csv_file: # Python 3 version #with open("out.csv", "wb") as csv_file: # Python 2 version csv_writer = csv.writer(csv_file) csv_writer.writerow([i[0] for i in cursor.description]) # write headers csv_writer.writerows(cursor) ``` [PEP 249 (DB API 2.0)](http://www.python.org/dev/peps/pep-0249/#description) has more information about `cursor.description`.
**How to extract the column headings from an existing table:** *You don't need to parse an SQL "create table" statement.* This is fortunate, as the "create table" syntax is neither nice nor clean, it is warthog-ugly. You can use the [`table_info`](http://www.sqlite.org/pragma.html#pragma_table_info) pragma. It gives you useful information about each column in a table, including the name of the column. Example: ``` >>> #coding: ascii ... import sqlite3 >>> >>> def get_col_names(cursor, table_name): ... results = cursor.execute("PRAGMA table_info(%s);" % table_name) ... return [row[1] for row in results] ... >>> def wrong_way(cur, table): ... import re ... cur.execute("SELECT sql FROM sqlite_master WHERE name=?;", (table, )) ... sql = cur.fetchone()[0] ... column_defs = re.findall("[(](.*)[)]", sql)[0] ... first_words = (line.split()[0].strip() for line in column_defs.split(',')) ... columns = [word for word in first_words if word.upper() != "CONSTRAINT"] ... return columns ... >>> conn = sqlite3.connect(":memory:") >>> curs = conn.cursor() >>> _ignored = curs.execute( ... "create table foo (id integer, name text, [haha gotcha] text);" ... ) >>> print get_col_names(curs, "foo") [u'id', u'name', u'haha gotcha'] >>> print wrong_way(curs, "foo") [u'id', u'name', u'[haha'] <<<<<===== WHOOPS! >>> ``` Other problems with the now-deleted "parse the create table SQL" answer: 1. Stuffs up with e.g. `create table test (id1 text, id2 int, msg text, primary key(id1, id2))` ... needs to ignore not only `CONSTRAINT`, but also keywords `PRIMARY`, `UNIQUE`, `CHECK` and `FOREIGN` (see the [`create table`](http://www.sqlite.org/lang_createtable.html) docs). 2. Needs to specify [`re.DOTALL`](https://docs.python.org/library/re.html#re.DOTALL) in case there are newlines in the SQL. 3. In `line.split()[0].strip()` the `strip` is redundant.
3,710,263
I have a Sqlite 3 and/or MySQL table named "clients".. Using python 2.6, How do I create a csv file named Clients100914.csv with headers? excel dialect... The Sql execute: select \* only gives table data, but I would like complete table with headers. How do I create a record set to get table headers. The table headers should come directly from sql not written in python. ``` w = csv.writer(open(Fn,'wb'),dialect='excel') #w.writelines("header_row") #Fetch into sqld w.writerows(sqld) ``` This code leaves me with file open and no headers. Also cant get figure out how to use file as log.
2010/09/14
[ "https://Stackoverflow.com/questions/3710263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428862/" ]
**How to extract the column headings from an existing table:** *You don't need to parse an SQL "create table" statement.* This is fortunate, as the "create table" syntax is neither nice nor clean, it is warthog-ugly. You can use the [`table_info`](http://www.sqlite.org/pragma.html#pragma_table_info) pragma. It gives you useful information about each column in a table, including the name of the column. Example: ``` >>> #coding: ascii ... import sqlite3 >>> >>> def get_col_names(cursor, table_name): ... results = cursor.execute("PRAGMA table_info(%s);" % table_name) ... return [row[1] for row in results] ... >>> def wrong_way(cur, table): ... import re ... cur.execute("SELECT sql FROM sqlite_master WHERE name=?;", (table, )) ... sql = cur.fetchone()[0] ... column_defs = re.findall("[(](.*)[)]", sql)[0] ... first_words = (line.split()[0].strip() for line in column_defs.split(',')) ... columns = [word for word in first_words if word.upper() != "CONSTRAINT"] ... return columns ... >>> conn = sqlite3.connect(":memory:") >>> curs = conn.cursor() >>> _ignored = curs.execute( ... "create table foo (id integer, name text, [haha gotcha] text);" ... ) >>> print get_col_names(curs, "foo") [u'id', u'name', u'haha gotcha'] >>> print wrong_way(curs, "foo") [u'id', u'name', u'[haha'] <<<<<===== WHOOPS! >>> ``` Other problems with the now-deleted "parse the create table SQL" answer: 1. Stuffs up with e.g. `create table test (id1 text, id2 int, msg text, primary key(id1, id2))` ... needs to ignore not only `CONSTRAINT`, but also keywords `PRIMARY`, `UNIQUE`, `CHECK` and `FOREIGN` (see the [`create table`](http://www.sqlite.org/lang_createtable.html) docs). 2. Needs to specify [`re.DOTALL`](https://docs.python.org/library/re.html#re.DOTALL) in case there are newlines in the SQL. 3. In `line.split()[0].strip()` the `strip` is redundant.
unless i'm missing something, you just want to do something like so... ``` f = open("somefile.csv") f.writelines("header_row") ``` logic to write lines to file (you may need to organize values and add comms or pipes etc...) ``` f.close() ```
3,710,263
I have a Sqlite 3 and/or MySQL table named "clients".. Using python 2.6, How do I create a csv file named Clients100914.csv with headers? excel dialect... The Sql execute: select \* only gives table data, but I would like complete table with headers. How do I create a record set to get table headers. The table headers should come directly from sql not written in python. ``` w = csv.writer(open(Fn,'wb'),dialect='excel') #w.writelines("header_row") #Fetch into sqld w.writerows(sqld) ``` This code leaves me with file open and no headers. Also cant get figure out how to use file as log.
2010/09/14
[ "https://Stackoverflow.com/questions/3710263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428862/" ]
This is simple and works fine for me. Lets say you have already connected to your database table and also got a cursor object. So following on on from that point. ``` import csv curs = conn.cursor() curs.execute("select * from oders") m_dict = list(curs.fetchall()) with open("mycsvfile.csv", "wb") as f: w = csv.DictWriter(f, m_dict[0].keys()) w.writerow(dict((fn,fn) for fn in m_dict[0].keys())) w.writerows(m_dict) ```
It can be easily done using pandas and sqlite3. In extension to the answer from Cristian Ciupitu. ``` import sqlite3 from glob import glob; from os.path import expanduser conn = sqlite3.connect(glob(expanduser('data/clients_data.sqlite'))[0]) cursor = conn.cursor() ``` Now use pandas to read the table and write to csv. ``` clients = pd.read_sql('SELECT * FROM clients' ,conn) clients.to_csv('data/Clients100914.csv', index=False) ``` This is more direct and works all the time.
3,710,263
I have a Sqlite 3 and/or MySQL table named "clients".. Using python 2.6, How do I create a csv file named Clients100914.csv with headers? excel dialect... The Sql execute: select \* only gives table data, but I would like complete table with headers. How do I create a record set to get table headers. The table headers should come directly from sql not written in python. ``` w = csv.writer(open(Fn,'wb'),dialect='excel') #w.writelines("header_row") #Fetch into sqld w.writerows(sqld) ``` This code leaves me with file open and no headers. Also cant get figure out how to use file as log.
2010/09/14
[ "https://Stackoverflow.com/questions/3710263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428862/" ]
Using the [csv module](http://docs.python.org/library/csv.html) is very straight forward and made for this task. ``` import csv writer = csv.writer(open("out.csv", 'w')) writer.writerow(['name', 'address', 'phone', 'etc']) writer.writerow(['bob', '2 main st', '703', 'yada']) writer.writerow(['mary', '3 main st', '704', 'yada']) ``` Creates exactly the format you're expecting.
The below code works for Oracle with Python 3.6 : ``` import cx_Oracle import csv # Create tns dsn_tns=cx_Oracle.makedsn('<host>', '<port>', service_name='<service_name>') # Connect to DB using user, password and tns settings conn=cx_Oracle.connect(user='<user>', password='<pass>',dsn=dsn_tns) c=conn.cursor() #Execute the Query c.execute("select * from <table>") # Write results into CSV file with open("<file>.csv", "w", newline='') as csv_file: csv_writer = csv.writer(csv_file) csv_writer.writerow([i[0] for i in c.description]) # write headers csv_writer.writerows(c) ```
2,415,651
In Ruby, there are currently 3 ODM (object data mappers) maintained: * [MongoMapper](https://github.com/jnunemaker/mongomapper) * [Mongoid](https://github.com/mongodb/mongoid) * [MongoDoc](https://github.com/leshill/mongodoc) Which is your preferred and why?
2010/03/10
[ "https://Stackoverflow.com/questions/2415651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/285289/" ]
I just chose Mongoid for a new Rails 3 project based on the argument that it has the best documentation. Since I am new to MongoDB (with many years of MySQL and a little bit of CouchDB experience), I needed good guides that take me by the hand and help me deliver something working within a reasonable span of time. AFAIK Mongoid has just that: a nice looking site, with well documented guides for newbies like me.
While not a direct answer to your question, I would also consider using the basic ruby driver directly. Unlike the various SQL adapters out there Mongo's ruby class is easy to use and powerful. Because queries are hashes, composing queries is generally easy. The real advantage is access to the [Atomic Modifiers](http://www.mongodb.org/display/DOCS/Updating). If you benefit from a Document database, these modifiers should be in your toolbox. Having said this, I will go ahead and recommend MongoMapper because it has cleaner integration with the non-CRUD parts of MongoDB. Both projects are making gains in this area, and the situation may have changes since I did my research in December 2010.
2,415,651
In Ruby, there are currently 3 ODM (object data mappers) maintained: * [MongoMapper](https://github.com/jnunemaker/mongomapper) * [Mongoid](https://github.com/mongodb/mongoid) * [MongoDoc](https://github.com/leshill/mongodoc) Which is your preferred and why?
2010/03/10
[ "https://Stackoverflow.com/questions/2415651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/285289/" ]
I just chose Mongoid for a new Rails 3 project based on the argument that it has the best documentation. Since I am new to MongoDB (with many years of MySQL and a little bit of CouchDB experience), I needed good guides that take me by the hand and help me deliver something working within a reasonable span of time. AFAIK Mongoid has just that: a nice looking site, with well documented guides for newbies like me.
Code Stats for Mongoid and MongoMapper ![enter image description here](https://i.stack.imgur.com/Xlmkh.png) It looks like MongoMapper has much better code quality (if it does the same with less). Here's the analyzer CodeStats <https://github.com/alexeypetrushin/code_stats>
2,415,651
In Ruby, there are currently 3 ODM (object data mappers) maintained: * [MongoMapper](https://github.com/jnunemaker/mongomapper) * [Mongoid](https://github.com/mongodb/mongoid) * [MongoDoc](https://github.com/leshill/mongodoc) Which is your preferred and why?
2010/03/10
[ "https://Stackoverflow.com/questions/2415651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/285289/" ]
Code Stats for Mongoid and MongoMapper ![enter image description here](https://i.stack.imgur.com/Xlmkh.png) It looks like MongoMapper has much better code quality (if it does the same with less). Here's the analyzer CodeStats <https://github.com/alexeypetrushin/code_stats>
There's also MongodbModel <http://alexeypetrushin.github.com/mongodb_model>
2,415,651
In Ruby, there are currently 3 ODM (object data mappers) maintained: * [MongoMapper](https://github.com/jnunemaker/mongomapper) * [Mongoid](https://github.com/mongodb/mongoid) * [MongoDoc](https://github.com/leshill/mongodoc) Which is your preferred and why?
2010/03/10
[ "https://Stackoverflow.com/questions/2415651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/285289/" ]
I was trying MongoMapper, but I think I'll go with Mongoid, because after quick reading docs it seems to me somewhat easier. Plus, it's developed by guys from Hashrocket, so that's a good reason itself.
There's also MongodbModel <http://alexeypetrushin.github.com/mongodb_model>
2,415,651
In Ruby, there are currently 3 ODM (object data mappers) maintained: * [MongoMapper](https://github.com/jnunemaker/mongomapper) * [Mongoid](https://github.com/mongodb/mongoid) * [MongoDoc](https://github.com/leshill/mongodoc) Which is your preferred and why?
2010/03/10
[ "https://Stackoverflow.com/questions/2415651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/285289/" ]
I was trying MongoMapper, but I think I'll go with Mongoid, because after quick reading docs it seems to me somewhat easier. Plus, it's developed by guys from Hashrocket, so that's a good reason itself.
I can recommend MongoMapper, since it also works with rails3 (beta and master). I personally didn't try the other 2 mappers you mentioned, since MM works great in my workflow and the mailinglist is very active. Furthermore the codebase is really stable and the only issue is with rails3 master, so you should use fredwu's branch, which already includes fixes for the current rails3 master changes on form\_for: <http://github.com/fredwu/mongomapper.git>
2,415,651
In Ruby, there are currently 3 ODM (object data mappers) maintained: * [MongoMapper](https://github.com/jnunemaker/mongomapper) * [Mongoid](https://github.com/mongodb/mongoid) * [MongoDoc](https://github.com/leshill/mongodoc) Which is your preferred and why?
2010/03/10
[ "https://Stackoverflow.com/questions/2415651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/285289/" ]
In my opinion it's hard to say which is better, if you have DataMapper experience you'll like MongoMapper, but if you used ActiveRecord, Mongoid it's your preferred choice. I believe all of them worths a try concerning the context where you want to use them.
I can recommend MongoMapper, since it also works with rails3 (beta and master). I personally didn't try the other 2 mappers you mentioned, since MM works great in my workflow and the mailinglist is very active. Furthermore the codebase is really stable and the only issue is with rails3 master, so you should use fredwu's branch, which already includes fixes for the current rails3 master changes on form\_for: <http://github.com/fredwu/mongomapper.git>
2,415,651
In Ruby, there are currently 3 ODM (object data mappers) maintained: * [MongoMapper](https://github.com/jnunemaker/mongomapper) * [Mongoid](https://github.com/mongodb/mongoid) * [MongoDoc](https://github.com/leshill/mongodoc) Which is your preferred and why?
2010/03/10
[ "https://Stackoverflow.com/questions/2415651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/285289/" ]
I am using MongoMapper. It good except it is little slow with Time conversions. And it loads all data as Array. `MyCollection.all` for example gives you huge array, not cursor. while Mongoid says: - Optimized for use with extremely large datasets. So I guess you could try MongoID if you need speed and have big recordsets.
There's also MongodbModel <http://alexeypetrushin.github.com/mongodb_model>
2,415,651
In Ruby, there are currently 3 ODM (object data mappers) maintained: * [MongoMapper](https://github.com/jnunemaker/mongomapper) * [Mongoid](https://github.com/mongodb/mongoid) * [MongoDoc](https://github.com/leshill/mongodoc) Which is your preferred and why?
2010/03/10
[ "https://Stackoverflow.com/questions/2415651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/285289/" ]
I just chose Mongoid for a new Rails 3 project based on the argument that it has the best documentation. Since I am new to MongoDB (with many years of MySQL and a little bit of CouchDB experience), I needed good guides that take me by the hand and help me deliver something working within a reasonable span of time. AFAIK Mongoid has just that: a nice looking site, with well documented guides for newbies like me.
I was trying MongoMapper, but I think I'll go with Mongoid, because after quick reading docs it seems to me somewhat easier. Plus, it's developed by guys from Hashrocket, so that's a good reason itself.
2,415,651
In Ruby, there are currently 3 ODM (object data mappers) maintained: * [MongoMapper](https://github.com/jnunemaker/mongomapper) * [Mongoid](https://github.com/mongodb/mongoid) * [MongoDoc](https://github.com/leshill/mongodoc) Which is your preferred and why?
2010/03/10
[ "https://Stackoverflow.com/questions/2415651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/285289/" ]
I am using MongoMapper. It good except it is little slow with Time conversions. And it loads all data as Array. `MyCollection.all` for example gives you huge array, not cursor. while Mongoid says: - Optimized for use with extremely large datasets. So I guess you could try MongoID if you need speed and have big recordsets.
I can recommend MongoMapper, since it also works with rails3 (beta and master). I personally didn't try the other 2 mappers you mentioned, since MM works great in my workflow and the mailinglist is very active. Furthermore the codebase is really stable and the only issue is with rails3 master, so you should use fredwu's branch, which already includes fixes for the current rails3 master changes on form\_for: <http://github.com/fredwu/mongomapper.git>
2,415,651
In Ruby, there are currently 3 ODM (object data mappers) maintained: * [MongoMapper](https://github.com/jnunemaker/mongomapper) * [Mongoid](https://github.com/mongodb/mongoid) * [MongoDoc](https://github.com/leshill/mongodoc) Which is your preferred and why?
2010/03/10
[ "https://Stackoverflow.com/questions/2415651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/285289/" ]
I just chose Mongoid for a new Rails 3 project based on the argument that it has the best documentation. Since I am new to MongoDB (with many years of MySQL and a little bit of CouchDB experience), I needed good guides that take me by the hand and help me deliver something working within a reasonable span of time. AFAIK Mongoid has just that: a nice looking site, with well documented guides for newbies like me.
I can recommend MongoMapper, since it also works with rails3 (beta and master). I personally didn't try the other 2 mappers you mentioned, since MM works great in my workflow and the mailinglist is very active. Furthermore the codebase is really stable and the only issue is with rails3 master, so you should use fredwu's branch, which already includes fixes for the current rails3 master changes on form\_for: <http://github.com/fredwu/mongomapper.git>
22,936
> > C'est **dans l'ordre des choses**. > > > As I understand it, the sentence above means "that is only natural". In the following sentence, however, this expression seems to carry a different meaning – which has me puzzled. > > Sache que **dans l'ordre des choses**, il nous est bien plus précieux que toi. > > >
2016/11/14
[ "https://french.stackexchange.com/questions/22936", "https://french.stackexchange.com", "https://french.stackexchange.com/users/10416/" ]
You are right, in the first sentence “l'ordre des choses” expresses a natural consequence. “Ordre” has temporal and causative implications. Wiktionary provides the following definition: > > Ce qui arrive, ce qui se passe, sans qu’il soit possible de le discuter, de le refuser. > > > Quite surprisingly, in the second sentence it's used with a much more literal meaning. If all things were ranked according to how precious they are to us, he would come before you (by far). “Ordre” is to be understood as a comparison order, but using “ordre des choses” for a universal, absolute scale of importance in this way sounds very unusual1 and quite literary. – 1. Apparently it was chosen for lack of a better translation that fits the format of subtitles.
### meaning [expressions-françaises](http://www.expressions-francaises.fr/expressions-c/2696-c-est-dans-l-ordre-des-choses.html) : > > Le dictionnaire des expressions et locutions définit l’expression française *c’est dans l’ordre des choses* comme **un événement normal, inévitable et prévisible**. > > > [wordreference](http://www.wordreference.com/fren/c%27est%20dans%20l%27ordre%20des%20choses) : > > that's the way it goes, that's the order of things, nothing to be done about it > > > --- ### Particular sentence > > > > > > Sachez que dans l'ordre des choses, il nous est bien plus précieux que toi. > > > > > > > > > In your particular sentence, the verb *savoir* indicates the speaker is reminding the context, the natural, bounded to happen, order of things. In this context, *"il"* is more valuable than the listener.
53,948,704
I am using Google Cloud Storage Java Api to manage my bucket on Firebase. i have activated the versioning with gsutil using this command : ``` gsutil versioning set on gs://[BUCKET_NAME] ``` After that i tried to delete some files with this java code : ``` com.google.cloud.storage.Bucket bucket = com.google.firebase.cloud.StorageClient.getInstance().bucket(); com.google.cloud.storage.Blob doc = bucket.get(documentPath); log.info("Deleting document info => " + doc.toString()); doc.delete(); ``` Log : Deleting document info => Blob{bucket=[BUCKET\_NAME], name=test.pdf, generation=1545929848902866, size=196220, content-type=application/pdf, metadata=null} This works, but it removes both the live and the archived version of the file. Please how to just delete the live version and conserve the archived one ?
2018/12/27
[ "https://Stackoverflow.com/questions/53948704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6364177/" ]
In the [versioning docs](https://cloud.google.com/storage/docs/object-versioning) they say : > > If you send a delete request with a generation that corresponds to the currently live object, Cloud Storage deletes the object without making an archived copy. > > > So, using `bucket.get('test.pdf');` returns the document and its generation number (you can see it in the log) even if i don't pass the generation number. Solution : ``` @Bean public FirebaseApp provideFirebaseOptions() throws IOException { log.info("INIT FIRBASE"); FirebaseOptions options = new FirebaseOptions.Builder() .setCredentials(GoogleCredentials.fromStream(apiKey.getInputStream())) .setStorageBucket(bucketPath) .build(); return FirebaseApp.initializeApp(options); } // add this bean to provide StorageOptions service @Bean public Storage provideStorageService() throws IOException { log.info("INIT STORAGE"); return StorageOptions.newBuilder() .setCredentials(ImplFirebaseTrampolines.getCredentials(provideFirebaseOptions())) .build() .getService(); } ``` Get and delete the doc : ``` //autowire storage bean private final Storage storage; public StorageService(Storage storage) {this.storage = storage;} ... BlobId blobId = BlobId.of(StorageClient.getInstance().bucket().getName(), documentPath); log.info("Deleting document info => " + blobId.toString()); storage.delete(blobId); ```
You are turning versioning off. The correct command to [enable versioning](https://cloud.google.com/storage/docs/using-object-versioning#enable) is: > > gsutil versioning set **on** gs://[BUCKET\_NAME] > > >
17,809,377
My Quest Spotlight Trial does not connect to DB. When I run the user wizard it always comes: > > > ``` > Cannot load OCI DLL: oci.dll > > ``` > > It is a 64-bit Windows Server / 64 bit Oracle server. I've already installed the 32 bit Oracle client and added the dict to path, but nothing worked. Does someone have a tip for me?
2013/07/23
[ "https://Stackoverflow.com/questions/17809377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2591465/" ]
According to [Spotlight requirements](http://www.quest.com/spotlight-on-oracle/#requirements): > > Note: Spotlight will run on 64-bit versions of the client operating > system with the use of a 32-bit Oracle client. > > > If you have 64-bit server and 32-bit client installed on the same computer it's possible that Spotlight looks for `oci.dll` at wrong Oracle Home. Examine order of Oracle home directories from Universal Installer and place 32-bit home first: 1. Run Oracle Universal Installer 2. Click "Installed Products" button 3. Switch to "Environment" tab 4. Reorder Oracle Homes with arrows on right side and click "Apply"
if you use 64-bit pc, oracle doesn't compatible with it. Oracle doesn't find oci.dll file in 64-bit. Therefore, you can try to change oracle home on the top. As a result of that, home path will change.
17,809,377
My Quest Spotlight Trial does not connect to DB. When I run the user wizard it always comes: > > > ``` > Cannot load OCI DLL: oci.dll > > ``` > > It is a 64-bit Windows Server / 64 bit Oracle server. I've already installed the 32 bit Oracle client and added the dict to path, but nothing worked. Does someone have a tip for me?
2013/07/23
[ "https://Stackoverflow.com/questions/17809377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2591465/" ]
InstallClient does not configure environment variables. Solution: * download instantclient\_11\_2(remember you InstallClient path) * PATH add :C:\ instantclient\_11\_2(OCI.DLL) * New system environment variables:SQLPATH,LOCAL,TNS\_ADMIN,LD\_LIBRARY\_PATH;content:C:\ instantclient\_11\_2 To use English, my English is bad
if you use 64-bit pc, oracle doesn't compatible with it. Oracle doesn't find oci.dll file in 64-bit. Therefore, you can try to change oracle home on the top. As a result of that, home path will change.
10,546,388
I have researched alot on google and also read the steps mentioned at www.dropbox.com, but I didn't found any way to list all the files and folders of dropbox in my application using dropbox API.. I know how to download a file from dropbox and also how to upload a file to dropbox. But anyone pls suggest me that Is this possible to list all the files and folder of dropbox and whenever you click on any file then that file starts downloading and save into your sdcard.. Anyone pls help me out with some sample ....plsss
2012/05/11
[ "https://Stackoverflow.com/questions/10546388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/960526/" ]
simple sample. ``` Entry entries = mApi.metadata(Path, 100, null, true, null); for (Entry e : entries.contents) { if (!e.isDeleted) { Log.i("Is Folder",String.valueOf(e.isDir)); Log.i("Item Name",e.fileName); } } ```
Use the [`/metadata`](https://www.dropbox.com/developers/reference/api#metadata) method with the `list` parameter set to `true` to get all the information about a folder and its contents.
23,116,637
I try to make regular expression which helps me filter strings like ``` blah_blah_suffix ``` where suffix is any string that has length from 2 to 5 characters. So I want accept strings ``` blah_blah_aa blah_blah_abcd ``` but discard ``` blah_blah_a blah_aaa blah_blah_aaaaaaa ``` I use grepl in the following way: ``` samples[grepl("blah_blah_.{2,5}", samples)] ``` but it ignores upper bound for repetition (5). So it discards strings blah\_blah\_a, blah\_aaa, but accepts string blah\_blah\_aaaaaaa. I know there is a way to filter strings without usage of regular expression but I want to understand how to use grepl correctly.
2014/04/16
[ "https://Stackoverflow.com/questions/23116637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2196184/" ]
You need to bound the expression to the start and end of the line: ``` ^blah_blah_.{2,5}$ ``` The `^` matches beginning of line and `$` matches end of line. See a working example here: [Regex101](http://regex101.com/r/zH8rR2) If you want to bound the expression to the beginning and end of a string (not multi-line), use `\A` and `\Z` instead of `^` and `$`. [Anchors Tutorial](http://www.regular-expressions.info/anchors.html)
``` /^[\w]+_[\w]+_[\w]{2,5}$/ ``` [DEMO](http://regex101.com/r/rE2vL8) ``` Options: dot matches newline; case insensitive; ^ and $ match at line breaks Assert position at the beginning of a line (at beginning of the string or after a line break character) «^» Match a single character that is a “word character” (letters, digits, and underscores) «[\w]+» Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» Match the character “_” literally «_» Match a single character that is a “word character” (letters, digits, and underscores) «[\w]+» Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» Match the character “_” literally «_» Match a single character that is a “word character” (letters, digits, and underscores) «[\w]{2,5}» Between 2 and 5 times, as many times as possible, giving back as needed (greedy) «{2,5}» Assert position at the end of a line (at the end of the string or before a line break character) «$» ```
70,500
New here and I just wanna ask the question of what happens when your pre warping doesnt work on your bilinear transform? I am assuming my isnt working as part of my research I have read that the higher the frequency is the more non linear it becomes, so I am assuming that my frequency I chose just has to many non linearities that it wouldn't ever get re-aligned to the continuous function critical frequency. It tries but doesnt get there. Sampling Frequency = 44.410kHz Nyquist Frequency = 22.205kHz Critical Frequency = 20kHz Ratio = Fs/Nyquist frequency = 20/22.205 = 90.1% I noticed the closer you are critical frequency is to your Nyquist frequency when applying the bilinear transform it gets ugly. And it looks like the pre warping can only do so much. The only way I see around this if I just changed my Sampling frequency to like 96kHz which would make my Nyquist frequency = 48kHz would be then the ratio = 42% this would ease the constraint of the non-linearities and have the pre warping affect work much better, but this raises the question is it possible to have a digital filter with a sampling frequency of 44.410kHz and a Fc = 20kHz? Because the way this is going I dont see it. [![enter image description here](https://i.stack.imgur.com/lK8Ql.jpg)](https://i.stack.imgur.com/lK8Ql.jpg) CODE: ``` s = tf('s'); Fs = 96e3; Ts = 1/Fs; Fc = 20e3; GP = -3; GS = -20; WP = 2*pi*Fc; WS = 251327.412; n = ceil(log10((10^(-GS/10)-1)/(10^(-GP/10)-1))/(2*log10(WS/WP))); WC_1 = WP/((10^(-GP/10)-1)^(1/(2*n))); WC_2 = WS/((10^(-GS/10)-1)^(1/(2*n))); LP = 1/((s/WC_1)^4+2.613*(s/WC_1)^3+3.414*(s/WC_1)^2+2.613*(s/WC_1)+1); LP_2 = 1/((s/WC_2)^4+2.613*(s/WC_2)^3+3.414*(s/WC_2)^2+2.613*(s/WC_1)+1); LP_44_410kHz = c2d(LP,1/44.410e3,['Method','tustin','PrewarpFrequency',WP]); LP_96kHz = c2d(LP,Ts,['Method','tustin','PrewarpFrequency',WP]); options = bodeoptions; options.FreqUnits = 'Hz'; options.Title.String = 'With Pre-Warping'; bode(LP_44_410kHz,LP,LP_96kHz,options); ```
2020/09/24
[ "https://dsp.stackexchange.com/questions/70500", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/49496/" ]
**DFT vs DTFT, Fourier Transform** The problem appears rooted in viewing DFT as a 'special case' of the continuous Fourier Transform, and of its input as some signal with legitimate frequency contents. *That's a fallacy*. The DFT is a standalone mathematical transformation which does not condition itself upon anything but the input being finitely long, and having finite values. It's an ***information encoding algorithm***. It operates on any and all finite information - be it signals, Shakesperean sonnets, or a cup of water - as long as represented numerically. DFT can be shown to be equivalent to solving $N$ simultaneous equations defining an $N$ long input; it's a complete, lossless transform. --- **What the spectrum "should be" is *not* what we get** * *Should be*: amounts of sinusoidal frequencies comprising the input data.$^1$ * *Is*: amounts of sinusoidal frequencies that sum to the input data.$^1$ See [here](https://dsp.stackexchange.com/a/70395/50076). The input can be a pulse, or a single nonzero value and the rest zeros; there's nothing of periodic nature about either of these, nor do they need to stem from a physical source which is sinusoidal. The only truth is that the coefficients we find give us the sinusoids that sum to the input; with another transform, it can be triangle waves. 1: for a *real-valued* input. For complex, something similar may hold, but it's still a sum of bases (discussion [here](https://dsp.stackexchange.com/a/70407/50076)). --- **DFT coefficients are *not* same as DTFT or FT coefficients** Both the forward and inverse transforms to acquire respective coefficients imply very different things for what the coefficients "mean". Under *certain assumptions* they can be treated equivalently, but not fundamentally. This is clear from the inverse-transform perspective, or reconstruction; assume for now a rectangular-windowed DTFT: * **DFT**: sum of $N$ bases, each $N$-long, finite in value. * **DFT coefficient**: describes one such basis. $N$ coefficients in total. * **DTFT**: *infinitesimal sum* (integral) of *infinitely many* bases, each $N$-long, finite in value. * **DTFT coefficient**: describes one such basis. *infinitely many* coefficients in total. From forward-transform: * **DFT coefficient**: obtained by adding (discretized complex phasor at integer frequency) \* (input), pointwise products. * **DTFT coefficient**: obtained the same way. Except not really; see below. Result? If you use one transform's coefficients in another transform, you get nonsense. --- **Generator vs Data** A generator is a complete descriptor - example: function, continuous. For describing a 1D signal, the signal is *infinitely resolved*; we can determine every possible intermediate value. From a generator we can get *data*, but not vice versa; even a truly continuous segment has infinite interpolations. The DTFT (no windows) works with *generators*, not *data*. Its coefficients are described by a *function* (continuous), which are also determined by an operation between functions (one describing an infinitely long but discrete input, another the complex phasor at a continuous $\omega$). The rectangular-windowed DTFT, on the other hand, works with both, but only "with permission" from generators - that is, the resulting spectrum happens to be the same whether we compute for $n=0$ to $N-1$ or $-\infty$ to $\infty$. In contrast, the DFT works with *data*. No generators. But we can use generators if we wish - it's now the reverse case, generators "with permission" from data. --- **Zero-padding: DFT coeffs treated as DTFT coeffs** -- [all code](https://pastebin.com/jsSphi5B). Before the meat, last piece of background. Take 1Hz over *two seconds*; what's the DFT (which freq is nonzero)? **2.** Now take 0.1Hz over 10 seconds; what's the DFT? **1.** The DFT correlates against basis functions spanning the length of the input signal, with no regard to "actual time". $k=1$ corresponds to 1 cycle over the length of the signal. We can use this to interpret "treat DFT coeffs as DTFT coeffs". Suppose $$s[n] = \cos(2 \pi n / N),\ N = 128,\ n=[0, ..., N - 1].$$ ![](https://i.stack.imgur.com/QlJtd.png) Pre-pad, the spectrum is just what we expect: nonzero everywhere but at $k=1$ and $k=128$. Post-pad - a madhouse. What's the deal? Recall how "0.1Hz over 10 seconds" $\rightarrow k=1$? By the same token, the original $f=1$ is now "seen" as $k=2$ - i.e., it correlates with the $k=2$ basis. Then what does $k=1$ "see"? Let's see: ![](https://i.stack.imgur.com/Edvjt.png) (Only real component of basis shown for clarity; can add the imaginary component for completeness) Put differently, the "normalized" frequency of the DFT is divided by two as a result of doubling the original signal's length with the padding, so $k\_p=2 \leftrightarrow k = 1$, and $k\_p=1 \leftrightarrow k = 0.5$. Or, integer frequencies with a padded signal's spectrum correspond to *fractional* frequencies in the unpadded's spectrum. Is there more evidence? Yes; first, see [this](https://youtu.be/spUNpyF58BY). If above is true, then we can correlate the *original* signal with a $k=0.5$ basis directly, and yield the *same* coefficient as with $k\_p=1$. And indeed: ![](https://i.stack.imgur.com/yKksW.png) Why one window for both padded and unpadded? ... because they look identical - check the code. Mean absolute difference: 6e-14 (within float). --- **In what sense do we "sample the DTFT"? What's the role of zero-padding?** Former should be clear now; the DTFT evaluates itself for every $\omega$. For any given $\omega$, this exactly the same as taking DFT with an equivalent $k$ basis. In other words, DTFT correlates with *neighboring fractional frequencies*, just like DFT correlates with *integer frequencies*. Simpler, "DTFT is DFT with $k$ spanning continuously" (but not quite; see caveats in above sections). So why does zero-padding "result in" the DFT sampling DTFT's spectrum? The answer is closer if we reformulate the question: Why does zero-padding result in the DFT correlating with fractional frequency bases? Yes, they're indeed one and the same question, which was answered in the previous section. A DFT with $2N$ coefficients is equivalent to a DFT with $N$ coefficients at integer frequency bases, and another DFT with $N$ coefficients at *fractional* frequency bases$^1$. **But why *zero*-padding?** Why not one-padding, or pi-padding? Because it's the *only* way for an $M>N$-DFT with integer frequencies to be *equivalent* to an $M$-DFT with fractional frequencies$^1$. Refer to the blue/orange figure; note how the sum of products of the orange with the blue for $k\_p=2$ is the *same* as for $k=1$ with the unpadded blue (not shown; just imagine). If the zeros were anything else, the values might have been proportional, or somehow similar, but not *equal*. In technical terms, zero is orthogonal to all basis functions over any interval. 1: if $M=3N$, then the integer-DFT will correlate $k=[0, 1, ..., 3N-1]$ bases with the *padded signal*, and the "mixed" DFT will correlate $k=[0, 0.33, 0.66, 1, ..., N-1, N - .66, N - .33]$ with the *original signal*. Note that if $M$ is not an integer multiple of $N$, then the padded's integer-DFT may not have any integer equivalents with the unpadded's DFT. --- **Does zero-padding distort the spectrum?** The grand-prize. The answer to which is... *yes and no*: * **No**: zero padding is equivalent to correlating with neighboring, non-integer frequencies; there is no "distortion" here, the coefficients describe exactly what they intend to. * **Yes**: if "the spectrum" is supposed to describe the frequencies in the input signal (e.g. $f=1$), then correlating with bases neighboring $1$ yields non-zero coefficients, implying non-zero frequencies around $1$, whereas the signal *has no such frequencies*. Further, only *integer-ratio* frequencies are completely decorrelated (e.g. 1 and 2, 1.5 and 3), so we'll get *many* high and low non-zero frequencies, whereas the input has only *one* frequency. So what's the deal? The deal is - **DFT does NOT describe input's spectrum**. This is the entire point of [this answer](https://dsp.stackexchange.com/q/70394/50076), which was so warmly-received because of a technicality I was quick to retract with a **NOTE:** on top. Ignore the downvotes, they mean nothing without explanation. Since it's not the spectrum we expect, it's meaningless to speak of a "distortion" as if it ever gave the actual spectrum. The input could be $f=1.1$, and then the unpadded DFT would be "distortion", and the only true spectrum would stem from incrementing the bases by $1.1$. This also explains why we can't do much better than the DFT; we *don't know* what the "actual" frequency of a signal is without its *generator* (function). The DFT is simply our "best guess", one which must be interpreted carefully. --- **Possible to pad *without* distorting?** *Yes*, but in a specific sense: if the number of zeros added is an *integer-multiple* of the signal's length, then the DFT will *contain the unpadded's spectrum*. For example, pad by $2N$; then, the DFT, from original's point of view, is doing $k=[0,.33,.66,1,...,N-1,N-.66,N-.33]$. Notice how $[0, 1, ..., N-1]$ are all captured. In other words, we can pad *without losing the original spectrum*. --- **Re: other answers** * The fact that the input is discrete or finite has virtually nothing to do with this - which [this upvoted answer](https://dsp.stackexchange.com/a/70484/50076) contradicts. Though, a little more work is due to show this; short version is, imagine the "winding machine" winding forever, and why that yields an impulse, and how that relates to the finite spike in DFT. Whatever the answer, it's way besides the point.
Yes. All windows distort spectrum, whether they be due to the inherent length of the DFT, or a zero-padding rectangle. That's because nothing of finite length (e.g. of finite support) consists of a single frequency in the frequency domain (or is even bounded in bandwidth). So you choose your preferred distortion (or window artifact). One often preferred distortion is using a DFT length that is an exact integer multiple of one constituent sinusoid, which has the strange windowing artifact of being zero for all but one matrix transform basis vector. Or some linear combination of exact integer periodic sinusoids thereof.
70,500
New here and I just wanna ask the question of what happens when your pre warping doesnt work on your bilinear transform? I am assuming my isnt working as part of my research I have read that the higher the frequency is the more non linear it becomes, so I am assuming that my frequency I chose just has to many non linearities that it wouldn't ever get re-aligned to the continuous function critical frequency. It tries but doesnt get there. Sampling Frequency = 44.410kHz Nyquist Frequency = 22.205kHz Critical Frequency = 20kHz Ratio = Fs/Nyquist frequency = 20/22.205 = 90.1% I noticed the closer you are critical frequency is to your Nyquist frequency when applying the bilinear transform it gets ugly. And it looks like the pre warping can only do so much. The only way I see around this if I just changed my Sampling frequency to like 96kHz which would make my Nyquist frequency = 48kHz would be then the ratio = 42% this would ease the constraint of the non-linearities and have the pre warping affect work much better, but this raises the question is it possible to have a digital filter with a sampling frequency of 44.410kHz and a Fc = 20kHz? Because the way this is going I dont see it. [![enter image description here](https://i.stack.imgur.com/lK8Ql.jpg)](https://i.stack.imgur.com/lK8Ql.jpg) CODE: ``` s = tf('s'); Fs = 96e3; Ts = 1/Fs; Fc = 20e3; GP = -3; GS = -20; WP = 2*pi*Fc; WS = 251327.412; n = ceil(log10((10^(-GS/10)-1)/(10^(-GP/10)-1))/(2*log10(WS/WP))); WC_1 = WP/((10^(-GP/10)-1)^(1/(2*n))); WC_2 = WS/((10^(-GS/10)-1)^(1/(2*n))); LP = 1/((s/WC_1)^4+2.613*(s/WC_1)^3+3.414*(s/WC_1)^2+2.613*(s/WC_1)+1); LP_2 = 1/((s/WC_2)^4+2.613*(s/WC_2)^3+3.414*(s/WC_2)^2+2.613*(s/WC_1)+1); LP_44_410kHz = c2d(LP,1/44.410e3,['Method','tustin','PrewarpFrequency',WP]); LP_96kHz = c2d(LP,Ts,['Method','tustin','PrewarpFrequency',WP]); options = bodeoptions; options.FreqUnits = 'Hz'; options.Title.String = 'With Pre-Warping'; bode(LP_44_410kHz,LP,LP_96kHz,options); ```
2020/09/24
[ "https://dsp.stackexchange.com/questions/70500", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/49496/" ]
**DFT vs DTFT, Fourier Transform** The problem appears rooted in viewing DFT as a 'special case' of the continuous Fourier Transform, and of its input as some signal with legitimate frequency contents. *That's a fallacy*. The DFT is a standalone mathematical transformation which does not condition itself upon anything but the input being finitely long, and having finite values. It's an ***information encoding algorithm***. It operates on any and all finite information - be it signals, Shakesperean sonnets, or a cup of water - as long as represented numerically. DFT can be shown to be equivalent to solving $N$ simultaneous equations defining an $N$ long input; it's a complete, lossless transform. --- **What the spectrum "should be" is *not* what we get** * *Should be*: amounts of sinusoidal frequencies comprising the input data.$^1$ * *Is*: amounts of sinusoidal frequencies that sum to the input data.$^1$ See [here](https://dsp.stackexchange.com/a/70395/50076). The input can be a pulse, or a single nonzero value and the rest zeros; there's nothing of periodic nature about either of these, nor do they need to stem from a physical source which is sinusoidal. The only truth is that the coefficients we find give us the sinusoids that sum to the input; with another transform, it can be triangle waves. 1: for a *real-valued* input. For complex, something similar may hold, but it's still a sum of bases (discussion [here](https://dsp.stackexchange.com/a/70407/50076)). --- **DFT coefficients are *not* same as DTFT or FT coefficients** Both the forward and inverse transforms to acquire respective coefficients imply very different things for what the coefficients "mean". Under *certain assumptions* they can be treated equivalently, but not fundamentally. This is clear from the inverse-transform perspective, or reconstruction; assume for now a rectangular-windowed DTFT: * **DFT**: sum of $N$ bases, each $N$-long, finite in value. * **DFT coefficient**: describes one such basis. $N$ coefficients in total. * **DTFT**: *infinitesimal sum* (integral) of *infinitely many* bases, each $N$-long, finite in value. * **DTFT coefficient**: describes one such basis. *infinitely many* coefficients in total. From forward-transform: * **DFT coefficient**: obtained by adding (discretized complex phasor at integer frequency) \* (input), pointwise products. * **DTFT coefficient**: obtained the same way. Except not really; see below. Result? If you use one transform's coefficients in another transform, you get nonsense. --- **Generator vs Data** A generator is a complete descriptor - example: function, continuous. For describing a 1D signal, the signal is *infinitely resolved*; we can determine every possible intermediate value. From a generator we can get *data*, but not vice versa; even a truly continuous segment has infinite interpolations. The DTFT (no windows) works with *generators*, not *data*. Its coefficients are described by a *function* (continuous), which are also determined by an operation between functions (one describing an infinitely long but discrete input, another the complex phasor at a continuous $\omega$). The rectangular-windowed DTFT, on the other hand, works with both, but only "with permission" from generators - that is, the resulting spectrum happens to be the same whether we compute for $n=0$ to $N-1$ or $-\infty$ to $\infty$. In contrast, the DFT works with *data*. No generators. But we can use generators if we wish - it's now the reverse case, generators "with permission" from data. --- **Zero-padding: DFT coeffs treated as DTFT coeffs** -- [all code](https://pastebin.com/jsSphi5B). Before the meat, last piece of background. Take 1Hz over *two seconds*; what's the DFT (which freq is nonzero)? **2.** Now take 0.1Hz over 10 seconds; what's the DFT? **1.** The DFT correlates against basis functions spanning the length of the input signal, with no regard to "actual time". $k=1$ corresponds to 1 cycle over the length of the signal. We can use this to interpret "treat DFT coeffs as DTFT coeffs". Suppose $$s[n] = \cos(2 \pi n / N),\ N = 128,\ n=[0, ..., N - 1].$$ ![](https://i.stack.imgur.com/QlJtd.png) Pre-pad, the spectrum is just what we expect: nonzero everywhere but at $k=1$ and $k=128$. Post-pad - a madhouse. What's the deal? Recall how "0.1Hz over 10 seconds" $\rightarrow k=1$? By the same token, the original $f=1$ is now "seen" as $k=2$ - i.e., it correlates with the $k=2$ basis. Then what does $k=1$ "see"? Let's see: ![](https://i.stack.imgur.com/Edvjt.png) (Only real component of basis shown for clarity; can add the imaginary component for completeness) Put differently, the "normalized" frequency of the DFT is divided by two as a result of doubling the original signal's length with the padding, so $k\_p=2 \leftrightarrow k = 1$, and $k\_p=1 \leftrightarrow k = 0.5$. Or, integer frequencies with a padded signal's spectrum correspond to *fractional* frequencies in the unpadded's spectrum. Is there more evidence? Yes; first, see [this](https://youtu.be/spUNpyF58BY). If above is true, then we can correlate the *original* signal with a $k=0.5$ basis directly, and yield the *same* coefficient as with $k\_p=1$. And indeed: ![](https://i.stack.imgur.com/yKksW.png) Why one window for both padded and unpadded? ... because they look identical - check the code. Mean absolute difference: 6e-14 (within float). --- **In what sense do we "sample the DTFT"? What's the role of zero-padding?** Former should be clear now; the DTFT evaluates itself for every $\omega$. For any given $\omega$, this exactly the same as taking DFT with an equivalent $k$ basis. In other words, DTFT correlates with *neighboring fractional frequencies*, just like DFT correlates with *integer frequencies*. Simpler, "DTFT is DFT with $k$ spanning continuously" (but not quite; see caveats in above sections). So why does zero-padding "result in" the DFT sampling DTFT's spectrum? The answer is closer if we reformulate the question: Why does zero-padding result in the DFT correlating with fractional frequency bases? Yes, they're indeed one and the same question, which was answered in the previous section. A DFT with $2N$ coefficients is equivalent to a DFT with $N$ coefficients at integer frequency bases, and another DFT with $N$ coefficients at *fractional* frequency bases$^1$. **But why *zero*-padding?** Why not one-padding, or pi-padding? Because it's the *only* way for an $M>N$-DFT with integer frequencies to be *equivalent* to an $M$-DFT with fractional frequencies$^1$. Refer to the blue/orange figure; note how the sum of products of the orange with the blue for $k\_p=2$ is the *same* as for $k=1$ with the unpadded blue (not shown; just imagine). If the zeros were anything else, the values might have been proportional, or somehow similar, but not *equal*. In technical terms, zero is orthogonal to all basis functions over any interval. 1: if $M=3N$, then the integer-DFT will correlate $k=[0, 1, ..., 3N-1]$ bases with the *padded signal*, and the "mixed" DFT will correlate $k=[0, 0.33, 0.66, 1, ..., N-1, N - .66, N - .33]$ with the *original signal*. Note that if $M$ is not an integer multiple of $N$, then the padded's integer-DFT may not have any integer equivalents with the unpadded's DFT. --- **Does zero-padding distort the spectrum?** The grand-prize. The answer to which is... *yes and no*: * **No**: zero padding is equivalent to correlating with neighboring, non-integer frequencies; there is no "distortion" here, the coefficients describe exactly what they intend to. * **Yes**: if "the spectrum" is supposed to describe the frequencies in the input signal (e.g. $f=1$), then correlating with bases neighboring $1$ yields non-zero coefficients, implying non-zero frequencies around $1$, whereas the signal *has no such frequencies*. Further, only *integer-ratio* frequencies are completely decorrelated (e.g. 1 and 2, 1.5 and 3), so we'll get *many* high and low non-zero frequencies, whereas the input has only *one* frequency. So what's the deal? The deal is - **DFT does NOT describe input's spectrum**. This is the entire point of [this answer](https://dsp.stackexchange.com/q/70394/50076), which was so warmly-received because of a technicality I was quick to retract with a **NOTE:** on top. Ignore the downvotes, they mean nothing without explanation. Since it's not the spectrum we expect, it's meaningless to speak of a "distortion" as if it ever gave the actual spectrum. The input could be $f=1.1$, and then the unpadded DFT would be "distortion", and the only true spectrum would stem from incrementing the bases by $1.1$. This also explains why we can't do much better than the DFT; we *don't know* what the "actual" frequency of a signal is without its *generator* (function). The DFT is simply our "best guess", one which must be interpreted carefully. --- **Possible to pad *without* distorting?** *Yes*, but in a specific sense: if the number of zeros added is an *integer-multiple* of the signal's length, then the DFT will *contain the unpadded's spectrum*. For example, pad by $2N$; then, the DFT, from original's point of view, is doing $k=[0,.33,.66,1,...,N-1,N-.66,N-.33]$. Notice how $[0, 1, ..., N-1]$ are all captured. In other words, we can pad *without losing the original spectrum*. --- **Re: other answers** * The fact that the input is discrete or finite has virtually nothing to do with this - which [this upvoted answer](https://dsp.stackexchange.com/a/70484/50076) contradicts. Though, a little more work is due to show this; short version is, imagine the "winding machine" winding forever, and why that yields an impulse, and how that relates to the finite spike in DFT. Whatever the answer, it's way besides the point.
Shorter version with more intuitive animation where original signal is fixed in frame, and alternate formulation: *zero-padding **extends** the spectrum*. Here's `k=1` basis (sine omitted) over 1Hz signal, `N=128` points: ![](https://i.stack.imgur.com/p4oq8.png) As we zero-pad the signal, this same `k=1` basis now spans the total length of the *padded* signal, while adding values only from the *unpadded* signal, which is exactly the same as multiplying w/ a cosine of *lower frequency* in the original frame (details in my first answer). Ignoring the padding part and thinking purely in terms of the modified cosine, this can be visualized as (try ignoring the right half entirely): ![](https://i.stack.imgur.com/MkzpK.gif) Now showing padding: ![](https://i.stack.imgur.com/7Rhm3.gif) This is repeated with every other `k`, and we have more of `k` in total (as many as `len(x) + pad_length`). For example, if `pad_length = len(x)`, then `k=2` 'becomes' `1Hz`, and likewise any padding *integer-multiple* length of original signal will *include* the original spectrum entirely in the longer spectrum. Thus, zero-padding can be interpreted as "extending" the spectrum, i.e. adding additional frequency correlates - atop original, or, if not integer-mult padded, *shifting* bins to fractions of unpadded (e.g. `len(x)=128`, `pad_length=64`, now `k=2` in padded frame is `k=2/1.5=1.33` in unpadded frame).
70,500
New here and I just wanna ask the question of what happens when your pre warping doesnt work on your bilinear transform? I am assuming my isnt working as part of my research I have read that the higher the frequency is the more non linear it becomes, so I am assuming that my frequency I chose just has to many non linearities that it wouldn't ever get re-aligned to the continuous function critical frequency. It tries but doesnt get there. Sampling Frequency = 44.410kHz Nyquist Frequency = 22.205kHz Critical Frequency = 20kHz Ratio = Fs/Nyquist frequency = 20/22.205 = 90.1% I noticed the closer you are critical frequency is to your Nyquist frequency when applying the bilinear transform it gets ugly. And it looks like the pre warping can only do so much. The only way I see around this if I just changed my Sampling frequency to like 96kHz which would make my Nyquist frequency = 48kHz would be then the ratio = 42% this would ease the constraint of the non-linearities and have the pre warping affect work much better, but this raises the question is it possible to have a digital filter with a sampling frequency of 44.410kHz and a Fc = 20kHz? Because the way this is going I dont see it. [![enter image description here](https://i.stack.imgur.com/lK8Ql.jpg)](https://i.stack.imgur.com/lK8Ql.jpg) CODE: ``` s = tf('s'); Fs = 96e3; Ts = 1/Fs; Fc = 20e3; GP = -3; GS = -20; WP = 2*pi*Fc; WS = 251327.412; n = ceil(log10((10^(-GS/10)-1)/(10^(-GP/10)-1))/(2*log10(WS/WP))); WC_1 = WP/((10^(-GP/10)-1)^(1/(2*n))); WC_2 = WS/((10^(-GS/10)-1)^(1/(2*n))); LP = 1/((s/WC_1)^4+2.613*(s/WC_1)^3+3.414*(s/WC_1)^2+2.613*(s/WC_1)+1); LP_2 = 1/((s/WC_2)^4+2.613*(s/WC_2)^3+3.414*(s/WC_2)^2+2.613*(s/WC_1)+1); LP_44_410kHz = c2d(LP,1/44.410e3,['Method','tustin','PrewarpFrequency',WP]); LP_96kHz = c2d(LP,Ts,['Method','tustin','PrewarpFrequency',WP]); options = bodeoptions; options.FreqUnits = 'Hz'; options.Title.String = 'With Pre-Warping'; bode(LP_44_410kHz,LP,LP_96kHz,options); ```
2020/09/24
[ "https://dsp.stackexchange.com/questions/70500", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/49496/" ]
Shorter version with more intuitive animation where original signal is fixed in frame, and alternate formulation: *zero-padding **extends** the spectrum*. Here's `k=1` basis (sine omitted) over 1Hz signal, `N=128` points: ![](https://i.stack.imgur.com/p4oq8.png) As we zero-pad the signal, this same `k=1` basis now spans the total length of the *padded* signal, while adding values only from the *unpadded* signal, which is exactly the same as multiplying w/ a cosine of *lower frequency* in the original frame (details in my first answer). Ignoring the padding part and thinking purely in terms of the modified cosine, this can be visualized as (try ignoring the right half entirely): ![](https://i.stack.imgur.com/MkzpK.gif) Now showing padding: ![](https://i.stack.imgur.com/7Rhm3.gif) This is repeated with every other `k`, and we have more of `k` in total (as many as `len(x) + pad_length`). For example, if `pad_length = len(x)`, then `k=2` 'becomes' `1Hz`, and likewise any padding *integer-multiple* length of original signal will *include* the original spectrum entirely in the longer spectrum. Thus, zero-padding can be interpreted as "extending" the spectrum, i.e. adding additional frequency correlates - atop original, or, if not integer-mult padded, *shifting* bins to fractions of unpadded (e.g. `len(x)=128`, `pad_length=64`, now `k=2` in padded frame is `k=2/1.5=1.33` in unpadded frame).
Yes. All windows distort spectrum, whether they be due to the inherent length of the DFT, or a zero-padding rectangle. That's because nothing of finite length (e.g. of finite support) consists of a single frequency in the frequency domain (or is even bounded in bandwidth). So you choose your preferred distortion (or window artifact). One often preferred distortion is using a DFT length that is an exact integer multiple of one constituent sinusoid, which has the strange windowing artifact of being zero for all but one matrix transform basis vector. Or some linear combination of exact integer periodic sinusoids thereof.
8,293,570
I'm new to subversion. I've created a repository, and I want to make the first commit. There are some files and folders that should not be checked in, such as `cache/` or `log/`. I've used `svn propset svn:ignore -F svn_ignore.txt`. I want to have a simple way to add new files to svn. Is there a way to do this while respecting the svn:ignore setting ? The following commands add every file, even the ignored ones : ``` svn add --force . alias svn_add_all='svn st|grep ^?|sed s/?//|xargs svn add $1' ``` **EDIT** Here's what I get : ``` $ svn status ? web/images/test/film_super8.jpg ? web/images/test/ea_dl_manager.jpg ? web/images/test/minecraft_anaglyph.png $ svn propget svn:ignore cache/* log/* web/images/blog/* web/images/test/* ```
2011/11/28
[ "https://Stackoverflow.com/questions/8293570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/113305/" ]
> > The patterns are strictly for that directory—they do not carry > recursively into subdirectories. > > > See [SVN documentation](http://svnbook.red-bean.com/en/1.1/ch07s02.html) So you must apply your patterns on all the directories, or only on the directories where that ignore is necessary. So the pattern shouldn't include directories like you do. `web/images/blog/*` won't work. You should go to the `blog` folder and set `svn:ignore` to `*` Some clients have a "Apply recursively" feature that does that for you. I don't know if you can do that with the "default" client. But in your case, it would be useless. It may be used when a specific file or pattern must be ignored everywhere (like `*.suo` files for Visual Studio projects)
`svn status` should not display an ignored file. But the issue might be in the way you do ignore a file: see "[Command Line svn:ignore a file](http://blog.bogojoker.com/2008/07/command-line-svnignore-a-file/)" > > You don’t `svn:ignore` a file. > > > You put an `svn:ignore` property **on the directory** to ignore that filename pattern! > > > ``` # Add just the single file to the current directories ignore list (like above) # Note the dot at the end of the command is important svn propset svn:ignore secret.txt . # See that things worked svn propget svn:ignore . # Notice the single file was added to the list svn status --no-ignore # You should see an 'I' next to the ignored files ```
7,220,737
I'm trying to parse some HTML that includes some HTML entities, like × ``` $str = '<a href="http://example.com/"> A &#215; B</a>'; $dom = new DomDocument; $dom -> substituteEntities = false; $dom ->loadHTML($str); $link = $dom ->getElementsByTagName('a') -> item(0); $fullname = $link -> nodeValue; $href = $link -> getAttribute('href'); echo " fullname: $fullname \n href: $href\n"; ``` but DomDocument substitutes the text for for A × B. Is there some way to keep it from taking the & for an HTML entity and make it just leave it alone? I tried to set substituteEntities to false but it doesn't do anything
2011/08/28
[ "https://Stackoverflow.com/questions/7220737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889482/" ]
This is no direct answer to the question, but you may use UTF-8 instead, which allows you to save glyphs like ÷ or × directly. To use UTF-8 with PHP DOM on the other needs [a little hack](http://php.net/manual/en/domdocument.loadhtml.php#95251). Also, if you are trying to display mathematical formulas (as A × B suggests) have a look at [MathML](http://www.w3.org/Math/).
Are you sure the & is being substituted to `&amp;`? If that were the case, you'd see the exact entity, as text, not the garbled response you're getting. My guess is that it is converted to the actual character, and you're viewing the page with a latin1 charset, which does not contain this character, hence the garbled response. If I render your example, my output is: ``` fullname: A × B href: http://example.com/ ``` When viewing this in latin1/iso-8859-1, I see the output you're describing. But when I set the charset to UTF-8, the output is fine.
7,220,737
I'm trying to parse some HTML that includes some HTML entities, like × ``` $str = '<a href="http://example.com/"> A &#215; B</a>'; $dom = new DomDocument; $dom -> substituteEntities = false; $dom ->loadHTML($str); $link = $dom ->getElementsByTagName('a') -> item(0); $fullname = $link -> nodeValue; $href = $link -> getAttribute('href'); echo " fullname: $fullname \n href: $href\n"; ``` but DomDocument substitutes the text for for A × B. Is there some way to keep it from taking the & for an HTML entity and make it just leave it alone? I tried to set substituteEntities to false but it doesn't do anything
2011/08/28
[ "https://Stackoverflow.com/questions/7220737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889482/" ]
From the docs: *The DOM extension uses UTF-8 encoding. Use utf8\_encode() and utf8\_decode() to work with texts in ISO-8859-1 encoding or Iconv for other encodings.* Assuming you're using latin-1 try: ``` <?php header('Content-type:text/html;charset=iso-8859-1'); $str = utf8_encode('<a href="http://example.com/"> A &#215; B</a>'); $dom = new DOMDocument; $dom -> substituteEntities = false; $dom ->loadHTML($str); $link = $dom ->getElementsByTagName('a') -> item(0); $fullname = utf8_decode($link -> nodeValue); $href = $link -> getAttribute('href'); echo " fullname: $fullname \n href: $href\n"; ?> ```
Are you sure the & is being substituted to `&amp;`? If that were the case, you'd see the exact entity, as text, not the garbled response you're getting. My guess is that it is converted to the actual character, and you're viewing the page with a latin1 charset, which does not contain this character, hence the garbled response. If I render your example, my output is: ``` fullname: A × B href: http://example.com/ ``` When viewing this in latin1/iso-8859-1, I see the output you're describing. But when I set the charset to UTF-8, the output is fine.
7,220,737
I'm trying to parse some HTML that includes some HTML entities, like × ``` $str = '<a href="http://example.com/"> A &#215; B</a>'; $dom = new DomDocument; $dom -> substituteEntities = false; $dom ->loadHTML($str); $link = $dom ->getElementsByTagName('a') -> item(0); $fullname = $link -> nodeValue; $href = $link -> getAttribute('href'); echo " fullname: $fullname \n href: $href\n"; ``` but DomDocument substitutes the text for for A × B. Is there some way to keep it from taking the & for an HTML entity and make it just leave it alone? I tried to set substituteEntities to false but it doesn't do anything
2011/08/28
[ "https://Stackoverflow.com/questions/7220737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889482/" ]
Are you sure the & is being substituted to `&amp;`? If that were the case, you'd see the exact entity, as text, not the garbled response you're getting. My guess is that it is converted to the actual character, and you're viewing the page with a latin1 charset, which does not contain this character, hence the garbled response. If I render your example, my output is: ``` fullname: A × B href: http://example.com/ ``` When viewing this in latin1/iso-8859-1, I see the output you're describing. But when I set the charset to UTF-8, the output is fine.
I fixed my problem with broken entities by converting UTF-8 to UTF-8 with BOM.
7,220,737
I'm trying to parse some HTML that includes some HTML entities, like × ``` $str = '<a href="http://example.com/"> A &#215; B</a>'; $dom = new DomDocument; $dom -> substituteEntities = false; $dom ->loadHTML($str); $link = $dom ->getElementsByTagName('a') -> item(0); $fullname = $link -> nodeValue; $href = $link -> getAttribute('href'); echo " fullname: $fullname \n href: $href\n"; ``` but DomDocument substitutes the text for for A × B. Is there some way to keep it from taking the & for an HTML entity and make it just leave it alone? I tried to set substituteEntities to false but it doesn't do anything
2011/08/28
[ "https://Stackoverflow.com/questions/7220737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889482/" ]
This is no direct answer to the question, but you may use UTF-8 instead, which allows you to save glyphs like ÷ or × directly. To use UTF-8 with PHP DOM on the other needs [a little hack](http://php.net/manual/en/domdocument.loadhtml.php#95251). Also, if you are trying to display mathematical formulas (as A × B suggests) have a look at [MathML](http://www.w3.org/Math/).
I fixed my problem with broken entities by converting UTF-8 to UTF-8 with BOM.
7,220,737
I'm trying to parse some HTML that includes some HTML entities, like × ``` $str = '<a href="http://example.com/"> A &#215; B</a>'; $dom = new DomDocument; $dom -> substituteEntities = false; $dom ->loadHTML($str); $link = $dom ->getElementsByTagName('a') -> item(0); $fullname = $link -> nodeValue; $href = $link -> getAttribute('href'); echo " fullname: $fullname \n href: $href\n"; ``` but DomDocument substitutes the text for for A × B. Is there some way to keep it from taking the & for an HTML entity and make it just leave it alone? I tried to set substituteEntities to false but it doesn't do anything
2011/08/28
[ "https://Stackoverflow.com/questions/7220737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889482/" ]
From the docs: *The DOM extension uses UTF-8 encoding. Use utf8\_encode() and utf8\_decode() to work with texts in ISO-8859-1 encoding or Iconv for other encodings.* Assuming you're using latin-1 try: ``` <?php header('Content-type:text/html;charset=iso-8859-1'); $str = utf8_encode('<a href="http://example.com/"> A &#215; B</a>'); $dom = new DOMDocument; $dom -> substituteEntities = false; $dom ->loadHTML($str); $link = $dom ->getElementsByTagName('a') -> item(0); $fullname = utf8_decode($link -> nodeValue); $href = $link -> getAttribute('href'); echo " fullname: $fullname \n href: $href\n"; ?> ```
I fixed my problem with broken entities by converting UTF-8 to UTF-8 with BOM.
22,662,559
I have the following piece of Java code and while debugging in Eclipse, Windows 7, the variable 'xoredChar' shows no value at all, not null, not '', nothing. ``` char xoredChar = (char) (stringA.charAt(j)^stringB.charAt(j)); ``` Why is that? I need to understand how can I do this xor operation between two characters in java. What am I missing?
2014/03/26
[ "https://Stackoverflow.com/questions/22662559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148175/" ]
Well, if the strings are equal you'll get back a `\0` which is not a printable character. Try something like this, ``` String stringA = "A"; String stringB = "A"; int j = 0; char xoredChar = (char) (stringA.charAt(j) ^ stringB.charAt(j)); System.out.printf("'%c' = %d\n", xoredChar, (int) xoredChar); ``` Output is ``` ' ' = 0 ```
If `stringA` and `stringB` are identical, then the XOR operation will yield `xoredChar = 0`. A 0 is probably showing in your IDE as nothing since 0 is used as a string terminator in most instances.
22,662,559
I have the following piece of Java code and while debugging in Eclipse, Windows 7, the variable 'xoredChar' shows no value at all, not null, not '', nothing. ``` char xoredChar = (char) (stringA.charAt(j)^stringB.charAt(j)); ``` Why is that? I need to understand how can I do this xor operation between two characters in java. What am I missing?
2014/03/26
[ "https://Stackoverflow.com/questions/22662559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148175/" ]
Well, if the strings are equal you'll get back a `\0` which is not a printable character. Try something like this, ``` String stringA = "A"; String stringB = "A"; int j = 0; char xoredChar = (char) (stringA.charAt(j) ^ stringB.charAt(j)); System.out.printf("'%c' = %d\n", xoredChar, (int) xoredChar); ``` Output is ``` ' ' = 0 ```
As mentioned by the other answers, xoring the same characters results in a `\0` value, which has no visual representation. Perhapse you are interested in a small application, which gives you and idea how XOR works on your strings: ``` public class Example { public static void main(String[] args) { String a = "abcde"; String b = a; for (int idx = 0; idx < b.length(); idx++) { System.out.printf("xoring <%s> [%s] with <%s> [%s]\n", a.charAt(0), toBinaryString(a.charAt(0)), b.charAt(idx), toBinaryString(b.charAt(idx))); int c = (a.charAt(0) ^ b.charAt(idx)); System.out.printf("result is <%s> [%s]\n", (char) c, toBinaryString(c)); } } } ``` Have fun!
6,972,753
Can somebody give a simple example for java code of a native app passing a string to a website? For example: when a string has the value `Hello everybody`, the text `Hello everybody` should get pasted into the Google search field.
2011/08/07
[ "https://Stackoverflow.com/questions/6972753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/798536/" ]
For the most simple use, you can try: ``` public static void browseURL(Activity activity, String url) { try { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); activity.startActivity(intent); } catch (Exception e) { message(activity, "Sorry, failed to view the desired page."); } } ``` and then call: ``` browseURL("http://www.google.com/search?q=Hello+World") ```
Do you want to fill the fields and submit them? If so, just do the request with the request parameters filled, and parse the response given by the server. Look into Apache HttpClient.
6,972,753
Can somebody give a simple example for java code of a native app passing a string to a website? For example: when a string has the value `Hello everybody`, the text `Hello everybody` should get pasted into the Google search field.
2011/08/07
[ "https://Stackoverflow.com/questions/6972753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/798536/" ]
For the most simple use, you can try: ``` public static void browseURL(Activity activity, String url) { try { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); activity.startActivity(intent); } catch (Exception e) { message(activity, "Sorry, failed to view the desired page."); } } ``` and then call: ``` browseURL("http://www.google.com/search?q=Hello+World") ```
You don't actually have to add text to the Google search field explicitly. You can send a URL with a query string. Depending on the website the query string will always be different. For Google it is <http://www.google.ca/search?q=something> . Anything after a ? is considered a query string which any good web developer will include in a webpage. That query string takes custom commands in the form of ?command=query for command&command2=query for command 2. Since this is tagged blackberry, I assume you want to implement a blackberry app, and you don't explicitly explain what you want to do, so you have two options, 1. [Invoke the browser](http://www.blackberry.com/developers/docs/4.7.0api/App-Integration-summary.html) On that page it describes how to open a browser session. So within the ``` browserSession.displayPage("http://http://www.google.ca/search?q=searching%20for%20something"); ``` If you need a class for URL encoding, let me know and I'll send one your way. 1. Http Request to pull the html of the webpage into the code. To do that, you'll have to look at my blog this week as I'll be posting a full in code network class either tomorrow or tuesday, which I'll edit this post to contain a link to. OR you can send me a message if you need it NOW and I can email the non-cleaned up code to you.
711,709
<https://what-if.xkcd.com/6/> has been mentioned here before, but I'm questioning whether or not the glass cup with the bottom half as a vacuum would rise at all. To start with, a vacuum exerts no force. Any perceived "sucking" is actually external pressure pushing into the vacuum. So the only force that could be lifting the glass would be buoyancy of the air around the cup. Let's ballpark it with a drinking cup that can hold about 500ml. If we consider the cup as an open-top cylinder, an internal radius of 3.8 cm and height of 11 cm gets us a 499ml volume, and the internal surface area is 308 cm^2. Based on a quick Google search, glass is about 2000x more dense than air, so in order for the glass to rise it would need to displace 2000x as much air as there is glass. That suggests that if the glass was sealed (by a weightless forcefield at the top) and was completely empty instead of having some water in it, the total volume of glass would have to be less than 0.5ml, resulting in an average width of 0.016mm. That's thinner than a human hair. Given that glass cups are significantly thicker than human hair1, is there any truth to the conclusions of that "What If?" Is there some effect that I've misunderstood or underestimated that significantly changes the situation? Or should we conclude, like <https://physics.stackexchange.com/a/33642/79374> did with the other vacuum cup, that Randall Munroe either miscalculated or was greatly exaggerating? 1 Citation needed
2022/06/01
[ "https://physics.stackexchange.com/questions/711709", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/79374/" ]
It's not just buoyancy because the slug of liquid can move. Your "force field" at the top of the glass modifies the premise of the XKCD scenario. If you look closely at the illustrations, his slug of liquid moves downward as the glass moves upward. The atmosphere pushes down on the slug of liquid and up on the glass, moving them both. But the center of mass of the system would not move.
Only if the cup is big enough and resistant to breaking, it will fly up. The volume, with zero mass inside, grows faster than the glass volume (assuming constant glass thickness). So the upward buoyancy force will exceed the total mass at some point. I only now saw the real problem. If you pull a vacuum in a cylinder with a piston and release the piston, the cylinder will accelerate oppositely. Likewise, the glass with a vacuum on the lower half will jump upward.
711,709
<https://what-if.xkcd.com/6/> has been mentioned here before, but I'm questioning whether or not the glass cup with the bottom half as a vacuum would rise at all. To start with, a vacuum exerts no force. Any perceived "sucking" is actually external pressure pushing into the vacuum. So the only force that could be lifting the glass would be buoyancy of the air around the cup. Let's ballpark it with a drinking cup that can hold about 500ml. If we consider the cup as an open-top cylinder, an internal radius of 3.8 cm and height of 11 cm gets us a 499ml volume, and the internal surface area is 308 cm^2. Based on a quick Google search, glass is about 2000x more dense than air, so in order for the glass to rise it would need to displace 2000x as much air as there is glass. That suggests that if the glass was sealed (by a weightless forcefield at the top) and was completely empty instead of having some water in it, the total volume of glass would have to be less than 0.5ml, resulting in an average width of 0.016mm. That's thinner than a human hair. Given that glass cups are significantly thicker than human hair1, is there any truth to the conclusions of that "What If?" Is there some effect that I've misunderstood or underestimated that significantly changes the situation? Or should we conclude, like <https://physics.stackexchange.com/a/33642/79374> did with the other vacuum cup, that Randall Munroe either miscalculated or was greatly exaggerating? 1 Citation needed
2022/06/01
[ "https://physics.stackexchange.com/questions/711709", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/79374/" ]
For a glass of water, the buoyant force is a small correction to the gravitational force arising because the pressure is different at different altitudes. The timescales in this problem are short enough that we can neglect the center-of-mass motion due to gravity, so we can absolutely neglect the center-of-mass motion due to the buoyant correction. The net force on the glass will be \begin{align} \vec F\_\text{net} &= \vec F\_\text{out} + \vec F\_\text{in} \\ &= \int P\_\text{air}\ \mathrm d\vec A\_\text{outside} + \int P\_\text{vacuum}\ \mathrm d\vec A\_\text{inside} \end{align} For a disc with air below and vacuum above, this force works out to be just the air pressure applied to the area of the disc. The drinking glasses in my kitchen have outer diameter $\rm 5\,cm$ at the base, so call the inner area $\rm 15\,cm^2$. (In the limit of a cylinder, the net vertical force on the glass walls is zero.) For a one-atmosphere pressure difference that’s a net force of $$ P\_\text{air} A\_\text{base} = 10^5\frac{\rm N}{\rm m^2} \cdot 15\rm\,cm^2 \color{lightgray}{ {}\times\left(\frac{1\rm\,m}{100\rm\,cm}\right)^2} = 150\rm\,N $$ This particular glass from my kitchen has a mass of about $\rm\frac13\,kg$, so with air below and vacuum above it would rocket upwards with an acceleration of about $45g$. (If you’d like, you can re-do the problem without neglecting gravity, and ask whether the correction to $44g$ upward is larger or smaller than our other simplifying assumptions.) If you consider the glass-plus-liquid as a single system, the no-gravity, no-buoyancy approximation is that the air pressure will symmetrically crush the water and the glass together without changing its center of mass: the water will move down and the glass will move up, so that the total momentum of the system remains at zero.
Only if the cup is big enough and resistant to breaking, it will fly up. The volume, with zero mass inside, grows faster than the glass volume (assuming constant glass thickness). So the upward buoyancy force will exceed the total mass at some point. I only now saw the real problem. If you pull a vacuum in a cylinder with a piston and release the piston, the cylinder will accelerate oppositely. Likewise, the glass with a vacuum on the lower half will jump upward.
711,709
<https://what-if.xkcd.com/6/> has been mentioned here before, but I'm questioning whether or not the glass cup with the bottom half as a vacuum would rise at all. To start with, a vacuum exerts no force. Any perceived "sucking" is actually external pressure pushing into the vacuum. So the only force that could be lifting the glass would be buoyancy of the air around the cup. Let's ballpark it with a drinking cup that can hold about 500ml. If we consider the cup as an open-top cylinder, an internal radius of 3.8 cm and height of 11 cm gets us a 499ml volume, and the internal surface area is 308 cm^2. Based on a quick Google search, glass is about 2000x more dense than air, so in order for the glass to rise it would need to displace 2000x as much air as there is glass. That suggests that if the glass was sealed (by a weightless forcefield at the top) and was completely empty instead of having some water in it, the total volume of glass would have to be less than 0.5ml, resulting in an average width of 0.016mm. That's thinner than a human hair. Given that glass cups are significantly thicker than human hair1, is there any truth to the conclusions of that "What If?" Is there some effect that I've misunderstood or underestimated that significantly changes the situation? Or should we conclude, like <https://physics.stackexchange.com/a/33642/79374> did with the other vacuum cup, that Randall Munroe either miscalculated or was greatly exaggerating? 1 Citation needed
2022/06/01
[ "https://physics.stackexchange.com/questions/711709", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/79374/" ]
For a glass of water, the buoyant force is a small correction to the gravitational force arising because the pressure is different at different altitudes. The timescales in this problem are short enough that we can neglect the center-of-mass motion due to gravity, so we can absolutely neglect the center-of-mass motion due to the buoyant correction. The net force on the glass will be \begin{align} \vec F\_\text{net} &= \vec F\_\text{out} + \vec F\_\text{in} \\ &= \int P\_\text{air}\ \mathrm d\vec A\_\text{outside} + \int P\_\text{vacuum}\ \mathrm d\vec A\_\text{inside} \end{align} For a disc with air below and vacuum above, this force works out to be just the air pressure applied to the area of the disc. The drinking glasses in my kitchen have outer diameter $\rm 5\,cm$ at the base, so call the inner area $\rm 15\,cm^2$. (In the limit of a cylinder, the net vertical force on the glass walls is zero.) For a one-atmosphere pressure difference that’s a net force of $$ P\_\text{air} A\_\text{base} = 10^5\frac{\rm N}{\rm m^2} \cdot 15\rm\,cm^2 \color{lightgray}{ {}\times\left(\frac{1\rm\,m}{100\rm\,cm}\right)^2} = 150\rm\,N $$ This particular glass from my kitchen has a mass of about $\rm\frac13\,kg$, so with air below and vacuum above it would rocket upwards with an acceleration of about $45g$. (If you’d like, you can re-do the problem without neglecting gravity, and ask whether the correction to $44g$ upward is larger or smaller than our other simplifying assumptions.) If you consider the glass-plus-liquid as a single system, the no-gravity, no-buoyancy approximation is that the air pressure will symmetrically crush the water and the glass together without changing its center of mass: the water will move down and the glass will move up, so that the total momentum of the system remains at zero.
It's not just buoyancy because the slug of liquid can move. Your "force field" at the top of the glass modifies the premise of the XKCD scenario. If you look closely at the illustrations, his slug of liquid moves downward as the glass moves upward. The atmosphere pushes down on the slug of liquid and up on the glass, moving them both. But the center of mass of the system would not move.