qid
int64
1
74.7M
question
stringlengths
15
55.4k
date
stringlengths
10
10
metadata
sequencelengths
3
3
response_j
stringlengths
2
32.4k
response_k
stringlengths
9
40.5k
140
I have rabbits that routinely build nests in my yard. How can I get rid of the rabbits legally? I don't want some officer from the DNR knocking on my door because I improperly hunted or poisoned them. The rabbits cause several problems: 1. Our dog goes absolutely nuts barking at them through the window, chases them when she can in the back yard, and gently removes the young from their nest to play with (or tend to as a mother) when she finds a nest. 2. The nests are basically a hole in the ground about the size of a softball. They're easily big enough to cause a twisted ankle when stepped in while walking in the yard. 3. I'd like to start planting tomatoes and other vegetables, but I'm fearful the rabbits will have their way with my crops. I've recently started using [Liquid Fence](http://www.liquidfence.com/), but it's hard to say if that's had much of an effect. I've certainly still had some rabbits, but maybe not as often. What's the best course of action for me?
2011/06/08
[ "https://gardening.stackexchange.com/questions/140", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/105/" ]
Deer and rabbits both have a very keen sense of smell. I use a mixture of garlic powder, chili powder and water to keep the deer out of the garden. I am pretty sure that would work for rabbits as well. Spray it around where they are nesting and see if they move. If they do make up a large batch and spray the whole yard. I spray once a week on average. If it rains I spray again as soon as it's dry.
Every product I've tried hasn't worked for long. I finally put up chicken wire. That's the only thing that worked. What didn't work - Don't waste your money. An owl with light up eyes, moved every couple of days to a different spot. Many different brands of rabbit repellant, including Liquid Fence. Crushed up egg shells. Plastic snakes. All different colors. Spraying the bunnies with a garden hose - they come right back. What did work - I had three places to fence in. Once I got the hang of it, a 20' by 15' bed took me around an hour to install. I used 24" tall cheap chicken wire. It was around $10.00 for a 50 foot roll. I bought 8-foot 2" x 1" lumber for $1.00 apiece. I had each one cut into four 2-foot pieces. I used plastic zip ties to attach the chicken wire to the stakes. I spaced the stakes about 4 to 6 feet apart. On the first fence I buried the chicken wire a few inches. That worked. Then I tried bending the wire outward a few inches. That worked too. For the last bed I didn't bother burying it or bending it. That worked fine too. I thought they might chew through wood or the zip ties or burrow under the fences but they didn't. Good luck!
140
I have rabbits that routinely build nests in my yard. How can I get rid of the rabbits legally? I don't want some officer from the DNR knocking on my door because I improperly hunted or poisoned them. The rabbits cause several problems: 1. Our dog goes absolutely nuts barking at them through the window, chases them when she can in the back yard, and gently removes the young from their nest to play with (or tend to as a mother) when she finds a nest. 2. The nests are basically a hole in the ground about the size of a softball. They're easily big enough to cause a twisted ankle when stepped in while walking in the yard. 3. I'd like to start planting tomatoes and other vegetables, but I'm fearful the rabbits will have their way with my crops. I've recently started using [Liquid Fence](http://www.liquidfence.com/), but it's hard to say if that's had much of an effect. I've certainly still had some rabbits, but maybe not as often. What's the best course of action for me?
2011/06/08
[ "https://gardening.stackexchange.com/questions/140", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/105/" ]
After just reading the title, I was going to suggest get a dog. Our dog has killed a couple rabbits already this year. Perhaps you could simply leave your dog in the yard more often, letting him/her out when she's barking at them through the window. I guess this depends if your dog is fast enough to catch them. You could consider getting another dog, perhaps a bigger, faster one. Another note: when putting in vegetables, make sure you have a sure method of keeping your dog out of them. Our dog ate quite a few of our green beans last year (didn't bother the tomatoes, though), so we had to put up a higher fence this year.
Every product I've tried hasn't worked for long. I finally put up chicken wire. That's the only thing that worked. What didn't work - Don't waste your money. An owl with light up eyes, moved every couple of days to a different spot. Many different brands of rabbit repellant, including Liquid Fence. Crushed up egg shells. Plastic snakes. All different colors. Spraying the bunnies with a garden hose - they come right back. What did work - I had three places to fence in. Once I got the hang of it, a 20' by 15' bed took me around an hour to install. I used 24" tall cheap chicken wire. It was around $10.00 for a 50 foot roll. I bought 8-foot 2" x 1" lumber for $1.00 apiece. I had each one cut into four 2-foot pieces. I used plastic zip ties to attach the chicken wire to the stakes. I spaced the stakes about 4 to 6 feet apart. On the first fence I buried the chicken wire a few inches. That worked. Then I tried bending the wire outward a few inches. That worked too. For the last bed I didn't bother burying it or bending it. That worked fine too. I thought they might chew through wood or the zip ties or burrow under the fences but they didn't. Good luck!
24,517
As title above, how to play vs. ``` [fen ""] 1.e4 e5 2.Nf3 Nc6 3.Bc4 d6 ``` I see that this move (3...d6) is generally considered inferior in books, or not even mentioned in books about 3.Bc4, but I cannot see a clear way to obtain advantage.
2019/05/18
[ "https://chess.stackexchange.com/questions/24517", "https://chess.stackexchange.com", "https://chess.stackexchange.com/users/8291/" ]
The game will get the characteristics of the Philidor Defense rather than the Italian Game. Wikipedia calls it the [Semi-Italian Opening](https://en.wikipedia.org/wiki/Semi-Italian_Opening). > > I. A. Horowitz called the defence "solid", also writing: "It does not seem quite sufficient for equality." > > > The Wikipedia article notes several possible continuations for White, with 4. d4 probably the best bet for advantage.
There is no way to "crush" that move. You just play! Develop your pieces, get space in the center and obtain a small advantage. Your opponent won't be losing a piece or something like that. I assume 3...d6 may have some ideas related to a pin on g4 (for instance, 4.d4 Bg4) A c3 pawn advance can be useful to prevent some ...Nd4. I think you'll be fine after 4.0-0 Bg4 5.c3, but also 4.Nc3 Bg4 5.h3 or many other sequences In short, I don't know what the best answer is. I doubt anyone in the world actually does. Analyze your games and find what works best for yourself
24,517
As title above, how to play vs. ``` [fen ""] 1.e4 e5 2.Nf3 Nc6 3.Bc4 d6 ``` I see that this move (3...d6) is generally considered inferior in books, or not even mentioned in books about 3.Bc4, but I cannot see a clear way to obtain advantage.
2019/05/18
[ "https://chess.stackexchange.com/questions/24517", "https://chess.stackexchange.com", "https://chess.stackexchange.com/users/8291/" ]
1.e4 e5 2.Nf3 Nc6 3.Bc4 d6: 365chess.com database shows: ``` MOVE | games | year | White + Draw + Black -------+-------+------+--------+--------+------- 4. d4 | 491 | 2018 | 50.3 % | 24.4 % | 25.3 % 4. c3 | 359 | 2018 | 53.5 % | 20.6 % | 25.9 % 4. d3 | 357 | 2018 | 45.4 % | 22.7 % | 31.9 % 4. h3 | 323 | 2016 | 42.7 % | 25.7 % | 31.6 % 4. Nc3 | 289 | 2018 | 50.9 % | 16.3 % | 32.9 % 4. O-O | 249 | 2019 | 50.6 % | 22.1 % | 27.3 % ``` White will get a space advantage and freer development after d4 (whether delayed or played immediately). Or White can play the pawn to d3 and the fact that his Bishop is outside the pawn chain (and Blacks Bf8 is inside) gives White an easier position. There is no knock-out blow for White as Black is accepting a slightly passive but solid position.
There is no way to "crush" that move. You just play! Develop your pieces, get space in the center and obtain a small advantage. Your opponent won't be losing a piece or something like that. I assume 3...d6 may have some ideas related to a pin on g4 (for instance, 4.d4 Bg4) A c3 pawn advance can be useful to prevent some ...Nd4. I think you'll be fine after 4.0-0 Bg4 5.c3, but also 4.Nc3 Bg4 5.h3 or many other sequences In short, I don't know what the best answer is. I doubt anyone in the world actually does. Analyze your games and find what works best for yourself
72,902,209
how to create a regex that replaces a space with an underscore and adds spaces between semicolons? Replacing a space with a underscore in the entire text can be solved: ``` data.replace(/ /g, "_"); ``` But how to solve the situation with semicolons at the same time? The point is that I have a text file that separates individual texts with an underscore. If it does not contain any data, it simply continues in the next semicolons: ``` data;data;;data;;;data ``` I need it to add a blank space between the semicolons in each case. The problem is that the number of semicolons is irregular and I always need to add a space: ``` data;data; ;data; ; ;data ``` There are more than 10,000 such lines in the text file. Is there a solution for my case? ```js const data = "red;;I WW2;123;;;error;more;;blue;;;;123;I love you"; const replaceData = data.replace(/ /g, "_"); /* // //This is not a solution for me, as the number of semicolons is not always the same. And I also can't combine this regex into one. // //const replaceData2 = data.replace(/;;/g, "; ;"); */ console.log(replaceData); ``` The result should be like this: ``` red; ;I_WW2;123; ; ;error;more; ;blue; ; ; ;123;I_love_you ``` Thanks
2022/07/07
[ "https://Stackoverflow.com/questions/72902209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12648892/" ]
You can call `.replace` twice: ```js const data = "red;;I WW2;123;;;error;more;;blue;;;;123;I love you"; var repl = data.replace(/ +/g, "_").replace(/;(?=;)/g, "$& "); console.log(repl); ``` But make sure to replace spaces with `_` before inserting spaces between `;`s. * `.replace(/ +/g, "_")`: Replace 1+ spaces with `_` * `.replace(/;(?=;)/g, "$& ")`: Insert space between 2 adjacent semicolons
If you want to do it with one regex, it can be done with a callback argument, but this will also cost execution time. Like I wrote in comments, it may turn out to be better to stick with 2 `replace` calls. Just see how it performs in your environment, and on your data. Here is how it would work with callback: ```js const data = "red;;I WW2;123;;;error;more;;blue;;;;123;I love you"; const result = data.replace(/ |(?<=;)(?=;)/g, m => " _"[m.length]); console.log(result); ``` The regex has a zero-length match between two semi-colons, so when it matches that, `m` will be the empty string (in the callback). So the size of `m` can be used to distinguish the two cases, and `length` can then serve to select the replacement character (either a space or an underscore).
72,902,209
how to create a regex that replaces a space with an underscore and adds spaces between semicolons? Replacing a space with a underscore in the entire text can be solved: ``` data.replace(/ /g, "_"); ``` But how to solve the situation with semicolons at the same time? The point is that I have a text file that separates individual texts with an underscore. If it does not contain any data, it simply continues in the next semicolons: ``` data;data;;data;;;data ``` I need it to add a blank space between the semicolons in each case. The problem is that the number of semicolons is irregular and I always need to add a space: ``` data;data; ;data; ; ;data ``` There are more than 10,000 such lines in the text file. Is there a solution for my case? ```js const data = "red;;I WW2;123;;;error;more;;blue;;;;123;I love you"; const replaceData = data.replace(/ /g, "_"); /* // //This is not a solution for me, as the number of semicolons is not always the same. And I also can't combine this regex into one. // //const replaceData2 = data.replace(/;;/g, "; ;"); */ console.log(replaceData); ``` The result should be like this: ``` red; ;I_WW2;123; ; ;error;more; ;blue; ; ; ;123;I_love_you ``` Thanks
2022/07/07
[ "https://Stackoverflow.com/questions/72902209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12648892/" ]
You can call `.replace` twice: ```js const data = "red;;I WW2;123;;;error;more;;blue;;;;123;I love you"; var repl = data.replace(/ +/g, "_").replace(/;(?=;)/g, "$& "); console.log(repl); ``` But make sure to replace spaces with `_` before inserting spaces between `;`s. * `.replace(/ +/g, "_")`: Replace 1+ spaces with `_` * `.replace(/;(?=;)/g, "$& ")`: Insert space between 2 adjacent semicolons
this will help you to get your desire output. 1. Positive Lookbehind (?<=;) 2. Positive Lookahead (?=;) and we replace it with `" "` `space`. ```js const data = "red;;I WW2;123;;;error;more;;blue;;;;123;I love you"; const replaceData = data.replace(/(?<=;)(?=;)/g, " "); console.log(replaceData) ```
26,339
Every `Account` has its owner who is `Person` The bank has list of owners. I am not sure if my destructors are right and `delete bank` will delete all elements of `list<Account*>* v` nad the list itself. Please help. ``` #include <iostream> #include <vector> #include <list> using namespace std; class Person{ public: char* name; int age; Person(char* name, int age){ this->name = name; this->age = age; } ~Person(){ } void show(){ cout<<name<<" "<<age<<" yo"; } }; class Account{ public: Person& owner; double money; Account(Person* owner, double money): owner(*owner) , // this->owner = *owner; money(money) { //Uninitialized reference member } void show(){ cout<<"\n-------------\n"; owner.show(); cout<<endl; cout<<money<<"USD\n-------------"; } ~Account(){ } }; class Bank{ public: list<Account*>* v; Bank(){ v = new list<Account*>(); } Account* openNewAccount(Person* client, double money){ Account* r = new Account(client, money); v->push_back(r); return r; } void zmienWlasciciela(Person& o, Account* r){ r->owner = o; } void usunRachunek(Account* r){ cout<<"\n\n\nUSUNALEM"<<endl; v->remove(r); delete r; } void show(){ for (list<Account*>::iterator it = v->begin(); it != v->end(); ++it){ (*it)->show(); } } ~Bank(){ delete v; } }; int main(){ Bank* bank = new Bank(); Person* thomas = new Person("thomas", 34); Account* r1 = bank->openNewAccount(thomas, 64363.32); Account* r2 = bank->openNewAccount(thomas, 41251.54); Account* r3 = bank->openNewAccount(thomas, 3232.32); bank->show(); Person* margaret = new Person("Margaret", 23); bank->zmienWlasciciela(*margaret, r2); cout<<"I have changed owner of account r2"<<endl; bank->show(); cout<<"I have deleted account r3"<<endl; bank->usunRachunek(r3); bank->show(); delete bank; return 0; } ```
2013/05/19
[ "https://codereview.stackexchange.com/questions/26339", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/25235/" ]
General Comment on Style ------------------------ This is probably not what you want. ``` Bank* bank = new Bank(); Person* thomas = new Person("thomas", 34); ``` You actually want: ``` Bank bank; Person thomas("thomas", 34); ``` This creates automatic variables. That are properly destroyed automatically at the end of scope. It is very rare to use RAW pointers in C++ `Bank*` or `Person*`. When you dynamically allocate objects using `new` you want to make sure that the returned pointer is put into an object that controls their lifespan and garbage collects the values when you are finished using them. ``` std::shared_ptr<Bank> bank = new Bank; // This is the closest to a Java object // that C++ has. It allows multiple users // and it is correctly destroyed when nobody // has a reference to it anymore. ``` Looking at the code: -------------------- Don't do this: ``` using namespace std; ``` I know all the shitty C++ books you read have it in. Its fine for 10 line long programs you type out of a book. But once you get past those programs it can cause problems with namespace pollution. Its thus a very bad habit and one you should break as soon as possible. See: <https://stackoverflow.com/q/1452721/14065> ### Person Pointers are bad. ``` char* name; ``` Unless you do a lot of validation and know the ownership of the thing you are pointing at and it is not going to be cleaned up behind you then you should be very weary of using pointers. I have checked your code and you are fine in this simple program but this is not a good design outside of a small toy project. C++ also has its own string type `std::string` so you don't need to know or use C-String. So I would change this to ``` std::string name; ``` In constructors prefer to use the initializer list to initialize the members. ``` Person(char* name, int age){ this->name = name; this->age = age; } ``` Second point about pointers here. Its not normal to pass pointers to around in C++ (this is very common in C but modern C++ you should basically never do it (with a few exceptions that you will work out when you have more experience)). Pass objects by reference if you want to retain ownership; otherwise pass a smart\_pointer to transfer ownership of the object. In this case you want to pass a `std::string`. As you don't want to change the original but make your own copy pass a const reference (if you are in C++11 you may want to also add a move constructor (but this is advanced so don't worry about it)). So it should look more like: ``` Person(std::string const& name, int age) : name(name) , age(age) {} ``` If a destructor does not do anything then don't declare it. ``` ~Person(){ } ``` Its fine to have a public `show()` method. But any method that does not change the state of the object should be declared as `const`. This allows you to call the object from const objects (useful technique later). And if you add a parameter so it can be any stream it makes it more versatile. But you should also declare a stream operator for your Person type. Thus you can stream your person just like any other type. ``` void show(std::ostream& out = std::cout) const { // ^^^^^ Does not change the state // so make the method const. // ^^^^^^^^^^^^^^^^^ Pass stream to print on. // You may want to print in other places. // rather than std::cout (like a file). out<<name<<" "<<age<<" yo"; // A few spaces to make it readable // would be nice. } // Pass person by const reference so the compiler // knows you are not going to modify the object. // This means you can only call const methods (so `show()` must be const. std::ostream& operator<<(std::stream& stream, Person const& person) { person.show(stream); return stream; } int main() { std::cout << Perons("Loki", 962) << "\n"; } ``` ### Account This is fine. ``` Person& owner; ``` It means you have a reference to a person that is stored somewhere else. But you need to be careful of lifetimes. Make sure the `Person` object is still alive while you are alive. Passing by pointer again. ``` Account(Person* owner, double money): ``` This is dangerous. Especially since you de-reference without checking. Since you are storing a reference. Pass the value in by reference. ``` Account(Person& owner, double money) : owner(owner) , money(money) {} ``` Make the `show()` method const and pass a stream. ``` void show(std::ostream& out = std::cout) const { // ^^^^^ out<<"\n-------------\n" << owner << std::endl << money<<"USD\n-------------"; return out; } ``` Add a stream operator ``` std::ostream& operator<<(std::stream& stream, Account const& account) { account.show(stream); } ``` Destructor does nothing so remove it. ``` ~Account(){ } ``` ### Bank Ok. Obviously a java (or java inspired language user). ``` list<Account*>* v; ``` You don't want to use pointers here. By making this a pointer you need to do all sorts of memory management (and make sure you obey the rule of three (look it up)). But you don't need to do that just make it a normal object and all those problems go away. list v; When the bank object is created. It automatically creates a list now. When the bank is destroyed it automatically cleans up its members (including the list). When the back is copied it automatically copies the accounts to the new Bank. Second; don't make the Account's inside the list pointers. Again you will need to manage the each object and control its lifespan. Much easier to put Account objects into the list. list v; There is also a principle called `Separation of Concerns`. Basically this says that an type should either be `Business Logic` or `Resource Management` you should not do both in the same type. Since `Bank` is obviously business logic you should not be doing resource management in the Bank. If you were using pointers then you would delegate the memory management of those pointers to anther type that would correctly do the clean up. C++ already has a whole bunch of smart pointers explicitly for managing pointers. **BUT** in this situation I would defiantly sidestep the memory management by using automatic objects and make the changes I described above as **ALL** your memory management issues disappear. Remember use initializer list. ``` Bank(){ v = new list<Account*>(); } ``` But if you change the type as (described above) you don't need to do anything. The object automatically creates and initializes all members. Again passing pointers is bad: ``` Account* openNewAccount(Person* client, double money){ Account* r = new Account(client, money); v->push_back(r); return r; } ``` If you return a pointer `Account*` you don't specify any ownership semantics. If you don't specify ownership semantics then you are very liable to leak as nobody knows who is supposed to clean up. In this situation the `Account` obviously belongs to the Bank object (The Bank will do the memory management). So here you should return a reference. This is an indication you can use the account. But the account will be managed by the Bank. ``` Account& openNewAccount(Person const& client, double money) { Account newAccount(client, money); // Create a new account. v->push_back(newAccount); // Not when you push objects into containers // they make a copy of the object. // So you have a copy of `newAccount` return v.last(); // return a reference to the last member of `v` // that you just pushed there via `push_back` // The user can now operate on the referenc // Also the reference will never be NULL // so the user needs to check for that. } ``` Pass by reference. You don't need to check for NULL ``` void zmienWlasciciela(Person& o, Account* r) // Becomes. void zmienWlasciciela(Person& o, Account& r){ r.owner = o; } ``` Pass by reference (that's how it was given to you). ``` void usunRachunek(Account* r) // Becomes void usunRachunek(Account* r){ cout<<"\n\n\nUSUNALEM"<<endl; v.remove(r); } ``` Make `show()` const and take a stream ``` void show(std::ostream& out = std::cout ) const { for (list<Account*>::iterator it = v.begin(); it != v.end(); ++it){ (*it)->show(out); } ``` You could use a simple algorithm to copy the Account to the stream. ``` void show(std::ostream& out = std::cout ) const { // for this to work Account must have operator<< defined. std::copy(v.begin(), v.end(), std::ostream_iterator(out)); } } ``` This is correct **BUT NOT ENOUGH** for your original definition where v is a pointer. If you use objects you don't need to do anything. ``` ~Bank(){ delete v; } ``` If you were using pointers then you also need to define a copy constructor and assignment operator to make sure you are not violating the rule of three. If you are using objects the compiler generated defaults work perfectly fine.
Deleting the vector will only delete the pointers in the vector, not the things to which they point. You need to iterate though the vector deleting the accounts before deleting the vector.
27,070,425
I have been working on this form and can't get past the CalculateTotal. I am completely lost on how to get this to add up and display in the box. Can anyone help? Here is my jsfiddle <http://jsfiddle.net/clbacon70/x6kjqbop/1/> ```js var gc_fSandwichPrice = 5.99; // Price for each sandwich var gc_fExtrasPrice = 1.50; // Price for each extra item // GLOBAL VARS // Global object vars var divErrors; var radSandwich; var radSize; var chkExtras; // Other global vars var g_fTotal; var g_sSandwich; var g_sSize; var g_sExtras; window.addEventListener('load', Init); function Init() { document.getElementById("h1Title").innerHTML = "Dirty Deli 1.0"; var spanExtrasPrice = document.getElementById("spanExtrasPrice"); var btnCalculateTotal = document.getElementById("btnCalculateTotal"); divErrors = document.getElementById("divErrors"); radSandwich = document.getElementsByName('radSandwich'); radSize = document.getElementsByName('radSize'); chkExtras = document.getElementsByName('chkExtras'); spanExtrasPrice.innerHTML = gc_fExtrasPrice.toFixed(2); btnCalculateTotal.addEventListener('click', CalculateTotal); } // function Init() function CalculateTotal() { divErrors.innerHTML = ''; if (radSandwich[0].checked) { g_sSandwich = radSandwich[0].value; } else if (radSandwich[1].checked) { g_sSandwich = radSandwich[1].value; } else if (radSandwich[2].checked) { g_sSandwich = radSandwich[2].value; } else if (radSandwich[3].checked) { g_sSandwich = radSandwich[3].value; } else { divErrors.innerHTML = "Select a Sandwich"; return; } if (radSize[0].checked){ g_fTotal = radSize[0].title; } else if (radSize[1].checked) { g_fTotal = radSize[1].title; } else if (radSize[2].checked) { g_fTotal = radSize[2].title; } else { divErrors.innerHTML = "Please choose a size"; return; } if (chkExtras[0].checked) { g_sExtras = chkExtras[0].value; g_fTotal = g_fTotal + gc_fExtrasPrice; } if (chkExtras[1].checked) { g_sExtras = g_sExtras + ',' + chkExtras[1].value; g_fTotal = g_fTotal + gc_fExtrasPrice; } if (chkExtras[2].checked) { g_sExtras = g_sExtras +', ' + chkExtras[2].value; g_fTotal = g_fTotal + gc_fExtrasPrice; } var textTotal = document.getElementById('textTotal'); textTotal.value = g_fTotal; } // function CalculateTotal function ProcessOrder() { } // function ProcessOrder ``` ```css * { margin: 0; padding: 0; } body { background-color: #333; } #divWrapper { background-color: #efe; width: 40em; border: solid black; border-radius: 0 0 20px 20px; border-width: 0 1px 1px 1px; margin: 0 auto; padding: 2em 1em; } h2 { font-style: italic; font-size: 1.3em; color: #666; margin-top: 0px; } input { margin-right: 0.3em; } h3, p { margin: 0.5em 0; } div#divErrors { font-size: 110%; color: white; background: #f00; margin-bottom: 0.5em; } #divPaymentInfo { margin: 10px 0 20px 0; padding-bottom: 10px; border: solid black; border-width: 1px 0; } #divCreditCardInfo { font-size: .8em; visibility: hidden; margin-left: 1em; display: inline; } #divOrder { background: white; min-height: 10em; width: 25em; border: 1px solid black; margin: 0.5em 0; padding: 10px; } ``` ```html <body> <div id="divWrapper"> <form name="frmMain"> <h1 id="h1Title">Deli Form</h1> <h2>Part 1</h2> <h3>Sandwich</h3> <label><input type="radio" name="radSandwich" value="Breast of Chicken">Breast of Chicken</label><br> <label><input type="radio" name="radSandwich" value="Leg of Lamb">Leg of Lamb</label><br> <label><input type="radio" name="radSandwich" value="Loin of Ham">Loin of Ham</label><br> <label><input type="radio" name="radSandwich" value="ReelMeat&reg;">ReelMeat&reg;</label><br> <br> <h3>Size</h3> <label><input type="radio" name="radSize" value="Manly Man" title="$4.99">Manly Man</label>&nbsp;&nbsp; <label><input type="radio" name="radSize" value="Girly Man" title="$5.99">Girly Man</label>&nbsp;&nbsp; <label><input type="radio" name="radSize" value="Super Girly Man" title="$6.99">Super Girly Man</label> <br><br> <h3>Extras ($<span id="spanExtrasPrice"></span> each)</h3> <label><input type="checkbox" name="chkExtras" value="Deep-Fried Spam">Deep-Fried Spam</label><br> <label><input type="checkbox" name="chkExtras" value="Toenails">Toenails</label><br> <label><input type="checkbox" name="chkExtras" value="Secret Sauce">Secret Sauce</label><br> <br><br> Total: <input type="text" id="txtTotal" size="5"> <input type="button" id="btnCalculateTotal" value="Calculate Total"> <br><br> <div id="divErrors"></div> <div id="divPaymentInfo"> <h2>Part 2</h2> <strong>Customer's Name:</strong> <input type="text" id="txtName"> <br><br> <strong>Payment:</strong> <select id="selPayment"> <option value="Cash" selected="selected">Cash</option> <option value="Check">Check</option> <option value="Credit Card">Credit Card</option> </select> <div id="divCreditCardInfo"> Card Number: <input type="text" id="txtCreditCardNbr" size="20">&nbsp;&nbsp; Month: <input type="text" id="txtMonth" size="2">&nbsp;&nbsp;Year: <select id="selYear"> <option value="" selected="selected"></option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> <option value="2010">2017</option> <option value="2011">2018</option> </select> </div><!-- divCreditCardInfo --> </div><!-- divPaymentInfo --> <input type="button" id="btnProcessOrder" value="Process Order"> <div id="divOrder"></div> <input type="reset" value="Reset"> </form> </div> <!-- divWrapper --> </body> ```
2014/11/21
[ "https://Stackoverflow.com/questions/27070425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3381376/" ]
You have a typo in your javascript. You are attempting to fetch an html element with id `textTotal`, when the field you're interesting in is actually given the id `txtTotal`. Fix that typo and it will work.
You have to add brackets after 'Init'. ``` window.addEventListener('load', Init()); ``` And also there was a typo in the end of CalculateTotal function. Here is working example: <http://jsfiddle.net/x6kjqbop/3/>
27,070,425
I have been working on this form and can't get past the CalculateTotal. I am completely lost on how to get this to add up and display in the box. Can anyone help? Here is my jsfiddle <http://jsfiddle.net/clbacon70/x6kjqbop/1/> ```js var gc_fSandwichPrice = 5.99; // Price for each sandwich var gc_fExtrasPrice = 1.50; // Price for each extra item // GLOBAL VARS // Global object vars var divErrors; var radSandwich; var radSize; var chkExtras; // Other global vars var g_fTotal; var g_sSandwich; var g_sSize; var g_sExtras; window.addEventListener('load', Init); function Init() { document.getElementById("h1Title").innerHTML = "Dirty Deli 1.0"; var spanExtrasPrice = document.getElementById("spanExtrasPrice"); var btnCalculateTotal = document.getElementById("btnCalculateTotal"); divErrors = document.getElementById("divErrors"); radSandwich = document.getElementsByName('radSandwich'); radSize = document.getElementsByName('radSize'); chkExtras = document.getElementsByName('chkExtras'); spanExtrasPrice.innerHTML = gc_fExtrasPrice.toFixed(2); btnCalculateTotal.addEventListener('click', CalculateTotal); } // function Init() function CalculateTotal() { divErrors.innerHTML = ''; if (radSandwich[0].checked) { g_sSandwich = radSandwich[0].value; } else if (radSandwich[1].checked) { g_sSandwich = radSandwich[1].value; } else if (radSandwich[2].checked) { g_sSandwich = radSandwich[2].value; } else if (radSandwich[3].checked) { g_sSandwich = radSandwich[3].value; } else { divErrors.innerHTML = "Select a Sandwich"; return; } if (radSize[0].checked){ g_fTotal = radSize[0].title; } else if (radSize[1].checked) { g_fTotal = radSize[1].title; } else if (radSize[2].checked) { g_fTotal = radSize[2].title; } else { divErrors.innerHTML = "Please choose a size"; return; } if (chkExtras[0].checked) { g_sExtras = chkExtras[0].value; g_fTotal = g_fTotal + gc_fExtrasPrice; } if (chkExtras[1].checked) { g_sExtras = g_sExtras + ',' + chkExtras[1].value; g_fTotal = g_fTotal + gc_fExtrasPrice; } if (chkExtras[2].checked) { g_sExtras = g_sExtras +', ' + chkExtras[2].value; g_fTotal = g_fTotal + gc_fExtrasPrice; } var textTotal = document.getElementById('textTotal'); textTotal.value = g_fTotal; } // function CalculateTotal function ProcessOrder() { } // function ProcessOrder ``` ```css * { margin: 0; padding: 0; } body { background-color: #333; } #divWrapper { background-color: #efe; width: 40em; border: solid black; border-radius: 0 0 20px 20px; border-width: 0 1px 1px 1px; margin: 0 auto; padding: 2em 1em; } h2 { font-style: italic; font-size: 1.3em; color: #666; margin-top: 0px; } input { margin-right: 0.3em; } h3, p { margin: 0.5em 0; } div#divErrors { font-size: 110%; color: white; background: #f00; margin-bottom: 0.5em; } #divPaymentInfo { margin: 10px 0 20px 0; padding-bottom: 10px; border: solid black; border-width: 1px 0; } #divCreditCardInfo { font-size: .8em; visibility: hidden; margin-left: 1em; display: inline; } #divOrder { background: white; min-height: 10em; width: 25em; border: 1px solid black; margin: 0.5em 0; padding: 10px; } ``` ```html <body> <div id="divWrapper"> <form name="frmMain"> <h1 id="h1Title">Deli Form</h1> <h2>Part 1</h2> <h3>Sandwich</h3> <label><input type="radio" name="radSandwich" value="Breast of Chicken">Breast of Chicken</label><br> <label><input type="radio" name="radSandwich" value="Leg of Lamb">Leg of Lamb</label><br> <label><input type="radio" name="radSandwich" value="Loin of Ham">Loin of Ham</label><br> <label><input type="radio" name="radSandwich" value="ReelMeat&reg;">ReelMeat&reg;</label><br> <br> <h3>Size</h3> <label><input type="radio" name="radSize" value="Manly Man" title="$4.99">Manly Man</label>&nbsp;&nbsp; <label><input type="radio" name="radSize" value="Girly Man" title="$5.99">Girly Man</label>&nbsp;&nbsp; <label><input type="radio" name="radSize" value="Super Girly Man" title="$6.99">Super Girly Man</label> <br><br> <h3>Extras ($<span id="spanExtrasPrice"></span> each)</h3> <label><input type="checkbox" name="chkExtras" value="Deep-Fried Spam">Deep-Fried Spam</label><br> <label><input type="checkbox" name="chkExtras" value="Toenails">Toenails</label><br> <label><input type="checkbox" name="chkExtras" value="Secret Sauce">Secret Sauce</label><br> <br><br> Total: <input type="text" id="txtTotal" size="5"> <input type="button" id="btnCalculateTotal" value="Calculate Total"> <br><br> <div id="divErrors"></div> <div id="divPaymentInfo"> <h2>Part 2</h2> <strong>Customer's Name:</strong> <input type="text" id="txtName"> <br><br> <strong>Payment:</strong> <select id="selPayment"> <option value="Cash" selected="selected">Cash</option> <option value="Check">Check</option> <option value="Credit Card">Credit Card</option> </select> <div id="divCreditCardInfo"> Card Number: <input type="text" id="txtCreditCardNbr" size="20">&nbsp;&nbsp; Month: <input type="text" id="txtMonth" size="2">&nbsp;&nbsp;Year: <select id="selYear"> <option value="" selected="selected"></option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> <option value="2010">2017</option> <option value="2011">2018</option> </select> </div><!-- divCreditCardInfo --> </div><!-- divPaymentInfo --> <input type="button" id="btnProcessOrder" value="Process Order"> <div id="divOrder"></div> <input type="reset" value="Reset"> </form> </div> <!-- divWrapper --> </body> ```
2014/11/21
[ "https://Stackoverflow.com/questions/27070425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3381376/" ]
``` var textTotal = document.getElementById('textTotal'); ``` Your selector is wrong. The element id of your textbox is `txtTotal` so the following should work: ``` var textTotal = document.getElementById('txtTotal'); ```
You have to add brackets after 'Init'. ``` window.addEventListener('load', Init()); ``` And also there was a typo in the end of CalculateTotal function. Here is working example: <http://jsfiddle.net/x6kjqbop/3/>
27,070,425
I have been working on this form and can't get past the CalculateTotal. I am completely lost on how to get this to add up and display in the box. Can anyone help? Here is my jsfiddle <http://jsfiddle.net/clbacon70/x6kjqbop/1/> ```js var gc_fSandwichPrice = 5.99; // Price for each sandwich var gc_fExtrasPrice = 1.50; // Price for each extra item // GLOBAL VARS // Global object vars var divErrors; var radSandwich; var radSize; var chkExtras; // Other global vars var g_fTotal; var g_sSandwich; var g_sSize; var g_sExtras; window.addEventListener('load', Init); function Init() { document.getElementById("h1Title").innerHTML = "Dirty Deli 1.0"; var spanExtrasPrice = document.getElementById("spanExtrasPrice"); var btnCalculateTotal = document.getElementById("btnCalculateTotal"); divErrors = document.getElementById("divErrors"); radSandwich = document.getElementsByName('radSandwich'); radSize = document.getElementsByName('radSize'); chkExtras = document.getElementsByName('chkExtras'); spanExtrasPrice.innerHTML = gc_fExtrasPrice.toFixed(2); btnCalculateTotal.addEventListener('click', CalculateTotal); } // function Init() function CalculateTotal() { divErrors.innerHTML = ''; if (radSandwich[0].checked) { g_sSandwich = radSandwich[0].value; } else if (radSandwich[1].checked) { g_sSandwich = radSandwich[1].value; } else if (radSandwich[2].checked) { g_sSandwich = radSandwich[2].value; } else if (radSandwich[3].checked) { g_sSandwich = radSandwich[3].value; } else { divErrors.innerHTML = "Select a Sandwich"; return; } if (radSize[0].checked){ g_fTotal = radSize[0].title; } else if (radSize[1].checked) { g_fTotal = radSize[1].title; } else if (radSize[2].checked) { g_fTotal = radSize[2].title; } else { divErrors.innerHTML = "Please choose a size"; return; } if (chkExtras[0].checked) { g_sExtras = chkExtras[0].value; g_fTotal = g_fTotal + gc_fExtrasPrice; } if (chkExtras[1].checked) { g_sExtras = g_sExtras + ',' + chkExtras[1].value; g_fTotal = g_fTotal + gc_fExtrasPrice; } if (chkExtras[2].checked) { g_sExtras = g_sExtras +', ' + chkExtras[2].value; g_fTotal = g_fTotal + gc_fExtrasPrice; } var textTotal = document.getElementById('textTotal'); textTotal.value = g_fTotal; } // function CalculateTotal function ProcessOrder() { } // function ProcessOrder ``` ```css * { margin: 0; padding: 0; } body { background-color: #333; } #divWrapper { background-color: #efe; width: 40em; border: solid black; border-radius: 0 0 20px 20px; border-width: 0 1px 1px 1px; margin: 0 auto; padding: 2em 1em; } h2 { font-style: italic; font-size: 1.3em; color: #666; margin-top: 0px; } input { margin-right: 0.3em; } h3, p { margin: 0.5em 0; } div#divErrors { font-size: 110%; color: white; background: #f00; margin-bottom: 0.5em; } #divPaymentInfo { margin: 10px 0 20px 0; padding-bottom: 10px; border: solid black; border-width: 1px 0; } #divCreditCardInfo { font-size: .8em; visibility: hidden; margin-left: 1em; display: inline; } #divOrder { background: white; min-height: 10em; width: 25em; border: 1px solid black; margin: 0.5em 0; padding: 10px; } ``` ```html <body> <div id="divWrapper"> <form name="frmMain"> <h1 id="h1Title">Deli Form</h1> <h2>Part 1</h2> <h3>Sandwich</h3> <label><input type="radio" name="radSandwich" value="Breast of Chicken">Breast of Chicken</label><br> <label><input type="radio" name="radSandwich" value="Leg of Lamb">Leg of Lamb</label><br> <label><input type="radio" name="radSandwich" value="Loin of Ham">Loin of Ham</label><br> <label><input type="radio" name="radSandwich" value="ReelMeat&reg;">ReelMeat&reg;</label><br> <br> <h3>Size</h3> <label><input type="radio" name="radSize" value="Manly Man" title="$4.99">Manly Man</label>&nbsp;&nbsp; <label><input type="radio" name="radSize" value="Girly Man" title="$5.99">Girly Man</label>&nbsp;&nbsp; <label><input type="radio" name="radSize" value="Super Girly Man" title="$6.99">Super Girly Man</label> <br><br> <h3>Extras ($<span id="spanExtrasPrice"></span> each)</h3> <label><input type="checkbox" name="chkExtras" value="Deep-Fried Spam">Deep-Fried Spam</label><br> <label><input type="checkbox" name="chkExtras" value="Toenails">Toenails</label><br> <label><input type="checkbox" name="chkExtras" value="Secret Sauce">Secret Sauce</label><br> <br><br> Total: <input type="text" id="txtTotal" size="5"> <input type="button" id="btnCalculateTotal" value="Calculate Total"> <br><br> <div id="divErrors"></div> <div id="divPaymentInfo"> <h2>Part 2</h2> <strong>Customer's Name:</strong> <input type="text" id="txtName"> <br><br> <strong>Payment:</strong> <select id="selPayment"> <option value="Cash" selected="selected">Cash</option> <option value="Check">Check</option> <option value="Credit Card">Credit Card</option> </select> <div id="divCreditCardInfo"> Card Number: <input type="text" id="txtCreditCardNbr" size="20">&nbsp;&nbsp; Month: <input type="text" id="txtMonth" size="2">&nbsp;&nbsp;Year: <select id="selYear"> <option value="" selected="selected"></option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> <option value="2010">2017</option> <option value="2011">2018</option> </select> </div><!-- divCreditCardInfo --> </div><!-- divPaymentInfo --> <input type="button" id="btnProcessOrder" value="Process Order"> <div id="divOrder"></div> <input type="reset" value="Reset"> </form> </div> <!-- divWrapper --> </body> ```
2014/11/21
[ "https://Stackoverflow.com/questions/27070425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3381376/" ]
Here's a fixed copy of your jsFiddle: <http://jsfiddle.net/dcseekcw/> What I fixed: * You were passing in `$` along with values you were trying to add as floats. Removed them from your title values and only put it back in after the total is calculated. * Put in parseFloat so values could be added together instead of being concatenated as strings. * Initialised your `g_fTotal` and `chkExtras` variables. * Put in some basic checking so that `radSize` doesn't cause problems when it's not selected.
You have to add brackets after 'Init'. ``` window.addEventListener('load', Init()); ``` And also there was a typo in the end of CalculateTotal function. Here is working example: <http://jsfiddle.net/x6kjqbop/3/>
5,813,823
I am working for Translate animation of two images overlapping each other and both Images should translate from top to middle of the screen. plesee share some sample programmes for this Help is always appreciated, ....Thanks!
2011/04/28
[ "https://Stackoverflow.com/questions/5813823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
anim.xml ``` <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <translate android:fromYDelta="0" android:toYDelta="50%p" android:duration="1000"/> </set> ``` in java file.. ``` Animation anim = AnimationUtils.loadAnimation(activity, R.anim.anim); anim.setInterpolator((new AccelerateDecelerateInterpolator())); anim.setFillAfter(true); ImageView.setAnimation(anim); ```
To animate from **Top to middle** of screen it should be something like this **anmation.xml** ``` <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <translate android:fromYDelta="-50%p" android:toYDelta="0%p" android:duration="2000" /> </set> ``` And to use this animation ``` Animation bottomUp = AnimationUtils.loadAnimation(this, R.anim.animation); tv_logo.startAnimation(bottomUp); ```
40,803,051
When i was run patch install command by CLI i see this below error. Please suggest me where i am wrong. I have install below version Patchs only here i am facing this problem. ``` sh PATCH_SUPEE-8788_CE_1.9.1.0_v2-2016-10-14-09-38-31.sh Checking if patch can be applied/reverted successfully... ERROR: Patch can't be applied/reverted successfully. patching file app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Gallery/Content.php patching file app/code/core/Mage/Adminhtml/Block/Cms/Wysiwyg/Images/Content/Uploader.php patching file app/code/core/Mage/Adminhtml/Block/Media/Uploader.php patching file app/code/core/Mage/Adminhtml/Block/Urlrewrite/Category/Tree.php patching file app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Serialized.php patching file app/code/core/Mage/Adminhtml/controllers/DashboardController.php patching file app/code/core/Mage/Adminhtml/controllers/IndexController.php patching file app/code/core/Mage/Adminhtml/controllers/Media/UploaderController.php patching file app/code/core/Mage/Catalog/Helper/Image.php patching file app/code/core/Mage/Catalog/etc/config.xml patching file app/code/core/Mage/Catalog/etc/system.xml patching file app/code/core/Mage/Centinel/Model/Api.php patching file app/code/core/Mage/Centinel/Model/Api/Client.php patching file app/code/core/Mage/Core/Block/Abstract.php patching file app/code/core/Mage/Core/Helper/Url.php patching file app/code/core/Mage/Core/Model/Encryption.php patching file app/code/core/Mage/Core/Model/Input/Filter/MaliciousCode.php patching file app/code/core/Mage/Core/functions.php patching file app/code/core/Mage/Customer/Block/Address/Book.php patching file app/code/core/Mage/Customer/controllers/AddressController.php patching file app/code/core/Mage/Dataflow/Model/Profile.php patching file app/code/core/Mage/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Links.php patching file app/code/core/Mage/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Samples.php patching file app/code/core/Mage/Downloadable/Helper/File.php patching file app/code/core/Mage/Oauth/Model/Server.php patching file app/code/core/Mage/Paygate/Model/Authorizenet.php patching file app/code/core/Mage/Payment/Block/Info/Checkmo.php patching file app/code/core/Mage/Paypal/Model/Express/Checkout.php patching file app/code/core/Mage/Paypal/Model/Resource/Payment/Transaction.php patching file app/code/core/Mage/Sales/Model/Resource/Order/Payment.php patching file app/code/core/Mage/Sales/Model/Resource/Order/Payment/Transaction.php patching file app/code/core/Mage/Sales/Model/Resource/Quote/Payment.php patching file app/code/core/Mage/Sales/Model/Resource/Recurring/Profile.php patching file app/code/core/Mage/Uploader/Block/Abstract.php patching file app/code/core/Mage/Uploader/Block/Multiple.php patching file app/code/core/Mage/Uploader/Block/Single.php patching file app/code/core/Mage/Uploader/Helper/Data.php patching file app/code/core/Mage/Uploader/Helper/File.php patching file app/code/core/Mage/Uploader/Model/Config/Abstract.php patching file app/code/core/Mage/Uploader/Model/Config/Browsebutton.php patching file app/code/core/Mage/Uploader/Model/Config/Misc.php patching file app/code/core/Mage/Uploader/Model/Config/Uploader.php patching file app/code/core/Mage/Uploader/etc/config.xml patching file app/code/core/Mage/Uploader/etc/jstranslator.xml patching file app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl.php patching file app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl/International.php patching file app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex.php patching file app/code/core/Mage/Usa/Model/Shipping/Carrier/Ups.php patching file app/code/core/Mage/Usa/etc/config.xml patching file app/code/core/Mage/Usa/etc/system.xml patching file app/code/core/Mage/Wishlist/Helper/Data.php patching file app/code/core/Mage/Wishlist/controllers/IndexController.php patching file app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design.php patching file app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Images.php patching file app/code/core/Mage/XmlConnect/controllers/Adminhtml/MobileController.php patching file app/design/adminhtml/default/default/layout/cms.xml patching file app/design/adminhtml/default/default/layout/main.xml patching file app/design/adminhtml/default/default/layout/xmlconnect.xml patching file app/design/adminhtml/default/default/template/catalog/product/helper/gallery.phtml patching file app/design/adminhtml/default/default/template/cms/browser/content/uploader.phtml patching file app/design/adminhtml/default/default/template/downloadable/product/edit/downloadable.phtml patching file app/design/adminhtml/default/default/template/downloadable/product/edit/downloadable/links.phtml patching file app/design/adminhtml/default/default/template/downloadable/product/edit/downloadable/samples.phtml patching file app/design/adminhtml/default/default/template/media/uploader.phtml patching file app/design/adminhtml/default/default/template/xmlconnect/edit/tab/design.phtml patching file app/etc/modules/Mage_All.xml patching file app/locale/en_US/Mage_Media.csv patching file app/locale/en_US/Mage_Uploader.csv patching file downloader/lib/Mage/HTTP/Client/Curl.php patching file js/lib/uploader/flow.min.js patching file js/lib/uploader/fusty-flow-factory.js patching file js/lib/uploader/fusty-flow.js patching file js/mage/adminhtml/product.js patching file js/mage/adminhtml/uploader/instance.js patching file lib/Unserialize/Parser.php patching file lib/Unserialize/Reader/Arr.php patching file lib/Unserialize/Reader/ArrValue.php patching file lib/Unserialize/Reader/Null.php patching file skin/adminhtml/default/default/boxes.css patching file skin/adminhtml/default/default/media/flex.swf Reversed (or previously applied) patch detected! Assume -R? [n] Apply anyway? [n] Skipping patch. 1 out of 1 hunk ignored -- saving rejects to file skin/adminhtml/default/default/media/flex.swf.rej patching file skin/adminhtml/default/default/media/uploader.swf Reversed (or previously applied) patch detected! Assume -R? [n] Apply anyway? [n] Skipping patch. 1 out of 1 hunk ignored -- saving rejects to file skin/adminhtml/default/default/media/uploader.swf.rej patching file skin/adminhtml/default/default/media/uploaderSingle.swf Reversed (or previously applied) patch detected! Assume -R? [n] Apply anyway? [n] Skipping patch. 1 out of 1 hunk ignored -- saving rejects to file skin/adminhtml/default/default/media/uploaderSingle.swf.rej patching file skin/adminhtml/default/default/xmlconnect/boxes.css ```
2016/11/25
[ "https://Stackoverflow.com/questions/40803051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2185477/" ]
These error you can see when you run the command. It means the file is conflicted with patches. You can replace with your version and again run your command. or Simply you can go through- <https://magentary.com/kb/install-supee-8788-without-ssh/> download file and implement to your magento in mage report 8788 not detected you need to delete. ``` /skin/adminhtml/default/default/media/flex.swf /skin/adminhtml/default/default/media/uploader.swf /skin/adminhtml/default/default/media/uploaderSingle.swf ``` Note: Please take backup of your website before do this.
**First read carefully after that apply following steps.** I got the solution if you have changed in core files then this error will come. here have very easy solution download any upgrated version of magento and replace your current core files with upgrated files, after that excute the frontend URL it will automatically update magento with availble patches. Note: you can note degrate you upgrated version so that please take a backup of files and database so that your data will save.
7,588
hi, i was asked to do sound design / processing for a live performance-art act. specifically, i need to be able to pick up live sounds from several locations across the stage, mix and process them simultaneously. one challenging scenario is this: the performer/dancer will be crawling on the surface of some sort of round metal container (about 4 meter diameter) full of gravel (about 1 meter deep). what i want to do is install a few microphones inside the gravel pool (say place them 20-30cm deep), in order to pick up and amplify the friction sound produced by the gravel as the performer will crawl on its surface. additionally, i'd like to be able to pick up and amplify the performer's breathings as he crawls. question 1: what would be the best type of microphones to use in order to pick up the gravel sound? question 2: what would be the best way to pick up the performer's breathings? - the solution must not involve attaching a mike to the performer's body. thanks, K.
2011/04/28
[ "https://sound.stackexchange.com/questions/7588", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/596/" ]
The only thing I'd put in a gravel pit is an SM-57 or 58. Those things are crazy durable. anything less robust will be seriously damaged. Sound quality is kind of crap though. My next thought is that you could rent 4 wireless mic kits and set them around the edge of the pool (or just two on opposite sides from each other). I'm assuming that the performer will have a particular way of doing the gravel sequence since it's part of a larger routine. In that case you can get down to one if they're really consistent in rehearsal.
for gravels, i would opt for contact mics / piezo strips. for breathings.. well, if you can't attach anything to the performer's body, you can only try with a shotgun mic placed on top of it (if he will stay in the same place for the whole performance).
7,588
hi, i was asked to do sound design / processing for a live performance-art act. specifically, i need to be able to pick up live sounds from several locations across the stage, mix and process them simultaneously. one challenging scenario is this: the performer/dancer will be crawling on the surface of some sort of round metal container (about 4 meter diameter) full of gravel (about 1 meter deep). what i want to do is install a few microphones inside the gravel pool (say place them 20-30cm deep), in order to pick up and amplify the friction sound produced by the gravel as the performer will crawl on its surface. additionally, i'd like to be able to pick up and amplify the performer's breathings as he crawls. question 1: what would be the best type of microphones to use in order to pick up the gravel sound? question 2: what would be the best way to pick up the performer's breathings? - the solution must not involve attaching a mike to the performer's body. thanks, K.
2011/04/28
[ "https://sound.stackexchange.com/questions/7588", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/596/" ]
for gravels, i would opt for contact mics / piezo strips. for breathings.. well, if you can't attach anything to the performer's body, you can only try with a shotgun mic placed on top of it (if he will stay in the same place for the whole performance).
It might be worth discussing a wireless with the performer otherwise you are going to have cables everywhere. If they are really anti-wireless then you could rent a parabolic dish and connect it to a wireless transmitter and follow the artist round with that. When I have had to do unusual events like this I mic everything with Audio Technica cardioid lavalier mics in AT8418 Unimounts and have attached them successfully to all sorts of objects. The unimount has a built in pop screen which also acts partially as a suspension mount, as the foam completely encases the mic isolating it from the support.
7,588
hi, i was asked to do sound design / processing for a live performance-art act. specifically, i need to be able to pick up live sounds from several locations across the stage, mix and process them simultaneously. one challenging scenario is this: the performer/dancer will be crawling on the surface of some sort of round metal container (about 4 meter diameter) full of gravel (about 1 meter deep). what i want to do is install a few microphones inside the gravel pool (say place them 20-30cm deep), in order to pick up and amplify the friction sound produced by the gravel as the performer will crawl on its surface. additionally, i'd like to be able to pick up and amplify the performer's breathings as he crawls. question 1: what would be the best type of microphones to use in order to pick up the gravel sound? question 2: what would be the best way to pick up the performer's breathings? - the solution must not involve attaching a mike to the performer's body. thanks, K.
2011/04/28
[ "https://sound.stackexchange.com/questions/7588", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/596/" ]
The only thing I'd put in a gravel pit is an SM-57 or 58. Those things are crazy durable. anything less robust will be seriously damaged. Sound quality is kind of crap though. My next thought is that you could rent 4 wireless mic kits and set them around the edge of the pool (or just two on opposite sides from each other). I'm assuming that the performer will have a particular way of doing the gravel sequence since it's part of a larger routine. In that case you can get down to one if they're really consistent in rehearsal.
It might be worth discussing a wireless with the performer otherwise you are going to have cables everywhere. If they are really anti-wireless then you could rent a parabolic dish and connect it to a wireless transmitter and follow the artist round with that. When I have had to do unusual events like this I mic everything with Audio Technica cardioid lavalier mics in AT8418 Unimounts and have attached them successfully to all sorts of objects. The unimount has a built in pop screen which also acts partially as a suspension mount, as the foam completely encases the mic isolating it from the support.
224,503
I bought a cheap Blackview BV5900 running on Android 9.0 (I assume a custom ROM) as I needed something rugged and with long battery life for testing purposes. I'm struggling to find any answers as to why apps won't auto start when they are supposed to. The app in question primarily is Grandstream Wave - Video which is effectively a SIP client. It auto starts just fine on an old Samsung Galaxy V6. I've tried various auto-start apps to see if I could get around it, but it would seem they fail to load as well on boot, so they don't do the task they are intended to perform. I've been in contact with the manufacturer and their answer is it just won't do it. As it's a test phone I'm quite happy to root it, although I'm completely new to Android, I'm sure I'll find enough info to get started with a bit of googling. What I'm after is a bit of help on what to look for and how to find it. From what I gather, the app is looking for a `BOOT_COMPLETE` message of some sort, so I'm guessing that is disabled somewhere? Any answers, please assume I know nothing, you will be correct. **EDIT 11May2020** Tried the shell command as requested [here](https://android.stackexchange.com/a/224547/322004) - no Joy. Result from shell below. Not sure whether this just means I don't have enough privilege to run it or it's disabled in some way? ``` Broadcasting: Intent { act=android.intent.action.BOOT_COMPLETED flg=0x400000 pkg=com.grandstream.wave } Security exception: Permission Denial: not allowed to send broadcast android.intent.action.BOOT_COMPLETED from pid=5834, uid=2000 java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.BOOT_COMPLETED from pid=5834, uid=2000 at com.android.server.am.ActivityManagerService.broadcastIntentLocked(ActivityManagerService.java:21774) at com.android.server.am.ActivityManagerService.broadcastIntent(ActivityManagerService.java:22411) at com.android.server.am.ActivityManagerShellCommand.runSendBroadcast(ActivityManagerShellCommand.java:690) at com.android.server.am.ActivityManagerShellCommand.onCommand(ActivityManagerShellCommand.java:174) at android.os.ShellCommand.exec(ShellCommand.java:103) at com.android.server.am.ActivityManagerService.onShellCommand(ActivityManagerService.java:16434) at android.os.Binder.shellCommand(Binder.java:634) at android.os.Binder.onTransact(Binder.java:532) at android.app.IActivityManager$Stub.onTransact(IActivityManager.java:3551) at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:3397) at android.os.Binder.execTransact(Binder.java:731) ```
2020/04/29
[ "https://android.stackexchange.com/questions/224503", "https://android.stackexchange.com", "https://android.stackexchange.com/users/321904/" ]
I solved it by swiping down the lock icon on my android 10 device. Hope this helps
Not sure if you're still having this issue, but recently suffered the same (different app) and managed to resolve it completely by accident: Go to the recent apps menu (as shown in image) and simple do a (quick) swipe to the right on the app you want to lock/unlock, starting point doesn't seem to matter much but make sure to swipe all the way to (or over) the edge. If you do it too slow or not far enough it doesn't work. I haven't been able to find this in any official documentation or if/where it can be configured/disabled, it's not listed in the System->Gestures menu. It also seems to be fairly tenacious since 'locking' an app persists after a reboot or force stop via developer menu's 'running services'. It seems to be something similar to Windows' 'Pin to Taskbar' or Apple's 'Keep in Dock'. Phone: Alcatel 1S (2019) running Android 9 (build 01001)
233,673
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: ``` flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) ``` Note that this example mindfully avoids `lambda`. It prints "4 4 4", which is surprising. I'd expect "0 2 4". This equivalent Perl code does it right: ``` my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f->(2), "\n"; } ``` "0 2 4" is printed. Can you please explain the difference ? --- Update: The problem **is not** with `i` being global. This displays the same behavior: ``` flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) ``` As the commented line shows, `i` is unknown at that point. Still, it prints "4 4 4".
2008/10/24
[ "https://Stackoverflow.com/questions/233673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
What is happening is that the variable i is captured, and the functions are returning the value it is bound to at the time it is called. In functional languages this kind of situation never arises, as i wouldn't be rebound. However with python, and also as you've seen with lisp, this is no longer true. The difference with your scheme example is to do with the semantics of the do loop. Scheme is effectively creating a new i variable each time through the loop, rather than reusing an existing i binding as with the other languages. If you use a different variable created external to the loop and mutate it, you'll see the same behaviour in scheme. Try replacing your loop with: ``` (let ((ii 1)) ( (do ((i 1 (+ 1 i))) ((>= i 4)) (set! flist (cons (lambda (x) (* ii x)) flist)) (set! ii i)) )) ``` Take a look [here](http://lambda-the-ultimate.org/node/2648) for some further discussion of this. [Edit] Possibly a better way to describe it is to think of the do loop as a macro which performs the following steps: 1. Define a lambda taking a single parameter (i), with a body defined by the body of the loop, 2. An immediate call of that lambda with appropriate values of i as its parameter. ie. the equivalent to the below python: ``` flist = [] def loop_body(i): # extract body of the for loop to function def func(x): return x*i flist.append(func) map(loop_body, xrange(3)) # for i in xrange(3): body ``` The i is no longer the one from the parent scope but a brand new variable in its own scope (ie. the parameter to the lambda) and so you get the behaviour you observe. Python doesn't have this implicit new scope, so the body of the for loop just shares the i variable.
I'm still not entirely convinced why in some languages this works one way, and in some another way. In Common Lisp it's like Python: ``` (defvar *flist* '()) (dotimes (i 3 t) (setf *flist* (cons (lambda (x) (* x i)) *flist*))) (dolist (f *flist*) (format t "~a~%" (funcall f 2))) ``` Prints "6 6 6" (note that here the list is from 1 to 3, and built in reverse"). While in Scheme it works like in Perl: ``` (define flist '()) (do ((i 1 (+ 1 i))) ((>= i 4)) (set! flist (cons (lambda (x) (* i x)) flist))) (map (lambda (f) (printf "~a~%" (f 2))) flist) ``` Prints "6 4 2" And as I've mentioned already, Javascript is in the Python/CL camp. It appears there is an implementation decision here, which different languages approach in distinct ways. I would love to understand what is the decision, exactly.
233,673
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: ``` flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) ``` Note that this example mindfully avoids `lambda`. It prints "4 4 4", which is surprising. I'd expect "0 2 4". This equivalent Perl code does it right: ``` my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f->(2), "\n"; } ``` "0 2 4" is printed. Can you please explain the difference ? --- Update: The problem **is not** with `i` being global. This displays the same behavior: ``` flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) ``` As the commented line shows, `i` is unknown at that point. Still, it prints "4 4 4".
2008/10/24
[ "https://Stackoverflow.com/questions/233673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
What is happening is that the variable i is captured, and the functions are returning the value it is bound to at the time it is called. In functional languages this kind of situation never arises, as i wouldn't be rebound. However with python, and also as you've seen with lisp, this is no longer true. The difference with your scheme example is to do with the semantics of the do loop. Scheme is effectively creating a new i variable each time through the loop, rather than reusing an existing i binding as with the other languages. If you use a different variable created external to the loop and mutate it, you'll see the same behaviour in scheme. Try replacing your loop with: ``` (let ((ii 1)) ( (do ((i 1 (+ 1 i))) ((>= i 4)) (set! flist (cons (lambda (x) (* ii x)) flist)) (set! ii i)) )) ``` Take a look [here](http://lambda-the-ultimate.org/node/2648) for some further discussion of this. [Edit] Possibly a better way to describe it is to think of the do loop as a macro which performs the following steps: 1. Define a lambda taking a single parameter (i), with a body defined by the body of the loop, 2. An immediate call of that lambda with appropriate values of i as its parameter. ie. the equivalent to the below python: ``` flist = [] def loop_body(i): # extract body of the for loop to function def func(x): return x*i flist.append(func) map(loop_body, xrange(3)) # for i in xrange(3): body ``` The i is no longer the one from the parent scope but a brand new variable in its own scope (ie. the parameter to the lambda) and so you get the behaviour you observe. Python doesn't have this implicit new scope, so the body of the for loop just shares the i variable.
I didn't like how solutions above created `wrappers` in the loop. Note: python 3.xx ``` flist = [] def func(i): return lambda x: x * i for i in range(3): flist.append(func(i)) for f in flist: print f(2) ```
233,673
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: ``` flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) ``` Note that this example mindfully avoids `lambda`. It prints "4 4 4", which is surprising. I'd expect "0 2 4". This equivalent Perl code does it right: ``` my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f->(2), "\n"; } ``` "0 2 4" is printed. Can you please explain the difference ? --- Update: The problem **is not** with `i` being global. This displays the same behavior: ``` flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) ``` As the commented line shows, `i` is unknown at that point. Still, it prints "4 4 4".
2008/10/24
[ "https://Stackoverflow.com/questions/233673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
The functions defined in the loop keep accessing the same variable `i` while its value changes. At the end of the loop, all the functions point to the same variable, which is holding the last value in the loop: the effect is what reported in the example. In order to evaluate `i` and use its value, a common pattern is to set it as a parameter default: parameter defaults are evaluated when the `def` statement is executed, and thus the value of the loop variable is frozen. The following works as expected: ``` flist = [] for i in xrange(3): def func(x, i=i): # the *value* of i is copied in func() environment return x * i flist.append(func) for f in flist: print f(2) ```
I didn't like how solutions above created `wrappers` in the loop. Note: python 3.xx ``` flist = [] def func(i): return lambda x: x * i for i in range(3): flist.append(func(i)) for f in flist: print f(2) ```
233,673
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: ``` flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) ``` Note that this example mindfully avoids `lambda`. It prints "4 4 4", which is surprising. I'd expect "0 2 4". This equivalent Perl code does it right: ``` my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f->(2), "\n"; } ``` "0 2 4" is printed. Can you please explain the difference ? --- Update: The problem **is not** with `i` being global. This displays the same behavior: ``` flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) ``` As the commented line shows, `i` is unknown at that point. Still, it prints "4 4 4".
2008/10/24
[ "https://Stackoverflow.com/questions/233673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
Python is actually behaving as defined. **Three separate functions** are created, but they each have the **closure of the environment they're defined in** - in this case, the global environment (or the outer function's environment if the loop is placed inside another function). This is exactly the problem, though - in this environment, **i is modified**, and the closures all **refer to the same i**. Here is the best solution I can come up with - create a function creater and invoke *that* instead. This will force **different environments** for each of the functions created, with a **different i** in each one. ``` flist = [] for i in xrange(3): def funcC(j): def func(x): return x * j return func flist.append(funcC(i)) for f in flist: print f(2) ``` This is what happens when you mix side effects and functional programming.
look at this: ``` for f in flist: print f.func_closure (<cell at 0x00C980B0: int object at 0x009864B4>,) (<cell at 0x00C980B0: int object at 0x009864B4>,) (<cell at 0x00C980B0: int object at 0x009864B4>,) ``` It means they all point to the same i variable instance, which will have a value of 2 once the loop is over. A readable solution: ``` for i in xrange(3): def ffunc(i): def func(x): return x * i return func flist.append(ffunc(i)) ```
233,673
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: ``` flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) ``` Note that this example mindfully avoids `lambda`. It prints "4 4 4", which is surprising. I'd expect "0 2 4". This equivalent Perl code does it right: ``` my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f->(2), "\n"; } ``` "0 2 4" is printed. Can you please explain the difference ? --- Update: The problem **is not** with `i` being global. This displays the same behavior: ``` flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) ``` As the commented line shows, `i` is unknown at that point. Still, it prints "4 4 4".
2008/10/24
[ "https://Stackoverflow.com/questions/233673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
What is happening is that the variable i is captured, and the functions are returning the value it is bound to at the time it is called. In functional languages this kind of situation never arises, as i wouldn't be rebound. However with python, and also as you've seen with lisp, this is no longer true. The difference with your scheme example is to do with the semantics of the do loop. Scheme is effectively creating a new i variable each time through the loop, rather than reusing an existing i binding as with the other languages. If you use a different variable created external to the loop and mutate it, you'll see the same behaviour in scheme. Try replacing your loop with: ``` (let ((ii 1)) ( (do ((i 1 (+ 1 i))) ((>= i 4)) (set! flist (cons (lambda (x) (* ii x)) flist)) (set! ii i)) )) ``` Take a look [here](http://lambda-the-ultimate.org/node/2648) for some further discussion of this. [Edit] Possibly a better way to describe it is to think of the do loop as a macro which performs the following steps: 1. Define a lambda taking a single parameter (i), with a body defined by the body of the loop, 2. An immediate call of that lambda with appropriate values of i as its parameter. ie. the equivalent to the below python: ``` flist = [] def loop_body(i): # extract body of the for loop to function def func(x): return x*i flist.append(func) map(loop_body, xrange(3)) # for i in xrange(3): body ``` The i is no longer the one from the parent scope but a brand new variable in its own scope (ie. the parameter to the lambda) and so you get the behaviour you observe. Python doesn't have this implicit new scope, so the body of the for loop just shares the i variable.
The reasoning behind the behavior has already been explained, and multiple solutions have been posted, but I think this is the most pythonic (remember, everything in Python is an object!): ``` flist = [] for i in xrange(3): def func(x): return x * func.i func.i=i flist.append(func) for f in flist: print f(2) ``` Claudiu's answer is pretty good, using a function generator, but piro's answer is a hack, to be honest, as it's making i into a "hidden" argument with a default value (it'll work fine, but it's not "pythonic").
233,673
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: ``` flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) ``` Note that this example mindfully avoids `lambda`. It prints "4 4 4", which is surprising. I'd expect "0 2 4". This equivalent Perl code does it right: ``` my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f->(2), "\n"; } ``` "0 2 4" is printed. Can you please explain the difference ? --- Update: The problem **is not** with `i` being global. This displays the same behavior: ``` flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) ``` As the commented line shows, `i` is unknown at that point. Still, it prints "4 4 4".
2008/10/24
[ "https://Stackoverflow.com/questions/233673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
The problem is that all of the local functions bind to the same environment and thus to the same `i` variable. The solution (workaround) is to create separate environments (stack frames) for each function (or lambda): ``` t = [ (lambda x: lambda y : x*y)(x) for x in range(5)] >>> t[1](2) 2 >>> t[2](2) 4 ```
I didn't like how solutions above created `wrappers` in the loop. Note: python 3.xx ``` flist = [] def func(i): return lambda x: x * i for i in range(3): flist.append(func(i)) for f in flist: print f(2) ```
233,673
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: ``` flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) ``` Note that this example mindfully avoids `lambda`. It prints "4 4 4", which is surprising. I'd expect "0 2 4". This equivalent Perl code does it right: ``` my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f->(2), "\n"; } ``` "0 2 4" is printed. Can you please explain the difference ? --- Update: The problem **is not** with `i` being global. This displays the same behavior: ``` flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) ``` As the commented line shows, `i` is unknown at that point. Still, it prints "4 4 4".
2008/10/24
[ "https://Stackoverflow.com/questions/233673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
Python is actually behaving as defined. **Three separate functions** are created, but they each have the **closure of the environment they're defined in** - in this case, the global environment (or the outer function's environment if the loop is placed inside another function). This is exactly the problem, though - in this environment, **i is modified**, and the closures all **refer to the same i**. Here is the best solution I can come up with - create a function creater and invoke *that* instead. This will force **different environments** for each of the functions created, with a **different i** in each one. ``` flist = [] for i in xrange(3): def funcC(j): def func(x): return x * j return func flist.append(funcC(i)) for f in flist: print f(2) ``` This is what happens when you mix side effects and functional programming.
What is happening is that the variable i is captured, and the functions are returning the value it is bound to at the time it is called. In functional languages this kind of situation never arises, as i wouldn't be rebound. However with python, and also as you've seen with lisp, this is no longer true. The difference with your scheme example is to do with the semantics of the do loop. Scheme is effectively creating a new i variable each time through the loop, rather than reusing an existing i binding as with the other languages. If you use a different variable created external to the loop and mutate it, you'll see the same behaviour in scheme. Try replacing your loop with: ``` (let ((ii 1)) ( (do ((i 1 (+ 1 i))) ((>= i 4)) (set! flist (cons (lambda (x) (* ii x)) flist)) (set! ii i)) )) ``` Take a look [here](http://lambda-the-ultimate.org/node/2648) for some further discussion of this. [Edit] Possibly a better way to describe it is to think of the do loop as a macro which performs the following steps: 1. Define a lambda taking a single parameter (i), with a body defined by the body of the loop, 2. An immediate call of that lambda with appropriate values of i as its parameter. ie. the equivalent to the below python: ``` flist = [] def loop_body(i): # extract body of the for loop to function def func(x): return x*i flist.append(func) map(loop_body, xrange(3)) # for i in xrange(3): body ``` The i is no longer the one from the parent scope but a brand new variable in its own scope (ie. the parameter to the lambda) and so you get the behaviour you observe. Python doesn't have this implicit new scope, so the body of the for loop just shares the i variable.
233,673
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: ``` flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) ``` Note that this example mindfully avoids `lambda`. It prints "4 4 4", which is surprising. I'd expect "0 2 4". This equivalent Perl code does it right: ``` my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f->(2), "\n"; } ``` "0 2 4" is printed. Can you please explain the difference ? --- Update: The problem **is not** with `i` being global. This displays the same behavior: ``` flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) ``` As the commented line shows, `i` is unknown at that point. Still, it prints "4 4 4".
2008/10/24
[ "https://Stackoverflow.com/questions/233673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
Python is actually behaving as defined. **Three separate functions** are created, but they each have the **closure of the environment they're defined in** - in this case, the global environment (or the outer function's environment if the loop is placed inside another function). This is exactly the problem, though - in this environment, **i is modified**, and the closures all **refer to the same i**. Here is the best solution I can come up with - create a function creater and invoke *that* instead. This will force **different environments** for each of the functions created, with a **different i** in each one. ``` flist = [] for i in xrange(3): def funcC(j): def func(x): return x * j return func flist.append(funcC(i)) for f in flist: print f(2) ``` This is what happens when you mix side effects and functional programming.
The variable `i` is a global, whose value is 2 at each time the function `f` is called. I would be inclined to implement the behavior you're after as follows: ``` >>> class f: ... def __init__(self, multiplier): self.multiplier = multiplier ... def __call__(self, multiplicand): return self.multiplier*multiplicand ... >>> flist = [f(i) for i in range(3)] >>> [g(2) for g in flist] [0, 2, 4] ``` **Response to your update**: It's not the globalness of `i` *per se* which is causing this behavior, it's the fact that it's a variable from an enclosing scope which has a fixed value over the times when f is called. In your second example, the value of `i` is taken from the scope of the `kkk` function, and nothing is changing that when you call the functions on `flist`.
233,673
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: ``` flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) ``` Note that this example mindfully avoids `lambda`. It prints "4 4 4", which is surprising. I'd expect "0 2 4". This equivalent Perl code does it right: ``` my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f->(2), "\n"; } ``` "0 2 4" is printed. Can you please explain the difference ? --- Update: The problem **is not** with `i` being global. This displays the same behavior: ``` flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) ``` As the commented line shows, `i` is unknown at that point. Still, it prints "4 4 4".
2008/10/24
[ "https://Stackoverflow.com/questions/233673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
Here's how you do it using the `functools` library (which I'm not sure was available at the time the question was posed). ``` from functools import partial flist = [] def func(i, x): return x * i for i in range(3): flist.append(partial(func, i)) for f in flist: print(f(2)) ``` Outputs 0 2 4, as expected.
What is happening is that the variable i is captured, and the functions are returning the value it is bound to at the time it is called. In functional languages this kind of situation never arises, as i wouldn't be rebound. However with python, and also as you've seen with lisp, this is no longer true. The difference with your scheme example is to do with the semantics of the do loop. Scheme is effectively creating a new i variable each time through the loop, rather than reusing an existing i binding as with the other languages. If you use a different variable created external to the loop and mutate it, you'll see the same behaviour in scheme. Try replacing your loop with: ``` (let ((ii 1)) ( (do ((i 1 (+ 1 i))) ((>= i 4)) (set! flist (cons (lambda (x) (* ii x)) flist)) (set! ii i)) )) ``` Take a look [here](http://lambda-the-ultimate.org/node/2648) for some further discussion of this. [Edit] Possibly a better way to describe it is to think of the do loop as a macro which performs the following steps: 1. Define a lambda taking a single parameter (i), with a body defined by the body of the loop, 2. An immediate call of that lambda with appropriate values of i as its parameter. ie. the equivalent to the below python: ``` flist = [] def loop_body(i): # extract body of the for loop to function def func(x): return x*i flist.append(func) map(loop_body, xrange(3)) # for i in xrange(3): body ``` The i is no longer the one from the parent scope but a brand new variable in its own scope (ie. the parameter to the lambda) and so you get the behaviour you observe. Python doesn't have this implicit new scope, so the body of the for loop just shares the i variable.
233,673
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: ``` flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) ``` Note that this example mindfully avoids `lambda`. It prints "4 4 4", which is surprising. I'd expect "0 2 4". This equivalent Perl code does it right: ``` my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f->(2), "\n"; } ``` "0 2 4" is printed. Can you please explain the difference ? --- Update: The problem **is not** with `i` being global. This displays the same behavior: ``` flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) ``` As the commented line shows, `i` is unknown at that point. Still, it prints "4 4 4".
2008/10/24
[ "https://Stackoverflow.com/questions/233673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
look at this: ``` for f in flist: print f.func_closure (<cell at 0x00C980B0: int object at 0x009864B4>,) (<cell at 0x00C980B0: int object at 0x009864B4>,) (<cell at 0x00C980B0: int object at 0x009864B4>,) ``` It means they all point to the same i variable instance, which will have a value of 2 once the loop is over. A readable solution: ``` for i in xrange(3): def ffunc(i): def func(x): return x * i return func flist.append(ffunc(i)) ```
I didn't like how solutions above created `wrappers` in the loop. Note: python 3.xx ``` flist = [] def func(i): return lambda x: x * i for i in range(3): flist.append(func(i)) for f in flist: print f(2) ```
19,916,907
I need to handle a **large** list of objects (in that case, sprites in a game) **in a particular order**, determined by one of their property (in that case, the `zIndex` of the sprite). I acquire the objects one-by-one, in a random order, but not so far from the perfect one. At the moment, I push naively each object I acquire in an array, and I sort it before the operation (with the [`orderBy`](http://docs.angularjs.org/api/ng.filter%3aorderBy) filter of AngularJS). But the operation is really slow (50% of the total calculation time). What can I do to speed up the process? I've try to use a sparse array, whose keys are the `zIndex` of my objects, but for a mysterious reason: * [`angular.forEach`](http://docs.angularjs.org/api/angular.forEach) is really slow on the sparse array, * the order doesn't seem to be preserved when I iterate over the array with a `for ... in` loop.
2013/11/11
[ "https://Stackoverflow.com/questions/19916907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2057033/" ]
What about using `array.sort()`. The closer you get to the native browser JavaScript the quicker you're going to get. See <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort>
I wouldn't use a `for ... in` loop. From Mozilla: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in> `Iterates over the enumerable properties of an object, in arbitrary order.` `for ... in` will usually iterate over an array in the order that the array properties were defined, which is why sorting doesn't work. Not sure if it will solve your problem, but doing a `var i = 0, l = items.length; for (; i < l; i++) { // do stuff }` will preserve array order, and most likely be the fastest way as it uses native javascript. If this is the only issue that you're facing, and using a sparse array works with this, then it should be fine.
2,370,273
I have a binary tree class that is created with a root node and nodes can be added to it as needed in the code, however I am having trouble in deleting the nodes because I point to them with TNodePtr and it is an incompatible type with TNode. At the moment I have this recursive method of deleting nodes which should work once the incompatible types is sorted. Thanks. ``` Destructor TTree.Destroy; procedure FreeSubnodes(Node: TNodePtr); begin if Assigned(Node.Left) then FreeSubnodes(Node.Left); if Assigned(Node.Right) then FreeSubnodes(Node.Right); Delete(Node); end; begin FreeSubnodes(Root); inherited; end; ``` Edit 04/03/2010: The error given is this: [Warning] SystemBuild.pas(50): Method 'Destroy' hides virtual method of base type 'TObject' [Error] SystemBuild.pas(84): Incompatible types Line 84 is Delete(Node); I declared the node like this: ``` type TNodePtr = ^TNode; TNode = Record Data:String; Left:TNodePtr; Right:TNodePtr; end; ``` And the tree like this: ``` Type TTree = Class Private Root:TNodePtr; Public Function GetRoot:TNodePtr; Constructor Create; Destructor Destroy; end; ```
2010/03/03
[ "https://Stackoverflow.com/questions/2370273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193785/" ]
``` Destructor TTree.Destroy; procedure FreeSubnodes(Node: TNodePtr); var ThisNode:TNode; begin ThisNode := Node^; if Assigned(ThisNode.Left) then FreeSubnodes(ThisNode.Left); if Assigned(ThisNode.Right) then FreeSubnodes(ThisNode.Right); Dispose(Node); end; begin FreeSubnodes(Root); inherited; end; ```
to dereference the pointer use Node^
2,370,273
I have a binary tree class that is created with a root node and nodes can be added to it as needed in the code, however I am having trouble in deleting the nodes because I point to them with TNodePtr and it is an incompatible type with TNode. At the moment I have this recursive method of deleting nodes which should work once the incompatible types is sorted. Thanks. ``` Destructor TTree.Destroy; procedure FreeSubnodes(Node: TNodePtr); begin if Assigned(Node.Left) then FreeSubnodes(Node.Left); if Assigned(Node.Right) then FreeSubnodes(Node.Right); Delete(Node); end; begin FreeSubnodes(Root); inherited; end; ``` Edit 04/03/2010: The error given is this: [Warning] SystemBuild.pas(50): Method 'Destroy' hides virtual method of base type 'TObject' [Error] SystemBuild.pas(84): Incompatible types Line 84 is Delete(Node); I declared the node like this: ``` type TNodePtr = ^TNode; TNode = Record Data:String; Left:TNodePtr; Right:TNodePtr; end; ``` And the tree like this: ``` Type TTree = Class Private Root:TNodePtr; Public Function GetRoot:TNodePtr; Constructor Create; Destructor Destroy; end; ```
2010/03/03
[ "https://Stackoverflow.com/questions/2370273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193785/" ]
The error you see is because of a mistake I made in the answer I gave to [your previous question](https://stackoverflow.com/questions/2306696/creating-a-binary-tree-for-a-knockout-tournament). [I wrote `Delete`](https://stackoverflow.com/posts/2309918/revisions) when I should have written `Dispose`. I apologize. Here, then, is the correct destructor implementation: ``` destructor TTree.Destroy; procedure FreeSubnodes(Node: PNode); begin if Assigned(Node.Left) then FreeSubnodes(Node.Left); if Assigned(Node.Right) then FreeSubnodes(Node.Right); Dispose(Node); end; begin FreeSubnodes(Root); inherited; end; ``` The error is not saying that `TNodePtr` is incompatible with `TNode`. The error just says "incompatible types" because the compiler doesn't know what type `Delete` is supposed to receive. It's a compiler-magic function that accepts several different parameter types, none of which is compatible with `TNodePtr`. The first compiler message you see is about your `Destroy` method hiding the method from the base class. It's not responsible for the problem you were seeing, but you'd eventually notice a problem because your destructor would never get called. When you call `Free`, it will call *TObject's* `Destroy` method, not your new version. To make yours get called instead, you need to mark yours as *overriding* the inherited version. Then, when `TObject.Free` calls `Destroy`, control will go to your version first, and then go to the base class's version when you call `inherited`. Change the declaration to this: ``` destructor Destroy; override; ```
to dereference the pointer use Node^
2,370,273
I have a binary tree class that is created with a root node and nodes can be added to it as needed in the code, however I am having trouble in deleting the nodes because I point to them with TNodePtr and it is an incompatible type with TNode. At the moment I have this recursive method of deleting nodes which should work once the incompatible types is sorted. Thanks. ``` Destructor TTree.Destroy; procedure FreeSubnodes(Node: TNodePtr); begin if Assigned(Node.Left) then FreeSubnodes(Node.Left); if Assigned(Node.Right) then FreeSubnodes(Node.Right); Delete(Node); end; begin FreeSubnodes(Root); inherited; end; ``` Edit 04/03/2010: The error given is this: [Warning] SystemBuild.pas(50): Method 'Destroy' hides virtual method of base type 'TObject' [Error] SystemBuild.pas(84): Incompatible types Line 84 is Delete(Node); I declared the node like this: ``` type TNodePtr = ^TNode; TNode = Record Data:String; Left:TNodePtr; Right:TNodePtr; end; ``` And the tree like this: ``` Type TTree = Class Private Root:TNodePtr; Public Function GetRoot:TNodePtr; Constructor Create; Destructor Destroy; end; ```
2010/03/03
[ "https://Stackoverflow.com/questions/2370273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193785/" ]
The error you see is because of a mistake I made in the answer I gave to [your previous question](https://stackoverflow.com/questions/2306696/creating-a-binary-tree-for-a-knockout-tournament). [I wrote `Delete`](https://stackoverflow.com/posts/2309918/revisions) when I should have written `Dispose`. I apologize. Here, then, is the correct destructor implementation: ``` destructor TTree.Destroy; procedure FreeSubnodes(Node: PNode); begin if Assigned(Node.Left) then FreeSubnodes(Node.Left); if Assigned(Node.Right) then FreeSubnodes(Node.Right); Dispose(Node); end; begin FreeSubnodes(Root); inherited; end; ``` The error is not saying that `TNodePtr` is incompatible with `TNode`. The error just says "incompatible types" because the compiler doesn't know what type `Delete` is supposed to receive. It's a compiler-magic function that accepts several different parameter types, none of which is compatible with `TNodePtr`. The first compiler message you see is about your `Destroy` method hiding the method from the base class. It's not responsible for the problem you were seeing, but you'd eventually notice a problem because your destructor would never get called. When you call `Free`, it will call *TObject's* `Destroy` method, not your new version. To make yours get called instead, you need to mark yours as *overriding* the inherited version. Then, when `TObject.Free` calls `Destroy`, control will go to your version first, and then go to the base class's version when you call `inherited`. Change the declaration to this: ``` destructor Destroy; override; ```
``` Destructor TTree.Destroy; procedure FreeSubnodes(Node: TNodePtr); var ThisNode:TNode; begin ThisNode := Node^; if Assigned(ThisNode.Left) then FreeSubnodes(ThisNode.Left); if Assigned(ThisNode.Right) then FreeSubnodes(ThisNode.Right); Dispose(Node); end; begin FreeSubnodes(Root); inherited; end; ```
2,370,273
I have a binary tree class that is created with a root node and nodes can be added to it as needed in the code, however I am having trouble in deleting the nodes because I point to them with TNodePtr and it is an incompatible type with TNode. At the moment I have this recursive method of deleting nodes which should work once the incompatible types is sorted. Thanks. ``` Destructor TTree.Destroy; procedure FreeSubnodes(Node: TNodePtr); begin if Assigned(Node.Left) then FreeSubnodes(Node.Left); if Assigned(Node.Right) then FreeSubnodes(Node.Right); Delete(Node); end; begin FreeSubnodes(Root); inherited; end; ``` Edit 04/03/2010: The error given is this: [Warning] SystemBuild.pas(50): Method 'Destroy' hides virtual method of base type 'TObject' [Error] SystemBuild.pas(84): Incompatible types Line 84 is Delete(Node); I declared the node like this: ``` type TNodePtr = ^TNode; TNode = Record Data:String; Left:TNodePtr; Right:TNodePtr; end; ``` And the tree like this: ``` Type TTree = Class Private Root:TNodePtr; Public Function GetRoot:TNodePtr; Constructor Create; Destructor Destroy; end; ```
2010/03/03
[ "https://Stackoverflow.com/questions/2370273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193785/" ]
``` Destructor TTree.Destroy; procedure FreeSubnodes(Node: TNodePtr); var ThisNode:TNode; begin ThisNode := Node^; if Assigned(ThisNode.Left) then FreeSubnodes(ThisNode.Left); if Assigned(ThisNode.Right) then FreeSubnodes(ThisNode.Right); Dispose(Node); end; begin FreeSubnodes(Root); inherited; end; ```
use TComponent instead of Record. Record type(Pointer) is old and unsafe . TComponent is easier and more abstract. your issue similar to <https://stackoverflow.com/a/1032252/528588> .
2,370,273
I have a binary tree class that is created with a root node and nodes can be added to it as needed in the code, however I am having trouble in deleting the nodes because I point to them with TNodePtr and it is an incompatible type with TNode. At the moment I have this recursive method of deleting nodes which should work once the incompatible types is sorted. Thanks. ``` Destructor TTree.Destroy; procedure FreeSubnodes(Node: TNodePtr); begin if Assigned(Node.Left) then FreeSubnodes(Node.Left); if Assigned(Node.Right) then FreeSubnodes(Node.Right); Delete(Node); end; begin FreeSubnodes(Root); inherited; end; ``` Edit 04/03/2010: The error given is this: [Warning] SystemBuild.pas(50): Method 'Destroy' hides virtual method of base type 'TObject' [Error] SystemBuild.pas(84): Incompatible types Line 84 is Delete(Node); I declared the node like this: ``` type TNodePtr = ^TNode; TNode = Record Data:String; Left:TNodePtr; Right:TNodePtr; end; ``` And the tree like this: ``` Type TTree = Class Private Root:TNodePtr; Public Function GetRoot:TNodePtr; Constructor Create; Destructor Destroy; end; ```
2010/03/03
[ "https://Stackoverflow.com/questions/2370273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193785/" ]
The error you see is because of a mistake I made in the answer I gave to [your previous question](https://stackoverflow.com/questions/2306696/creating-a-binary-tree-for-a-knockout-tournament). [I wrote `Delete`](https://stackoverflow.com/posts/2309918/revisions) when I should have written `Dispose`. I apologize. Here, then, is the correct destructor implementation: ``` destructor TTree.Destroy; procedure FreeSubnodes(Node: PNode); begin if Assigned(Node.Left) then FreeSubnodes(Node.Left); if Assigned(Node.Right) then FreeSubnodes(Node.Right); Dispose(Node); end; begin FreeSubnodes(Root); inherited; end; ``` The error is not saying that `TNodePtr` is incompatible with `TNode`. The error just says "incompatible types" because the compiler doesn't know what type `Delete` is supposed to receive. It's a compiler-magic function that accepts several different parameter types, none of which is compatible with `TNodePtr`. The first compiler message you see is about your `Destroy` method hiding the method from the base class. It's not responsible for the problem you were seeing, but you'd eventually notice a problem because your destructor would never get called. When you call `Free`, it will call *TObject's* `Destroy` method, not your new version. To make yours get called instead, you need to mark yours as *overriding* the inherited version. Then, when `TObject.Free` calls `Destroy`, control will go to your version first, and then go to the base class's version when you call `inherited`. Change the declaration to this: ``` destructor Destroy; override; ```
use TComponent instead of Record. Record type(Pointer) is old and unsafe . TComponent is easier and more abstract. your issue similar to <https://stackoverflow.com/a/1032252/528588> .
44,557,759
Here is in Detail. I have a file which contains hidden BOM Characters as Shown Below 2225612|22225200240|STACKOVERFLOW|HELPSDEVELOPERS - LINE 1 **þÿ**2225612|22225200240|KIRK|CAPTAIN - LINE 2 2225612|22225200240|THANKS**þÿ**|INADVANCE - LINE 3 Now I have script where each row gets processed. As Per my assumption first line has to be processed since it doesn't have any BOM Character. But when second line starts processing it should raise an error since BOM Character is identified. Not only at the beginning of line the BOM Character can be anywhere in the row.For your reference the highlighted one is the BOM Character. When I use regex **/[^[:print]]/** using **gsub** it is considering space or new line as an BOM Character. I want only BOM characters to be detected. Can anyone writer script for this ? Thanks in advance guys
2017/06/15
[ "https://Stackoverflow.com/questions/44557759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6807825/" ]
I think this regex should work: ``` if line =~ /\xEF\xBB\xBF/ # If line contains BOM character fail "Line contains a BOM char!" end ``` If you have encoding issues, it might help to force both the line and regex to UTF-8, something like this: ``` regexp = Regexp.new("\xEF\xBB\xBF".force_encoding("UTF-8"), Regexp::FIXEDENCODING) if line.force_encoding("UTF-8") =~ regexp # ... ```
You can specify encoding with the File.read method. ``` File.read('your_file.txt', encoding: 'bom|utf-8') ``` or ``` File.readlines('your_file.txt', "r:utf-8") ```
12,912,770
How do I remove the white space that are in front and back of & <http://chemist.com:8080/eShop/search_results.jsp?IDNUMBER=BB55-7344> & Source=BuildingBlocks
2012/10/16
[ "https://Stackoverflow.com/questions/12912770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310156/" ]
``` String newUrl = oldUrl.replaceAll(" ", ""); ``` Hope this helps.
``` if(result.contains(" and "){ resultnew = result.replace(" and ","&amp").toString(); } ``` You don't really need the "if" check, although it is faster (unless result ***always*** contains " and ") as replace() will return the input string if " and " is not found. You also don't need the toString() since replace() returns a String.
12,912,770
How do I remove the white space that are in front and back of & <http://chemist.com:8080/eShop/search_results.jsp?IDNUMBER=BB55-7344> & Source=BuildingBlocks
2012/10/16
[ "https://Stackoverflow.com/questions/12912770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310156/" ]
Try : ``` urlString = urlString.replaceAll(" ", "%20"); ``` This code replaces all the white space.
``` String newUrl = oldUrl.replaceAll(" ", ""); ``` Hope this helps.
12,912,770
How do I remove the white space that are in front and back of & <http://chemist.com:8080/eShop/search_results.jsp?IDNUMBER=BB55-7344> & Source=BuildingBlocks
2012/10/16
[ "https://Stackoverflow.com/questions/12912770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310156/" ]
Try: ``` String newURI = oldURI.replaceAll("\\s+", ""); ```
``` if(result.contains(" and "){ resultnew = result.replace(" and ","&amp").toString(); } ``` You don't really need the "if" check, although it is faster (unless result ***always*** contains " and ") as replace() will return the input string if " and " is not found. You also don't need the toString() since replace() returns a String.
12,912,770
How do I remove the white space that are in front and back of & <http://chemist.com:8080/eShop/search_results.jsp?IDNUMBER=BB55-7344> & Source=BuildingBlocks
2012/10/16
[ "https://Stackoverflow.com/questions/12912770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310156/" ]
Try : ``` urlString = urlString.replaceAll(" ", "%20"); ``` This code replaces all the white space.
Try: ``` String newURI = oldURI.replaceAll("\\s+", ""); ```
12,912,770
How do I remove the white space that are in front and back of & <http://chemist.com:8080/eShop/search_results.jsp?IDNUMBER=BB55-7344> & Source=BuildingBlocks
2012/10/16
[ "https://Stackoverflow.com/questions/12912770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310156/" ]
Try : ``` urlString = urlString.replaceAll(" ", "%20"); ``` This code replaces all the white space.
``` if(result.contains(" and "){ resultnew = result.replace(" and ","&amp").toString(); } ``` You don't really need the "if" check, although it is faster (unless result ***always*** contains " and ") as replace() will return the input string if " and " is not found. You also don't need the toString() since replace() returns a String.
1,163
How should I describe a guy who moves to a city or urban area, but does not know much about how things work in those cities, and make an ass of themselves? The closest word I came up with is *unsophisticated*, but it is a broad term.
2013/02/07
[ "https://ell.stackexchange.com/questions/1163", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/299/" ]
Interesting question! *Make* and *Let* have subtly different meanings in certain cases, and are not interchangeable at all in others. To look at your examples: > > Don't make me feel alone. > > > *Make* here implies that the person you're talking to is intentionally trying to cause you to feel alone. They are making you feel this way, and by stopping their behavior you wouldn't feel alone anymore. Changing this to *let*, on the other hand: > > Don't let me feel alone. > > > *Let* here means that you already do feel alone, and are asking someone to help make you not feel alone. In this case their action will stop you from feeling alone, and if they do nothing you will continue to feel alone. So here the small difference between *make* and *let* actually completely changes the meaning of the sentence. > > Make me understand what you mean to say. > > > This is a command; you want to understand what they're saying, and you insist that they make it so you understand. This is perfectly acceptable, though a bit authoritarian; it's more likely one would say "Help me understand what you mean to say" as a request than to pose this command. That aside, *let* is not at all appropriate here. > > Let me understand what you mean to say. > > > This doesn't really make sense; asking someone to *let* you understand implies that they are currently preventing you from understanding and you would like them to stop. This seems an unlikely circumstance, and probably doesn't convey the meaning you're searching for. Now for your last case: > > You are requested not to let me feel alone. > > > This sounds oddly stilted and formal, but is grammatically correct. It carries the same meaning as "Don't let me feel alone", except it is phrased as a request rather than a command. If you're trying to politely ask someone to keep you company, for example, you might try saying: > > Please don't let me feel alone. > > > Or if you specifically don't want the person to leave because this is the action that will make you feel alone, you'd most commonly say: > > Please don't leave me alone. > > >
I would say the two have overlapping meanings, but *let* is more "passive," and *make* is more "active". IMPORTANT NOTE: by "passive" and "active," I am **not** referring to the [passive and active voice](http://owl.english.purdue.edu/owl/resource/539/01/). One definition of *passive* is "accepting or allowing what happens or what others do, without active response or resistance" (NOAD). So, in the instance of: > > Please don't let me feel alone. > > > I would interpret that to mean, *"I'm about to start feeling lonely; if you don't do something, I will start feeling lonely, so please do something."* Note that it is the hearer's *inaction* that will start the loneliness. However, with: > > Please don't make me feel alone. > > > I would interpret that to mean, *"You're about to do something; if you do that, then I will start feeling lonely, so please don't do that."* Here, it's the hearer's impending *action* that will cause the bout of loneliness. In both cases, the hearer is in a position to thwart the upcoming feelings of loneliness, which is why I said these words had "overlapping" meanings. However, one request solicits help through active intervention, while the other is a plea that the hearer not allow something to happen. The dictionary, it seems, would back up my interpretation. Again, from NOAD: > > **let** (*v.*) not prevent or forbid; allow > > > **make** (*v.*) cause (something) to exist or come about; bring about > > > Here's a similar example with a different verb pair: > > Please let the dog out. > > > is a request to open the door, so the dog can go outside. However: > > Please take the dog out. > > > is a request to make the dog go outside, even if the dog wants to stay inside.
37,683
**Wave soldering** I am trying to understand how wave soldering works. Unfortunately the [Wikipedia article](http://en.wikipedia.org/wiki/Wave_soldering) has has left me unsure about the process: 1. Is the entire board with its components quasi-immersed in liquid solder while it passes through the wave? (If not, the following question probably make no sense.) 2. If the board cuts into the wave, how is the wave maintained? 3. Why does this not leave superflous solder residue on the board? **Double-Sided SMT soldering** How are double sided boards with SMT components soldered? How is it prevented that the components on one side fall off?
2012/08/11
[ "https://electronics.stackexchange.com/questions/37683", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/8534/" ]
The wave only contacts the bottom side of the PCB. Once upon a time, a wave solder machine was used to solder SMT parts on the bottom side of the PCB but this is not used as much anymore in favor of more modern techniques. Here is the rough process for soldering PCB's with SMT parts on both sides, and through hole (TH) parts on the top side only. A. The bare PCB is turned "bottom side up". A solder paste is pressed through a stencil and onto the pads of the PCB. A pick and place machine places the parts onto the bottom side. The PCB is ran through an oven (hot-air convection or an IR oven) to melt the solder and attach the parts. An optional step is to place a small drop of glue under the parts. Solder paste first, then glue, then the parts are put onto the PCB and soldered. This glue helps keep the parts from falling off during a later step. B. The board is turned over (top side up), and the same process is repeated for all SMT parts on the top side of the PCB. By that I mean solder paste, parts placed, then through the oven. No glue is needed. During step B, the parts on the bottom of the PCB don't fall off. Obviously if they are glued down then they are stuck there, but most companies do not use glue. Without glue, the surface tension from the molten solder is enough to hold the parts in place. Some parts, particularly heavy parts without many pins, might not work with this technique since there is not enough surface tension to hold the parts on. C. All of the through-hole parts are then placed on the top side of the PCB. A solder pallet is attached to the bottom of the PCB. The PCB is ran through a wave solder machine to solder all the TH parts. Note: A solder pallet is basically a shield to protect the SMT parts from being removed in the wave. They are custom made for each PCB, and have holes and contours to expose the TH parts while shielding the SMT parts. The PCB must be designed with the solder pallet in mind, since you can't place the bottom side SMT parts too close to the TH parts and the SMT parts cannot be too tall. A relatively new technique for TH parts is to skip the wave solder machine completely. Back in step B, solder paste is placed on the TH pads (and in the holes) and the TH parts are inserted and soldered in the oven with the rest of the SMT parts. Some companies, like Motorola, have gotten rid of their wave solder machines in favor of this method. But most companies still use the older technique of using a wave solder machine with solder pallet. There are, of course, many variations of this entire process. I have just given a simple and brief overview. But it is fairly consistent with the way current manufacturing processes work today (things were different even just 10 years ago).
I do not know what you have pictured in your mind about solder wave, but it is a relatively simple process. The circuit board is set between 2 conveyor chains. The chains are simple roller chains but have "fingers" about 2 inches long. One conveyor is movable to accept different size circuit boards. They are also inclined maybe 7 degrees. The circuit boards are set on one end of the conveyor, they pass over a fluxer that applies solder flux to the connections to be soldered. The solder is contained in a tank that is HOT and the solder is in a liquid state. There are pumps that actually pump the solder within its own tank and creates the wave. Surface tension is very visible and the bottom of the circuit being soldered comes in contact with the solder as it passes over the wave. This is for through-hole soldering only and is not used for SMT components. Any flux residue is washed off in a commercial board washer. SMT components are a different story. The bare circuit board is run through a type of screen printer and solder paste is applied through a stencil. The components are placed with a Pick & Place machine, then the boards are run through a reflow oven. If the board is double-sided, a small amount of epoxy is placed under each component so it will not fall off the board during the reflow (oven) process of the second side. Hope I was able to answer your questions.
37,683
**Wave soldering** I am trying to understand how wave soldering works. Unfortunately the [Wikipedia article](http://en.wikipedia.org/wiki/Wave_soldering) has has left me unsure about the process: 1. Is the entire board with its components quasi-immersed in liquid solder while it passes through the wave? (If not, the following question probably make no sense.) 2. If the board cuts into the wave, how is the wave maintained? 3. Why does this not leave superflous solder residue on the board? **Double-Sided SMT soldering** How are double sided boards with SMT components soldered? How is it prevented that the components on one side fall off?
2012/08/11
[ "https://electronics.stackexchange.com/questions/37683", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/8534/" ]
The wave only contacts the bottom side of the PCB. Once upon a time, a wave solder machine was used to solder SMT parts on the bottom side of the PCB but this is not used as much anymore in favor of more modern techniques. Here is the rough process for soldering PCB's with SMT parts on both sides, and through hole (TH) parts on the top side only. A. The bare PCB is turned "bottom side up". A solder paste is pressed through a stencil and onto the pads of the PCB. A pick and place machine places the parts onto the bottom side. The PCB is ran through an oven (hot-air convection or an IR oven) to melt the solder and attach the parts. An optional step is to place a small drop of glue under the parts. Solder paste first, then glue, then the parts are put onto the PCB and soldered. This glue helps keep the parts from falling off during a later step. B. The board is turned over (top side up), and the same process is repeated for all SMT parts on the top side of the PCB. By that I mean solder paste, parts placed, then through the oven. No glue is needed. During step B, the parts on the bottom of the PCB don't fall off. Obviously if they are glued down then they are stuck there, but most companies do not use glue. Without glue, the surface tension from the molten solder is enough to hold the parts in place. Some parts, particularly heavy parts without many pins, might not work with this technique since there is not enough surface tension to hold the parts on. C. All of the through-hole parts are then placed on the top side of the PCB. A solder pallet is attached to the bottom of the PCB. The PCB is ran through a wave solder machine to solder all the TH parts. Note: A solder pallet is basically a shield to protect the SMT parts from being removed in the wave. They are custom made for each PCB, and have holes and contours to expose the TH parts while shielding the SMT parts. The PCB must be designed with the solder pallet in mind, since you can't place the bottom side SMT parts too close to the TH parts and the SMT parts cannot be too tall. A relatively new technique for TH parts is to skip the wave solder machine completely. Back in step B, solder paste is placed on the TH pads (and in the holes) and the TH parts are inserted and soldered in the oven with the rest of the SMT parts. Some companies, like Motorola, have gotten rid of their wave solder machines in favor of this method. But most companies still use the older technique of using a wave solder machine with solder pallet. There are, of course, many variations of this entire process. I have just given a simple and brief overview. But it is fairly consistent with the way current manufacturing processes work today (things were different even just 10 years ago).
**wave soldering** For wave soldering the PCB passes over a bath of molten solder where the solder is pushed up so that it strikes along the bottom side of the PCB. You'll need a solder resist mask to prevent to have solder over all the copper. Note that also SMDs can be wave soldered, but then the orientation of the parts is important. Some parts have to be placed perpendicular to the wave direction. Fine pitch parts like 0.4 mm QFPs can't be wave soldered because all the pins will be shorted, but QFPs with a higher pitch can. They need "solder thieves", which are solder pads at the end of a row of pins to gather residual solder. ![enter image description here](https://i.stack.imgur.com/3aAyb.gif) A QFP may have to be placed at a 45° angle, and will have the solder thieves at one of the corners: ![enter image description here](https://i.stack.imgur.com/VZiCf.png) The wave direction is important during PCB layout and panelization, and the production engineer should get clear instructions on it. **reflow soldering** SMDs for two-sided placement are glued on one side. After solder paste is applied with a stencil a glue dot machine places glue dots for the parts (at an incredible rate of more than 10 per second). Then the parts are placed, the panel is flipped over, and the other side gets solder paste and component placement.
37,683
**Wave soldering** I am trying to understand how wave soldering works. Unfortunately the [Wikipedia article](http://en.wikipedia.org/wiki/Wave_soldering) has has left me unsure about the process: 1. Is the entire board with its components quasi-immersed in liquid solder while it passes through the wave? (If not, the following question probably make no sense.) 2. If the board cuts into the wave, how is the wave maintained? 3. Why does this not leave superflous solder residue on the board? **Double-Sided SMT soldering** How are double sided boards with SMT components soldered? How is it prevented that the components on one side fall off?
2012/08/11
[ "https://electronics.stackexchange.com/questions/37683", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/8534/" ]
The wave only contacts the bottom side of the PCB. Once upon a time, a wave solder machine was used to solder SMT parts on the bottom side of the PCB but this is not used as much anymore in favor of more modern techniques. Here is the rough process for soldering PCB's with SMT parts on both sides, and through hole (TH) parts on the top side only. A. The bare PCB is turned "bottom side up". A solder paste is pressed through a stencil and onto the pads of the PCB. A pick and place machine places the parts onto the bottom side. The PCB is ran through an oven (hot-air convection or an IR oven) to melt the solder and attach the parts. An optional step is to place a small drop of glue under the parts. Solder paste first, then glue, then the parts are put onto the PCB and soldered. This glue helps keep the parts from falling off during a later step. B. The board is turned over (top side up), and the same process is repeated for all SMT parts on the top side of the PCB. By that I mean solder paste, parts placed, then through the oven. No glue is needed. During step B, the parts on the bottom of the PCB don't fall off. Obviously if they are glued down then they are stuck there, but most companies do not use glue. Without glue, the surface tension from the molten solder is enough to hold the parts in place. Some parts, particularly heavy parts without many pins, might not work with this technique since there is not enough surface tension to hold the parts on. C. All of the through-hole parts are then placed on the top side of the PCB. A solder pallet is attached to the bottom of the PCB. The PCB is ran through a wave solder machine to solder all the TH parts. Note: A solder pallet is basically a shield to protect the SMT parts from being removed in the wave. They are custom made for each PCB, and have holes and contours to expose the TH parts while shielding the SMT parts. The PCB must be designed with the solder pallet in mind, since you can't place the bottom side SMT parts too close to the TH parts and the SMT parts cannot be too tall. A relatively new technique for TH parts is to skip the wave solder machine completely. Back in step B, solder paste is placed on the TH pads (and in the holes) and the TH parts are inserted and soldered in the oven with the rest of the SMT parts. Some companies, like Motorola, have gotten rid of their wave solder machines in favor of this method. But most companies still use the older technique of using a wave solder machine with solder pallet. There are, of course, many variations of this entire process. I have just given a simple and brief overview. But it is fairly consistent with the way current manufacturing processes work today (things were different even just 10 years ago).
This is a somewhat archaic method where the entire bottom of the board is drawn along a flowing pool of solder: <https://www.youtube.com/watch?v=inHzaJIE7-4> Newer methods include a small cnc solder fountain that is applied to the individual solder points on the board, rather than a bath that the entire unit runs through. The pros and cons of each, I'm not entirely sure. Also, here's a video of a pick and place machine: <https://www.youtube.com/watch?v=tn0EKtLOVx4>
37,683
**Wave soldering** I am trying to understand how wave soldering works. Unfortunately the [Wikipedia article](http://en.wikipedia.org/wiki/Wave_soldering) has has left me unsure about the process: 1. Is the entire board with its components quasi-immersed in liquid solder while it passes through the wave? (If not, the following question probably make no sense.) 2. If the board cuts into the wave, how is the wave maintained? 3. Why does this not leave superflous solder residue on the board? **Double-Sided SMT soldering** How are double sided boards with SMT components soldered? How is it prevented that the components on one side fall off?
2012/08/11
[ "https://electronics.stackexchange.com/questions/37683", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/8534/" ]
I do not know what you have pictured in your mind about solder wave, but it is a relatively simple process. The circuit board is set between 2 conveyor chains. The chains are simple roller chains but have "fingers" about 2 inches long. One conveyor is movable to accept different size circuit boards. They are also inclined maybe 7 degrees. The circuit boards are set on one end of the conveyor, they pass over a fluxer that applies solder flux to the connections to be soldered. The solder is contained in a tank that is HOT and the solder is in a liquid state. There are pumps that actually pump the solder within its own tank and creates the wave. Surface tension is very visible and the bottom of the circuit being soldered comes in contact with the solder as it passes over the wave. This is for through-hole soldering only and is not used for SMT components. Any flux residue is washed off in a commercial board washer. SMT components are a different story. The bare circuit board is run through a type of screen printer and solder paste is applied through a stencil. The components are placed with a Pick & Place machine, then the boards are run through a reflow oven. If the board is double-sided, a small amount of epoxy is placed under each component so it will not fall off the board during the reflow (oven) process of the second side. Hope I was able to answer your questions.
This is a somewhat archaic method where the entire bottom of the board is drawn along a flowing pool of solder: <https://www.youtube.com/watch?v=inHzaJIE7-4> Newer methods include a small cnc solder fountain that is applied to the individual solder points on the board, rather than a bath that the entire unit runs through. The pros and cons of each, I'm not entirely sure. Also, here's a video of a pick and place machine: <https://www.youtube.com/watch?v=tn0EKtLOVx4>
37,683
**Wave soldering** I am trying to understand how wave soldering works. Unfortunately the [Wikipedia article](http://en.wikipedia.org/wiki/Wave_soldering) has has left me unsure about the process: 1. Is the entire board with its components quasi-immersed in liquid solder while it passes through the wave? (If not, the following question probably make no sense.) 2. If the board cuts into the wave, how is the wave maintained? 3. Why does this not leave superflous solder residue on the board? **Double-Sided SMT soldering** How are double sided boards with SMT components soldered? How is it prevented that the components on one side fall off?
2012/08/11
[ "https://electronics.stackexchange.com/questions/37683", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/8534/" ]
**wave soldering** For wave soldering the PCB passes over a bath of molten solder where the solder is pushed up so that it strikes along the bottom side of the PCB. You'll need a solder resist mask to prevent to have solder over all the copper. Note that also SMDs can be wave soldered, but then the orientation of the parts is important. Some parts have to be placed perpendicular to the wave direction. Fine pitch parts like 0.4 mm QFPs can't be wave soldered because all the pins will be shorted, but QFPs with a higher pitch can. They need "solder thieves", which are solder pads at the end of a row of pins to gather residual solder. ![enter image description here](https://i.stack.imgur.com/3aAyb.gif) A QFP may have to be placed at a 45° angle, and will have the solder thieves at one of the corners: ![enter image description here](https://i.stack.imgur.com/VZiCf.png) The wave direction is important during PCB layout and panelization, and the production engineer should get clear instructions on it. **reflow soldering** SMDs for two-sided placement are glued on one side. After solder paste is applied with a stencil a glue dot machine places glue dots for the parts (at an incredible rate of more than 10 per second). Then the parts are placed, the panel is flipped over, and the other side gets solder paste and component placement.
This is a somewhat archaic method where the entire bottom of the board is drawn along a flowing pool of solder: <https://www.youtube.com/watch?v=inHzaJIE7-4> Newer methods include a small cnc solder fountain that is applied to the individual solder points on the board, rather than a bath that the entire unit runs through. The pros and cons of each, I'm not entirely sure. Also, here's a video of a pick and place machine: <https://www.youtube.com/watch?v=tn0EKtLOVx4>
694,723
I just built a PC for my wife; i3-4130 / B85 / 8GB RAM / Radeon 7730 1GB GDDR5 / 120GB Intel 330 SSD / 22" HP IPS Monitor. She's an interior designer and she uses this software, 20-20 Design. She's satisfied with its performance over her Samsung laptop with i5-2430M with integrated graphics (the new desktop renders significantly quicker and has a lot better image quality), although even quicker render times will always be nice. Of course I am on a budget. My questions are: 1. Would it be better if I instead purchased a cheaper but 2GB video card? Perhaps a Radeon 7730 2GB DDR3? 2. If she wanted to render quicker for a similar price, would it be better if I purchased an AMD processor with more cores? Or will the Intel Haswell still do a better job with its 2 cores? 3. Is it the Haswell i3-4130 that renders much faster than the Sandy Bridge i5-2430m? They're both dual-cores (although 3.4Ghz vs 2.4Ghz), or does the video card also help in rendering times?
2013/12/30
[ "https://superuser.com/questions/694723", "https://superuser.com", "https://superuser.com/users/257654/" ]
Just looking at the [System Requirements](http://www.2020technologies.com/home/interior-design/kitchen-bath-and-home-organization/2020-design#&panel1-1), I would say that if you want it faster, I'd go for a CPU upgrade. However, an easy way to see if it's the CPU or GPU holding you back, you could have a peek in the task manager to see whether the CPU is maxing out when a render is being done. If it's maxing out, then upgrading the CPU will help. If it's not, then the GPU is what's holding the speed back. --- In response to your questions > > Would it be better if I instead purchased a cheaper but 2GB video card? Perhaps a Radeon 7730 2GB DDR3? > > > In this case, they're much the sameness. The amount of RAM is important to your needs, not the speed. > > If she wanted to render quicker for a similar price, would it be better if I purchased an AMD processor with more cores? Or will the Intel Haswell still do a better job with its 2 cores? > > > That would be hard to say. It would depend on how the application is designed. Generally however, Intel CPUs perform better than AMD CPUs. > > Is it the Haswell i3-4130 that renders much faster than the Sandy Bridge i5-2430m? They're both dual-cores (although 3.4Ghz vs 2.4Ghz), or does the video card also help in rendering times? > > > I'd say it's the graphics card that helps it render faster. But that's just an educated guess. The graphics card can do a lot of the heavy lifting when it comes to rendering 3D scenes. Lighting, reflections, transparency etc would likely be done by the graphics card.
I almost commented on Lawrence's answer, but reconsidered as my thoughts stand as an answer on their own. I've been down this journey a few times via various paths... and I'm still not exactly satisfied with the results. *Now, on to the arms race of "graphics" performance:* **CPU** Start with Lawrence's advice on checking the CPU in performance monitor. Most programs are sadly single threaded. If this is the case, then more cores just empties your wallet. I use Rhinoceros 3D for CAD and it is almost always single threaded (only uses 1 core). When your app is single threaded and can't use more cores, you need the newest architecture you can afford, the fastest clock speed possible, but with the least cores available. That means get a Core i3 with 3GHz+ clock speed. Mentioning Core i3 may not be the most current advice: google site:overclock.net about CPU performance. And Intel all the way. IMHO, AMD is great for servers (I have a 1055t in mine) but Intel for desktops. Caveat: when you're maxing out that program and only have 2 cores, make sure THAT is the only program running. You can alt-tab over to your Firefox with 30 tabs open and play candy crush. My Experience: I've gone from dual core to core 2 duo to 6 core to xeon 4 core (dual thread), all of them overclocked. I like to punish the program than switch to something else and stay productive while my task has the CAD program go all white. **RAM** I consider 4G to be insufficient for anything more than having a browser and one or two office programs open. Check out the performance monitor, you'll see. The problem is, you need to pay attention to the Windows OS version and its RAM limits. Right off, you need to be on 64 bit version of the OS. You can get 8GB in Win7 Home Basic. That's a great first step. ([Reference](http://msdn.microsoft.com/en-us/library/windows/desktop/aa366778%28v=vs.85%29.aspx#physical_memory_limits_windows_7)) Sadly, Home Premium limits you to 16G, so anything at work that does more than office-y stuff has to run Win 7 64 Pro. Speed or version of RAM is almost irrelevant imho. You're not overclocking or benchmarking. If 2G or 4G is holding you back, the cheapest 8G is going to feel like a Ferrari. **GPU** This is the tough one. Once the above two are assuredly not holding you back, this is the last continent to explore. If I hadn't personally seen what a Quadro workstation card can do, I would not be a believer in graphics cards. I had a pretty good on-board HDMI output on my CAD box of the moment and was taking my computer back and forth with me to work. I had spare peripherals at home and work, so it was only the box. At work I was using a 24" DVI monitor and at home is a higher end 42" Sony HDTV. I was given (*as in for free, like free beer*) a Quadro FX3800. It was waaay more than I needed, but a customer saw me talk about my problems and gave me a factory hook-up. I'm in the 2nd or 3rd week working on my CAD project at home and I see something... off the corner of my model... zoom zoom zoom zoom oh wow, there's trash hanging out there I didn't notice before! Those last two zooms were impossible to "see" before the new card. *But*, I didn't talk about rendering per-se, zooming in and re-drawing is a cousin to rendering, so we could be talking about the same thing or semantics has us in separate topics when it comes to GPU performance. You need to talk to technical support at the manufacturer of the software you're using and find out exactly what video hardware they have observed in their own lab to appear to be the best performance at realistic pricing. From my experience, they'll do their best to help because then you'll like them more and keep on buying their products. **GUI** When doing CAD-like stuff, see if the [3D Connexion Space Navigator](http://www.3dconnexion.com/products/spacenavigator.html) works in your software! OMG, I love it so much I bought a 2nd one to sit at home for the few times I do CAD at home on my laptop. It is like flying a helicopter through your drawing; you can get the view exactly on what you're doing! I have found so many minuscule defects where edges don't meet up properly via this + a good GPU. **My System** OK, so I gave all this advice. Here's [my CAD computer](http://www.overclock.net/lists/display/view/id/5217451/version/5217453). What's sad is that I humbly say "yeah it's ok", when it's a stonkin epic computer. The only thing(s) I bought new for it were the RAM and the AMD GPU. The rest was legacy stuff from other computers. The core i7 was from a Gateway store-box computer. It was the only thing worth beans in that whole computer. I bought a core i3 for it and it's a spare workstation for guests now. The Motherboard had only 2 slots and I recall was limited to 4G of RAM. :P I ganked it's CPU when I saw a core i3 on OCN for sale, which I put in my CAD box. The AMD GPU was on a special sale where they gave me a gift card for buying it. The only reason I bought it was when I moved my Quadro to the latest build, it stopped working. Got me why. I researched and the W5000 was the best performance for the money at the moment. RAM? 16G was enough for a long while. Then I got the laser scanner which upped the ante a LOT for filesize. :P There are 4 slots in the motherboard with 4 4GB sticks. So I went to 4 8GB sticks. If you buy memory, buy 8GB sticks so you only need to buy TWO to upgrade from 16G to 32G!! \*Next time\*\* I'm buying a server-type motherboard that can have even more RAM. The more ram you've got, the less programs need to "think" it seems. Get enough and you can make a RAM disk and save your files there, too. Win7Pro goes up to 192G; that's bigger than my SSD! After that, I'd get whatever processor has the highest "boost" speed and not care about cores. 4 or more are all the same unless you're certain your tasks are using those extra cores.
49,825,329
I want to shuffle non-zero elements of each column in a matrix but keep the zero elements at the same place. Like I have this: ``` A = [10 0 30 40 50 60 11 0 31 41 0 61 0 22 32 42 0 62 13 23 0 43 0 63 0 24 34 44 54 64 15 0 35 0 0 65 16 26 36 46 56 66] ``` And I want this: ``` B = [13 0 32 44 54 64 11 0 35 42 0 63 0 24 36 40 0 61 16 23 0 43 0 62 0 22 31 41 56 60 10 0 30 0 0 66 15 26 34 46 50 65] ``` So herein I have the zeros at the exact same place (i.e. ~A = ~B) and the non-zero elements are shuffled. Obviously shuffling the columns using 'randperm' does not work as it does not allow me to keep zeroes at the same place!
2018/04/13
[ "https://Stackoverflow.com/questions/49825329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7867604/" ]
This is a solution that works for one column: Making a new vector `C` containing the nonzero entries, shuffling those, and pasting them back into the nonzero entries of `B` should do exactly that. Now you can adjust this to work for matrices by looping over all columns. ```matlab A = [10, 11, 0, 13, 0, 15, 16]; B = A; C = A(A~=0); B(A~=0) = C(randperm(numel(C))); A B ``` [Try it online!](https://tio.run/##y08uSSxL/f/fUcFWQSHa0EBHwdBQRwFEGUMoUyA2i7XmcgIqcLTmcgZRGo51tgaaQDEIAyjkrFGUmJdSkFqUq5FXmpuao@GsqQlU4Mjl9P8/AA "Octave – Try It Online")
I wrote a function for you ``` function a=shuffle(src) [rows, cols] = size(src); a = zeros(rows,cols); for c = 1:cols lastIndex = 1; col = []; for r = 1:rows if(src(r,c) ~= 0) col(lastIndex) = src(r,c); lastIndex = lastIndex + 1; end end indexes = randperm(length(col)); lastIndex = 1; for r = 1:rows if(src(r,c) == 0) a(r,c) = 0; else a(r,c) = col(indexes(lastIndex)); lastIndex = lastIndex + 1; end end end end ``` It's not optimized, I leave it to You. It extracts the non-zeros to a vector, and takes randperm values from this vector to the new matrix, if the old matrix didnt have 0 there.
49,825,329
I want to shuffle non-zero elements of each column in a matrix but keep the zero elements at the same place. Like I have this: ``` A = [10 0 30 40 50 60 11 0 31 41 0 61 0 22 32 42 0 62 13 23 0 43 0 63 0 24 34 44 54 64 15 0 35 0 0 65 16 26 36 46 56 66] ``` And I want this: ``` B = [13 0 32 44 54 64 11 0 35 42 0 63 0 24 36 40 0 61 16 23 0 43 0 62 0 22 31 41 56 60 10 0 30 0 0 66 15 26 34 46 50 65] ``` So herein I have the zeros at the exact same place (i.e. ~A = ~B) and the non-zero elements are shuffled. Obviously shuffling the columns using 'randperm' does not work as it does not allow me to keep zeroes at the same place!
2018/04/13
[ "https://Stackoverflow.com/questions/49825329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7867604/" ]
Here's an alternative to the explicit loop-over-columns approach: ``` [~, jj, vv] = find(A); s = accumarray(jj, vv, [], @(x){x(randperm(numel(x)))}); B = A; B(B~=0) = cell2mat(s); ```
This is a solution that works for one column: Making a new vector `C` containing the nonzero entries, shuffling those, and pasting them back into the nonzero entries of `B` should do exactly that. Now you can adjust this to work for matrices by looping over all columns. ```matlab A = [10, 11, 0, 13, 0, 15, 16]; B = A; C = A(A~=0); B(A~=0) = C(randperm(numel(C))); A B ``` [Try it online!](https://tio.run/##y08uSSxL/f/fUcFWQSHa0EBHwdBQRwFEGUMoUyA2i7XmcgIqcLTmcgZRGo51tgaaQDEIAyjkrFGUmJdSkFqUq5FXmpuao@GsqQlU4Mjl9P8/AA "Octave – Try It Online")
49,825,329
I want to shuffle non-zero elements of each column in a matrix but keep the zero elements at the same place. Like I have this: ``` A = [10 0 30 40 50 60 11 0 31 41 0 61 0 22 32 42 0 62 13 23 0 43 0 63 0 24 34 44 54 64 15 0 35 0 0 65 16 26 36 46 56 66] ``` And I want this: ``` B = [13 0 32 44 54 64 11 0 35 42 0 63 0 24 36 40 0 61 16 23 0 43 0 62 0 22 31 41 56 60 10 0 30 0 0 66 15 26 34 46 50 65] ``` So herein I have the zeros at the exact same place (i.e. ~A = ~B) and the non-zero elements are shuffled. Obviously shuffling the columns using 'randperm' does not work as it does not allow me to keep zeroes at the same place!
2018/04/13
[ "https://Stackoverflow.com/questions/49825329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7867604/" ]
Here's an alternative to the explicit loop-over-columns approach: ``` [~, jj, vv] = find(A); s = accumarray(jj, vv, [], @(x){x(randperm(numel(x)))}); B = A; B(B~=0) = cell2mat(s); ```
I wrote a function for you ``` function a=shuffle(src) [rows, cols] = size(src); a = zeros(rows,cols); for c = 1:cols lastIndex = 1; col = []; for r = 1:rows if(src(r,c) ~= 0) col(lastIndex) = src(r,c); lastIndex = lastIndex + 1; end end indexes = randperm(length(col)); lastIndex = 1; for r = 1:rows if(src(r,c) == 0) a(r,c) = 0; else a(r,c) = col(indexes(lastIndex)); lastIndex = lastIndex + 1; end end end end ``` It's not optimized, I leave it to You. It extracts the non-zeros to a vector, and takes randperm values from this vector to the new matrix, if the old matrix didnt have 0 there.
57,830,632
i have a spinner in add new data, I want the selected data to be an image in the item of recyclerview anyone knows how to make like that like this but spinner that is from activity not item recycler view and thats the problem, how to get id spinner in adapter ``` holder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String item = parent.getItemAtPosition(position).toString(); if (item == important){ holder.img_category.setImageResource(R.drawable.important); }else if (item == notImportant){ holder.img_category.setImageResource(R.drawable.notimportant); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); ```
2019/09/07
[ "https://Stackoverflow.com/questions/57830632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11863128/" ]
Hi look updated answer ``` selectImageType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { if(i!=0) { selectedItem=binding.selectImageType.getSelectedItem().toString(); Log.e(TAG, "onItemSelected: "+selectedItem); if(!selectedItem.equalsIgnoreCase("")) { spinnerDemoAdapter=new SpinnerDemoAdapter(dataImageList,selectedItem,SpinnerDemoActivity.this); binding.recycleSpinnerDemo.setHasFixedSize(true); binding.recycleSpinnerDemo.setLayoutManager(new LinearLayoutManager(SpinnerDemoActivity.this, RecyclerView.VERTICAL,false)); binding.recycleSpinnerDemo.setAdapter(spinnerDemoAdapter); spinnerDemoAdapter.notifyDataSetChanged(); } } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); ``` And this below is your adapter code I take arraylist here and add random values for testing purpose ``` public SpinnerDemoAdapter(ArrayList<String> arrayList, String selectedItem, Context mContext) { this.arrayList = arrayList; this.selectedItem = selectedItem; this.mContext = mContext; } public void onBindViewHolder(@NonNull ViewHolder holder, int position) { if (!selectedItem.equalsIgnoreCase("")) { Log.e(TAG, "onBindViewHolder: "+selectedItem); if (selectedItem.equalsIgnoreCase("important")) { Glide.with(mContext).load(R.drawable.woman).into(holder.imageview); } else if (selectedItem.equalsIgnoreCase("notimportant")) { Glide.with(mContext).load(R.drawable.man).into(holder.imageview); } } } ```
use Glide for image set in imageView check below code. add -> 'implementation 'com.github.bumptech.glide:glide:4.9.0' into your app.gradle yes check that item getting your desired values using log and use `if(item.equalsIgnoreCase(important))` to check your if condition. ``` holder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String item = parent.getItemAtPosition(position).toString(); log.e("TAG","Selected ITEM :"+item); if(item.equalsIgnoreCase(important)){ Glide.with(context).load(R.drawable.important).into(holder.img_category); //here }else if(item.equalsIgnoreCase(notImportant)){ Glide.with(context).load(R.drawable.notimportant).into(holder.img_category); // here } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); ```
15,405,667
The following applies: ``` var rounded = Decimal.Round(7.635m, 2); //rounded: 7.63 ``` This, to me, is wrong and unexpected behavior. I would assume the value of *rounded* to be **7.64**. To achieve this, I can do: ``` var rounded = Decimal.Round(7.635m, 2, MidpointRounding.AwayFromZero); //rounded: 7.64 ``` How can this **not** be the default behavior of `Decimal.Round`? Any good reason for this?
2013/03/14
[ "https://Stackoverflow.com/questions/15405667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/896348/" ]
> > How can this not be the default behavior of Decimal.Round? Any good > reason for this? > > > If you look at the documentation of [Decimal.Round Method (Decimal)](http://msdn.microsoft.com/en-us/library/k4e2bye2.aspx) > > The **behavior of this method follows IEEE Standard 754, section 4**. > This kind of rounding is sometimes called *round half to even* or > *banker's rounding*. It minimizes rounding errors that result from > consistently rounding a midpoint value in a single direction. It is > equivalent to calling the Round(Decimal, MidpointRounding) method with > a mode argument of MidpointRounding.ToEven. > > >
From [`Math.Round(Decimal, Int32)`](http://msdn.microsoft.com/en-us/library/vstudio/zy06z30k%28v=vs.90%29.aspx) Method > > The behavior of this method follows IEEE Standard 754, section 4. This > kind of rounding is sometimes called rounding to nearest, or banker's > rounding. It minimizes rounding errors that result from consistently > rounding a midpoint value in a single direction. > > > This method is equivalent to calling the Round method with a mode > argument of MidpointRounding.ToEven. If there is a single non-zero > digit in d to the right of the decimals decimal position and its value > is 5, the digit in the decimals position is rounded up if it is odd, > or left unchanged if it is even. If d has fewer fractional digits than > decimals, d is returned unchanged. > > >
15,405,667
The following applies: ``` var rounded = Decimal.Round(7.635m, 2); //rounded: 7.63 ``` This, to me, is wrong and unexpected behavior. I would assume the value of *rounded* to be **7.64**. To achieve this, I can do: ``` var rounded = Decimal.Round(7.635m, 2, MidpointRounding.AwayFromZero); //rounded: 7.64 ``` How can this **not** be the default behavior of `Decimal.Round`? Any good reason for this?
2013/03/14
[ "https://Stackoverflow.com/questions/15405667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/896348/" ]
> > How can this not be the default behavior of Decimal.Round? Any good > reason for this? > > > If you look at the documentation of [Decimal.Round Method (Decimal)](http://msdn.microsoft.com/en-us/library/k4e2bye2.aspx) > > The **behavior of this method follows IEEE Standard 754, section 4**. > This kind of rounding is sometimes called *round half to even* or > *banker's rounding*. It minimizes rounding errors that result from > consistently rounding a midpoint value in a single direction. It is > equivalent to calling the Round(Decimal, MidpointRounding) method with > a mode argument of MidpointRounding.ToEven. > > >
The reason is they implemented a method following IEEE Standard 754, section 4. This is called rounding to nearest or sometimes bankers rounding. It's just one of many ways to do rounding and they choose this one. See: <http://en.wikipedia.org/wiki/Bankers_rounding> And for more information: [Why does .NET use banker's rounding as default?](https://stackoverflow.com/questions/311696/why-does-net-use-bankers-rounding-as-default)
15,405,667
The following applies: ``` var rounded = Decimal.Round(7.635m, 2); //rounded: 7.63 ``` This, to me, is wrong and unexpected behavior. I would assume the value of *rounded* to be **7.64**. To achieve this, I can do: ``` var rounded = Decimal.Round(7.635m, 2, MidpointRounding.AwayFromZero); //rounded: 7.64 ``` How can this **not** be the default behavior of `Decimal.Round`? Any good reason for this?
2013/03/14
[ "https://Stackoverflow.com/questions/15405667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/896348/" ]
From [`Math.Round(Decimal, Int32)`](http://msdn.microsoft.com/en-us/library/vstudio/zy06z30k%28v=vs.90%29.aspx) Method > > The behavior of this method follows IEEE Standard 754, section 4. This > kind of rounding is sometimes called rounding to nearest, or banker's > rounding. It minimizes rounding errors that result from consistently > rounding a midpoint value in a single direction. > > > This method is equivalent to calling the Round method with a mode > argument of MidpointRounding.ToEven. If there is a single non-zero > digit in d to the right of the decimals decimal position and its value > is 5, the digit in the decimals position is rounded up if it is odd, > or left unchanged if it is even. If d has fewer fractional digits than > decimals, d is returned unchanged. > > >
The reason is they implemented a method following IEEE Standard 754, section 4. This is called rounding to nearest or sometimes bankers rounding. It's just one of many ways to do rounding and they choose this one. See: <http://en.wikipedia.org/wiki/Bankers_rounding> And for more information: [Why does .NET use banker's rounding as default?](https://stackoverflow.com/questions/311696/why-does-net-use-bankers-rounding-as-default)
20,378,733
I have building a web site but i have a error code and i couldnt fould a fix it Error > > Parse error: syntax error, unexpected T\_PAAMAYIM\_NEKUDOTAYIM in /home/eneskura/public\_html/administrator/components/com\_tz\_portfolio/helpers/tz\_portfolio.php on line 42 > > > line 42- ``` $class::addEntry(JText::('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS'), 'index.php?option=com_tz_portfolio&view=fieldsgroup', $vName == 'fieldsgroup'); ``` how i can i fix it? Site: eneskuray.com php 5.2.17 litespeed full php ``` <?php // No direct access defined('_JEXEC') or die; class TZ_PortfolioHelper { public static $extension = 'com_content'; /** * Configure the Linkbar. * * @param string $vName The name of the active view. * * @return void * @since 1.6 */ public static function addSubmenu($vName) { $class = 'JHtmlSidebar'; if(!COM_TZ_PORTFOLIO_JVERSION_COMPARE){ $class = 'JSubMenuHelper'; } $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS'), 'index.php?option=com_tz_portfolio&view=fieldsgroup', $vName == 'fieldsgroup'); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_FIELDS'), 'index.php?option=com_tz_portfolio&view=fields', $vName == 'fields' ); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_CATEGORIES'), 'index.php?option=com_tz_portfolio&view=categories', $vName == 'categories'); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_ARTICLES'), 'index.php?option=com_tz_portfolio&view=articles', $vName == 'articles' ); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_FEATURED_ARTICLES'), 'index.php?option=com_tz_portfolio&view=featured', $vName == 'featured' ); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_TAGS'), 'index.php?option=com_tz_portfolio&view=tags', $vName == 'tags'); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_USERS'), 'index.php?option=com_tz_portfolio&view=users', $vName == 'users'); } /** * Gets a list of the actions that can be performed. * * @param int The category ID. * @param int The article ID. * * @return JObject * @since 1.6 */ public static function getActions($categoryId = 0, $articleId = 0) { $user = JFactory::getUser(); $result = new JObject; if (empty($articleId) && empty($categoryId)) { $assetName = 'com_tz_portfolio'; } elseif (empty($articleId)) { $assetName = 'com_tz_portfolio.category.'.(int) $categoryId; } else { $assetName = 'com_tz_portfolio.article.'.(int) $articleId; } $actions = array( 'core.admin', 'core.manage', 'core.create', 'core.edit', 'core.edit.own', 'core.edit.state', 'core.delete' ); foreach ($actions as $action) { $result->set($action, $user->authorise($action, $assetName)); } return $result; } /** * Applies the content tag filters to arbitrary text as per settings for current user group * @param text The string to filter * @return string The filtered string */ public static function filterText($text) { // Filter settings $config = JComponentHelper::getParams('com_config'); $user = JFactory::getUser(); $userGroups = JAccess::getGroupsByUser($user->get('id')); $filters = $config->get('filters'); $blackListTags = array(); $blackListAttributes = array(); $customListTags = array(); $customListAttributes = array(); $whiteListTags = array(); $whiteListAttributes = array(); $noHtml = false; $whiteList = false; $blackList = false; $customList = false; $unfiltered = false; // Cycle through each of the user groups the user is in. // Remember they are included in the Public group as well. foreach ($userGroups as $groupId) { // May have added a group but not saved the filters. if (!isset($filters->$groupId)) { continue; } // Each group the user is in could have different filtering properties. $filterData = $filters->$groupId; $filterType = strtoupper($filterData->filter_type); if ($filterType == 'NH') { // Maximum HTML filtering. $noHtml = true; } elseif ($filterType == 'NONE') { // No HTML filtering. $unfiltered = true; } else { // Black, white or custom list. // Preprocess the tags and attributes. $tags = explode(',', $filterData->filter_tags); $attributes = explode(',', $filterData->filter_attributes); $tempTags = array(); $tempAttributes = array(); foreach ($tags as $tag) { $tag = trim($tag); if ($tag) { $tempTags[] = $tag; } } foreach ($attributes as $attribute) { $attribute = trim($attribute); if ($attribute) { $tempAttributes[] = $attribute; } } // Collect the black or white list tags and attributes. // Each lists is cummulative. if ($filterType == 'BL') { $blackList = true; $blackListTags = array_merge($blackListTags, $tempTags); $blackListAttributes = array_merge($blackListAttributes, $tempAttributes); } elseif ($filterType == 'CBL') { // Only set to true if Tags or Attributes were added if ($tempTags || $tempAttributes) { $customList = true; $customListTags = array_merge($customListTags, $tempTags); $customListAttributes = array_merge($customListAttributes, $tempAttributes); } } elseif ($filterType == 'WL') { $whiteList = true; $whiteListTags = array_merge($whiteListTags, $tempTags); $whiteListAttributes = array_merge($whiteListAttributes, $tempAttributes); } } } // Remove duplicates before processing (because the black list uses both sets of arrays). $blackListTags = array_unique($blackListTags); $blackListAttributes = array_unique($blackListAttributes); $customListTags = array_unique($customListTags); $customListAttributes = array_unique($customListAttributes); $whiteListTags = array_unique($whiteListTags); $whiteListAttributes = array_unique($whiteListAttributes); // Unfiltered assumes first priority. if ($unfiltered) { // Dont apply filtering. } else { // Custom blacklist precedes Default blacklist if ($customList) { $filter = JFilterInput::getInstance(array(), array(), 1, 1); // Override filter's default blacklist tags and attributes if ($customListTags) { $filter->tagBlacklist = $customListTags; } if ($customListAttributes) { $filter->attrBlacklist = $customListAttributes; } } // Black lists take third precedence. elseif ($blackList) { // Remove the white-listed attributes from the black-list. $filter = JFilterInput::getInstance( array_diff($blackListTags, $whiteListTags), // blacklisted tags array_diff($blackListAttributes, $whiteListAttributes), // blacklisted attributes 1, // blacklist tags 1 // blacklist attributes ); // Remove white listed tags from filter's default blacklist if ($whiteListTags) { $filter->tagBlacklist = array_diff($filter->tagBlacklist, $whiteListTags); } // Remove white listed attributes from filter's default blacklist if ($whiteListAttributes) { $filter->attrBlacklist = array_diff($filter->attrBlacklist); } } // White lists take fourth precedence. elseif ($whiteList) { $filter = JFilterInput::getInstance($whiteListTags, $whiteListAttributes, 0, 0, 0); // turn off xss auto clean } // No HTML takes last place. else { $filter = JFilterInput::getInstance(); } $text = $filter->clean($text, 'html'); } return $text; } } ``` ATTETION : some texts deleted for privacy.
2013/12/04
[ "https://Stackoverflow.com/questions/20378733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The [scope resolution operator](http://www.php.net/manual/en/language.oop5.paamayim-nekudotayim.php) (::) can only be used on a class referenced using a variable from PHP 5.3 -- you're using 5.2. You'd have to do `JHtmlSidebar::addEntry` or `JSubMenuHelper::addEntry`; you can't do `$class::addEntry`.
`JText::('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS')` is not calling a method. It should be: ``` JText::_('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS') ``` See [`JText`](http://docs.joomla.org/JText/).
20,378,733
I have building a web site but i have a error code and i couldnt fould a fix it Error > > Parse error: syntax error, unexpected T\_PAAMAYIM\_NEKUDOTAYIM in /home/eneskura/public\_html/administrator/components/com\_tz\_portfolio/helpers/tz\_portfolio.php on line 42 > > > line 42- ``` $class::addEntry(JText::('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS'), 'index.php?option=com_tz_portfolio&view=fieldsgroup', $vName == 'fieldsgroup'); ``` how i can i fix it? Site: eneskuray.com php 5.2.17 litespeed full php ``` <?php // No direct access defined('_JEXEC') or die; class TZ_PortfolioHelper { public static $extension = 'com_content'; /** * Configure the Linkbar. * * @param string $vName The name of the active view. * * @return void * @since 1.6 */ public static function addSubmenu($vName) { $class = 'JHtmlSidebar'; if(!COM_TZ_PORTFOLIO_JVERSION_COMPARE){ $class = 'JSubMenuHelper'; } $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS'), 'index.php?option=com_tz_portfolio&view=fieldsgroup', $vName == 'fieldsgroup'); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_FIELDS'), 'index.php?option=com_tz_portfolio&view=fields', $vName == 'fields' ); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_CATEGORIES'), 'index.php?option=com_tz_portfolio&view=categories', $vName == 'categories'); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_ARTICLES'), 'index.php?option=com_tz_portfolio&view=articles', $vName == 'articles' ); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_FEATURED_ARTICLES'), 'index.php?option=com_tz_portfolio&view=featured', $vName == 'featured' ); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_TAGS'), 'index.php?option=com_tz_portfolio&view=tags', $vName == 'tags'); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_USERS'), 'index.php?option=com_tz_portfolio&view=users', $vName == 'users'); } /** * Gets a list of the actions that can be performed. * * @param int The category ID. * @param int The article ID. * * @return JObject * @since 1.6 */ public static function getActions($categoryId = 0, $articleId = 0) { $user = JFactory::getUser(); $result = new JObject; if (empty($articleId) && empty($categoryId)) { $assetName = 'com_tz_portfolio'; } elseif (empty($articleId)) { $assetName = 'com_tz_portfolio.category.'.(int) $categoryId; } else { $assetName = 'com_tz_portfolio.article.'.(int) $articleId; } $actions = array( 'core.admin', 'core.manage', 'core.create', 'core.edit', 'core.edit.own', 'core.edit.state', 'core.delete' ); foreach ($actions as $action) { $result->set($action, $user->authorise($action, $assetName)); } return $result; } /** * Applies the content tag filters to arbitrary text as per settings for current user group * @param text The string to filter * @return string The filtered string */ public static function filterText($text) { // Filter settings $config = JComponentHelper::getParams('com_config'); $user = JFactory::getUser(); $userGroups = JAccess::getGroupsByUser($user->get('id')); $filters = $config->get('filters'); $blackListTags = array(); $blackListAttributes = array(); $customListTags = array(); $customListAttributes = array(); $whiteListTags = array(); $whiteListAttributes = array(); $noHtml = false; $whiteList = false; $blackList = false; $customList = false; $unfiltered = false; // Cycle through each of the user groups the user is in. // Remember they are included in the Public group as well. foreach ($userGroups as $groupId) { // May have added a group but not saved the filters. if (!isset($filters->$groupId)) { continue; } // Each group the user is in could have different filtering properties. $filterData = $filters->$groupId; $filterType = strtoupper($filterData->filter_type); if ($filterType == 'NH') { // Maximum HTML filtering. $noHtml = true; } elseif ($filterType == 'NONE') { // No HTML filtering. $unfiltered = true; } else { // Black, white or custom list. // Preprocess the tags and attributes. $tags = explode(',', $filterData->filter_tags); $attributes = explode(',', $filterData->filter_attributes); $tempTags = array(); $tempAttributes = array(); foreach ($tags as $tag) { $tag = trim($tag); if ($tag) { $tempTags[] = $tag; } } foreach ($attributes as $attribute) { $attribute = trim($attribute); if ($attribute) { $tempAttributes[] = $attribute; } } // Collect the black or white list tags and attributes. // Each lists is cummulative. if ($filterType == 'BL') { $blackList = true; $blackListTags = array_merge($blackListTags, $tempTags); $blackListAttributes = array_merge($blackListAttributes, $tempAttributes); } elseif ($filterType == 'CBL') { // Only set to true if Tags or Attributes were added if ($tempTags || $tempAttributes) { $customList = true; $customListTags = array_merge($customListTags, $tempTags); $customListAttributes = array_merge($customListAttributes, $tempAttributes); } } elseif ($filterType == 'WL') { $whiteList = true; $whiteListTags = array_merge($whiteListTags, $tempTags); $whiteListAttributes = array_merge($whiteListAttributes, $tempAttributes); } } } // Remove duplicates before processing (because the black list uses both sets of arrays). $blackListTags = array_unique($blackListTags); $blackListAttributes = array_unique($blackListAttributes); $customListTags = array_unique($customListTags); $customListAttributes = array_unique($customListAttributes); $whiteListTags = array_unique($whiteListTags); $whiteListAttributes = array_unique($whiteListAttributes); // Unfiltered assumes first priority. if ($unfiltered) { // Dont apply filtering. } else { // Custom blacklist precedes Default blacklist if ($customList) { $filter = JFilterInput::getInstance(array(), array(), 1, 1); // Override filter's default blacklist tags and attributes if ($customListTags) { $filter->tagBlacklist = $customListTags; } if ($customListAttributes) { $filter->attrBlacklist = $customListAttributes; } } // Black lists take third precedence. elseif ($blackList) { // Remove the white-listed attributes from the black-list. $filter = JFilterInput::getInstance( array_diff($blackListTags, $whiteListTags), // blacklisted tags array_diff($blackListAttributes, $whiteListAttributes), // blacklisted attributes 1, // blacklist tags 1 // blacklist attributes ); // Remove white listed tags from filter's default blacklist if ($whiteListTags) { $filter->tagBlacklist = array_diff($filter->tagBlacklist, $whiteListTags); } // Remove white listed attributes from filter's default blacklist if ($whiteListAttributes) { $filter->attrBlacklist = array_diff($filter->attrBlacklist); } } // White lists take fourth precedence. elseif ($whiteList) { $filter = JFilterInput::getInstance($whiteListTags, $whiteListAttributes, 0, 0, 0); // turn off xss auto clean } // No HTML takes last place. else { $filter = JFilterInput::getInstance(); } $text = $filter->clean($text, 'html'); } return $text; } } ``` ATTETION : some texts deleted for privacy.
2013/12/04
[ "https://Stackoverflow.com/questions/20378733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The [scope resolution operator](http://www.php.net/manual/en/language.oop5.paamayim-nekudotayim.php) (::) can only be used on a class referenced using a variable from PHP 5.3 -- you're using 5.2. You'd have to do `JHtmlSidebar::addEntry` or `JSubMenuHelper::addEntry`; you can't do `$class::addEntry`.
`T_PAAMAYIM_NEKUDOTAYIM` refers to the two colons in a row like this `::`. Looking at your code sample: ``` $class::addEntry( JText::('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS'), 'index.php?option=com_tz_portfolio&view=fieldsgroup', $vName == 'fieldsgroup'); ``` I believe the issue is with `JText::(`. As per [Joomla documentation](http://docs.joomla.org/JText/) that should be formatted with an underscore so it is `JText::_(` so your code would be: ``` $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS'), 'index.php?option=com_tz_portfolio&view=fieldsgroup', $vName == 'fieldsgroup'); ``` Not 100% clear on Joomla internals, but that underscore (`_`) is actually a function/method of some sort within the `JText` class. So when you were calling it as `JText::(` PHP choked because it had no idea what you were trying to do with `JText`. By adding that underscore (`_`), it will now actually call a function within a class & do what it has to do.
68,589,876
I have API endpoint /department/getManagersList?department\_name=IT which is returning this ``` { "status": "success", "managersList": [ { "id": "6103d29974535fac35286aff", "name": "axe deo", "role": "Associate React Developer" }, { "id": "6103d1e274535fac35286afe", "name": "aakash kumar", "role": "Vice President Engineering" }, { "id": "6103d36074535fac35286b0a", "name": "atanu paul", "role": "Senior Software Enginner" }, { "id": "6103d7c1f2bba5af7cad4083", "name": "sam winchester", "role": "Junior Node JS Developer" } ] } ``` now "sam Winchester" is a new user who just created his profile I want to exclude him or in a nutshell, remove the newly created user from this list. The purpose is to return the names of all the employees of the department excluding the newly created user so that the new user can choose his/her reporting manager. Any idea how to do this? This is the current code that is returning the above JSON object ``` adminController.getManagersList = async (req, res) => { try { var manager_list = []; var department_data = {}; var employees_list = []; var manager_details = {}; var department_name = req.query.department_name; if (isEmpty(department_name)) return res.status(400).json({ status: "failure", message: `Department name ${emptyField}`, }); department_data = await DepartmentData.findOne({ department_name: department_name, }) .populate("employees") .exec(); if (isEmpty(department_data)) return res .status(400) .json({ status: "failure", message: `Department ${dataNotFound}` }); employees_list = department_data.employees; employees_list.forEach((empList) => { let department_data = empList.department; department_data.forEach((depList) => { if (depList.name == department_name) { manager_details = {}; // * Making the object empty for next value manager_details.id = empList._id; manager_details.name = empList.full_name; manager_details.role = depList.role; manager_list.push(manager_details); } }); }); res.status(200).json({ status: "success", managersList: manager_list }); } catch (err) { console.log(err); res .status(500) .json({ status: "failure", message: "Internal Server Error" }); } }; ```
2021/07/30
[ "https://Stackoverflow.com/questions/68589876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15556024/" ]
To remove the last item from your array you could use: ``` const arr = [1,2,3]; arr.pop(); // arr -> [1,2] ```
Generally speaking you already answered your question here: > > The purpose is to return the names of all the employees of the department excluding the newly created user so that the new user can choose his/her reporting manager. > > > So that you need find all employees who do not have managers yet. I assume that you have relationship between managers and users as `one-to-many`, (one manager can have many employees). Not sure what database are you using, but should be something like this: ``` department_data = await DepartmentData.findOne({ department_name: department_name, }) .populate({ path: 'employees', match: { managerId: { $eq: null }}, }) .exec(); ``` also rename "getManagersList" to "getEmployeesList"
4,444,870
I recently just started to migrate over a CI application to Amazon's EC2 service. To test I set up a micro instance of ubuntu and a LAMP stack. PHP, MySQL, HTTPD are all working beautifully. The one issue i'm having now is that when I run my application I receive an error saying that my helpers won't load. The helpers in particular that aren't loading are the ones in subdirectories in the helpers directory ie: /var/www/system/application/helpers/subdirectory/foo\_helper.php The helpers are being autoloaded and in my autoload.php config file they are written like: ``` $autoload['helper'] = array('subdirectory/foo', 'foo2',...); ``` Has anyone run into this issue, or have any pointers on where I could go look in my configuration to resolve this? Thanks for the help!
2010/12/14
[ "https://Stackoverflow.com/questions/4444870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135881/" ]
I ran into the same issue while trying to install MySQL 5.5.15 in Lion using homebrew and resolved the issue with: ``` mysql_install_db --verbose --user=`whoami` --basedir="$(brew --prefix mysql)" --datadir=/usr/local/var/mysql --tmpdir=/tmp ``` and creating a the file ~/my.cnf with the content: ``` [mysqld] basedir=/usr/local/Cellar/mysql/5.5.15 datadir=/usr/local/var/mysql ``` basedir - should be your current MySQL instalation dir datadir - should be the location of MySQL data You can figure out that too location by watching the make command during the "brew install mysql" searching for something like this: ``` -DCMAKE_INSTALL_PREFIX=/usr/local/Cellar/mysql/5.5.15 -DMYSQL_DATADIR=/usr/local/var/mysql -DINSTALL_MANDIR=/usr/local/Cellar/mysql ``` Where DCMAKE\_INSTALL\_PREFIX = basedir and DMYSQL\_DATADIR = datadir
1. `brew postinstall mysql` 2. `delete document /opt/homebrew/var/mysql` 3. `brew postinstall mysql`
4,444,870
I recently just started to migrate over a CI application to Amazon's EC2 service. To test I set up a micro instance of ubuntu and a LAMP stack. PHP, MySQL, HTTPD are all working beautifully. The one issue i'm having now is that when I run my application I receive an error saying that my helpers won't load. The helpers in particular that aren't loading are the ones in subdirectories in the helpers directory ie: /var/www/system/application/helpers/subdirectory/foo\_helper.php The helpers are being autoloaded and in my autoload.php config file they are written like: ``` $autoload['helper'] = array('subdirectory/foo', 'foo2',...); ``` Has anyone run into this issue, or have any pointers on where I could go look in my configuration to resolve this? Thanks for the help!
2010/12/14
[ "https://Stackoverflow.com/questions/4444870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135881/" ]
I ran into this same problem when installing via homebrew. Make sure you run these commands (which are listed during install but easy to miss): ``` unset TMPDIR mysql_install_db ```
Nothing else really helped, but the following worked: ``` $ ps aux | grep mysql tagir 27260 0.0 1.0 3562356 175120 ?? S 2:52PM 0:00.42 mysqld --skip-grant-tables tagir 42704 0.0 0.0 2434840 784 s000 S+ 3:04PM 0:00.00 grep mysql $ kill 27260 # Careful! This might erase your existing data $ rm -rf /usr/local/var/mysql $ mysqld --initialize $ mysql.server start ```
4,444,870
I recently just started to migrate over a CI application to Amazon's EC2 service. To test I set up a micro instance of ubuntu and a LAMP stack. PHP, MySQL, HTTPD are all working beautifully. The one issue i'm having now is that when I run my application I receive an error saying that my helpers won't load. The helpers in particular that aren't loading are the ones in subdirectories in the helpers directory ie: /var/www/system/application/helpers/subdirectory/foo\_helper.php The helpers are being autoloaded and in my autoload.php config file they are written like: ``` $autoload['helper'] = array('subdirectory/foo', 'foo2',...); ``` Has anyone run into this issue, or have any pointers on where I could go look in my configuration to resolve this? Thanks for the help!
2010/12/14
[ "https://Stackoverflow.com/questions/4444870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135881/" ]
I ran into this same problem when installing via homebrew. Make sure you run these commands (which are listed during install but easy to miss): ``` unset TMPDIR mysql_install_db ```
I am adding this here because I encountered this problem several times after installing other software. MySQL was working fine for days, then suddenly I get this error. It seems to happen when I install something (eg. elasticsearch or Puma web server). The MySql permissions get reverted again (back to me, and not `_mysql`). No idea why. * MacOS Sierra * Homebrew 1.0.5-43-g41b2df8 (2016-10-02) * MySQL 5.7.15 So I have found that one cause of this is the permissions on the location where MySQL stores your databases, which by default is here: ``` /usr/local/var/mysql ``` If you look in that folder you will see a file ``` <your computer name>.err ``` If you look inside that file (`more` it or `cat` it) you will probably see this error: ``` [ERROR] InnoDB: The innodb_system data file 'ibdata1' must be writable ``` If so then you know it is a permissions issue. If you don't care, you can probably just run MySQL by just running `mysqld` (and leave that terminal open). If you do care: `ls -al /usr/local/var/mysql` you will notice that the permissions are probably all set to you (your user account). This means mysql cannot mount your databases when you run it using the homebrew shortcut `sudo mysql.server start` [even though you are using sudo to run in 'admin' mode]. So, change the permissions: ``` $ sudo chown -R _mysql /usr/local/var/mysql $ sudo chmod -R o+rwx /usr/local/var/mysql ``` Then it will work.
4,444,870
I recently just started to migrate over a CI application to Amazon's EC2 service. To test I set up a micro instance of ubuntu and a LAMP stack. PHP, MySQL, HTTPD are all working beautifully. The one issue i'm having now is that when I run my application I receive an error saying that my helpers won't load. The helpers in particular that aren't loading are the ones in subdirectories in the helpers directory ie: /var/www/system/application/helpers/subdirectory/foo\_helper.php The helpers are being autoloaded and in my autoload.php config file they are written like: ``` $autoload['helper'] = array('subdirectory/foo', 'foo2',...); ``` Has anyone run into this issue, or have any pointers on where I could go look in my configuration to resolve this? Thanks for the help!
2010/12/14
[ "https://Stackoverflow.com/questions/4444870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135881/" ]
Nothing else really helped, but the following worked: ``` $ ps aux | grep mysql tagir 27260 0.0 1.0 3562356 175120 ?? S 2:52PM 0:00.42 mysqld --skip-grant-tables tagir 42704 0.0 0.0 2434840 784 s000 S+ 3:04PM 0:00.00 grep mysql $ kill 27260 # Careful! This might erase your existing data $ rm -rf /usr/local/var/mysql $ mysqld --initialize $ mysql.server start ```
1. `brew postinstall mysql` 2. `delete document /opt/homebrew/var/mysql` 3. `brew postinstall mysql`
4,444,870
I recently just started to migrate over a CI application to Amazon's EC2 service. To test I set up a micro instance of ubuntu and a LAMP stack. PHP, MySQL, HTTPD are all working beautifully. The one issue i'm having now is that when I run my application I receive an error saying that my helpers won't load. The helpers in particular that aren't loading are the ones in subdirectories in the helpers directory ie: /var/www/system/application/helpers/subdirectory/foo\_helper.php The helpers are being autoloaded and in my autoload.php config file they are written like: ``` $autoload['helper'] = array('subdirectory/foo', 'foo2',...); ``` Has anyone run into this issue, or have any pointers on where I could go look in my configuration to resolve this? Thanks for the help!
2010/12/14
[ "https://Stackoverflow.com/questions/4444870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135881/" ]
These following two commands should solve your issue. ``` > unset TMPDIR > mysql_install_db --verbose --user=\`whoami\` --basedir="$(brew --prefix mysql)" --datadir=/usr/local/var/mysql --tmpdir=/tmp ```
1. `brew postinstall mysql` 2. `delete document /opt/homebrew/var/mysql` 3. `brew postinstall mysql`
4,444,870
I recently just started to migrate over a CI application to Amazon's EC2 service. To test I set up a micro instance of ubuntu and a LAMP stack. PHP, MySQL, HTTPD are all working beautifully. The one issue i'm having now is that when I run my application I receive an error saying that my helpers won't load. The helpers in particular that aren't loading are the ones in subdirectories in the helpers directory ie: /var/www/system/application/helpers/subdirectory/foo\_helper.php The helpers are being autoloaded and in my autoload.php config file they are written like: ``` $autoload['helper'] = array('subdirectory/foo', 'foo2',...); ``` Has anyone run into this issue, or have any pointers on where I could go look in my configuration to resolve this? Thanks for the help!
2010/12/14
[ "https://Stackoverflow.com/questions/4444870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135881/" ]
You probably need to ensure that you're running mysql as the `root` user -- otherwise it won't have permission to write the PID file (thus the error you're receiving). Try this: ``` sudo mysql.server start ``` You'll be prompted for your password. (this assumes that your user account has permissions to "sudo" -- which it should, unless it's setup as a restricted user account in OS X). This may not be the only issue -- but it should get you to the next step anyway.
1. `brew postinstall mysql` 2. `delete document /opt/homebrew/var/mysql` 3. `brew postinstall mysql`
4,444,870
I recently just started to migrate over a CI application to Amazon's EC2 service. To test I set up a micro instance of ubuntu and a LAMP stack. PHP, MySQL, HTTPD are all working beautifully. The one issue i'm having now is that when I run my application I receive an error saying that my helpers won't load. The helpers in particular that aren't loading are the ones in subdirectories in the helpers directory ie: /var/www/system/application/helpers/subdirectory/foo\_helper.php The helpers are being autoloaded and in my autoload.php config file they are written like: ``` $autoload['helper'] = array('subdirectory/foo', 'foo2',...); ``` Has anyone run into this issue, or have any pointers on where I could go look in my configuration to resolve this? Thanks for the help!
2010/12/14
[ "https://Stackoverflow.com/questions/4444870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135881/" ]
I ran into this same problem when installing via homebrew. Make sure you run these commands (which are listed during install but easy to miss): ``` unset TMPDIR mysql_install_db ```
It appears that for whatever reason I can't comment below Immendes above, but on 10.8.2 with mySQL 5.6.10, in addition to verifying the db\_install and adding the my.cnf, I also had to chown -R myusername /tmp/mysql.sock. It appears that allowing mySQL to run under the user (as apposed to root or www as I woudl do on linux) is not the best idea in this regard (though Homebrew could update the formula -- beyond my scope and time).
4,444,870
I recently just started to migrate over a CI application to Amazon's EC2 service. To test I set up a micro instance of ubuntu and a LAMP stack. PHP, MySQL, HTTPD are all working beautifully. The one issue i'm having now is that when I run my application I receive an error saying that my helpers won't load. The helpers in particular that aren't loading are the ones in subdirectories in the helpers directory ie: /var/www/system/application/helpers/subdirectory/foo\_helper.php The helpers are being autoloaded and in my autoload.php config file they are written like: ``` $autoload['helper'] = array('subdirectory/foo', 'foo2',...); ``` Has anyone run into this issue, or have any pointers on where I could go look in my configuration to resolve this? Thanks for the help!
2010/12/14
[ "https://Stackoverflow.com/questions/4444870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135881/" ]
I ran into this same problem when installing via homebrew. Make sure you run these commands (which are listed during install but easy to miss): ``` unset TMPDIR mysql_install_db ```
These following two commands should solve your issue. ``` > unset TMPDIR > mysql_install_db --verbose --user=\`whoami\` --basedir="$(brew --prefix mysql)" --datadir=/usr/local/var/mysql --tmpdir=/tmp ```
4,444,870
I recently just started to migrate over a CI application to Amazon's EC2 service. To test I set up a micro instance of ubuntu and a LAMP stack. PHP, MySQL, HTTPD are all working beautifully. The one issue i'm having now is that when I run my application I receive an error saying that my helpers won't load. The helpers in particular that aren't loading are the ones in subdirectories in the helpers directory ie: /var/www/system/application/helpers/subdirectory/foo\_helper.php The helpers are being autoloaded and in my autoload.php config file they are written like: ``` $autoload['helper'] = array('subdirectory/foo', 'foo2',...); ``` Has anyone run into this issue, or have any pointers on where I could go look in my configuration to resolve this? Thanks for the help!
2010/12/14
[ "https://Stackoverflow.com/questions/4444870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135881/" ]
You probably need to ensure that you're running mysql as the `root` user -- otherwise it won't have permission to write the PID file (thus the error you're receiving). Try this: ``` sudo mysql.server start ``` You'll be prompted for your password. (this assumes that your user account has permissions to "sudo" -- which it should, unless it's setup as a restricted user account in OS X). This may not be the only issue -- but it should get you to the next step anyway.
Nothing else really helped, but the following worked: ``` $ ps aux | grep mysql tagir 27260 0.0 1.0 3562356 175120 ?? S 2:52PM 0:00.42 mysqld --skip-grant-tables tagir 42704 0.0 0.0 2434840 784 s000 S+ 3:04PM 0:00.00 grep mysql $ kill 27260 # Careful! This might erase your existing data $ rm -rf /usr/local/var/mysql $ mysqld --initialize $ mysql.server start ```
4,444,870
I recently just started to migrate over a CI application to Amazon's EC2 service. To test I set up a micro instance of ubuntu and a LAMP stack. PHP, MySQL, HTTPD are all working beautifully. The one issue i'm having now is that when I run my application I receive an error saying that my helpers won't load. The helpers in particular that aren't loading are the ones in subdirectories in the helpers directory ie: /var/www/system/application/helpers/subdirectory/foo\_helper.php The helpers are being autoloaded and in my autoload.php config file they are written like: ``` $autoload['helper'] = array('subdirectory/foo', 'foo2',...); ``` Has anyone run into this issue, or have any pointers on where I could go look in my configuration to resolve this? Thanks for the help!
2010/12/14
[ "https://Stackoverflow.com/questions/4444870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135881/" ]
I ran into this same problem when installing via homebrew. Make sure you run these commands (which are listed during install but easy to miss): ``` unset TMPDIR mysql_install_db ```
I ran into the same issue while trying to install MySQL 5.5.15 in Lion using homebrew and resolved the issue with: ``` mysql_install_db --verbose --user=`whoami` --basedir="$(brew --prefix mysql)" --datadir=/usr/local/var/mysql --tmpdir=/tmp ``` and creating a the file ~/my.cnf with the content: ``` [mysqld] basedir=/usr/local/Cellar/mysql/5.5.15 datadir=/usr/local/var/mysql ``` basedir - should be your current MySQL instalation dir datadir - should be the location of MySQL data You can figure out that too location by watching the make command during the "brew install mysql" searching for something like this: ``` -DCMAKE_INSTALL_PREFIX=/usr/local/Cellar/mysql/5.5.15 -DMYSQL_DATADIR=/usr/local/var/mysql -DINSTALL_MANDIR=/usr/local/Cellar/mysql ``` Where DCMAKE\_INSTALL\_PREFIX = basedir and DMYSQL\_DATADIR = datadir
17,654,302
Range slider ``` $("#slider-range").slider({ range: true, min: 0, max: 420, values: [0, 420], slide: slideTime, change: toSpin }); ``` and text fields ``` $('#min').val(ui.values[ 0 ]); $('#max').val(ui.values[ 1 ]); ``` and I would like to call a function when the value of each field changes, like ``` $('input').on('input propertychange', function() { ``` but since the mouse is never in the field it won't work. Maybe local storage is the answer, but before getting into it I thought I would see if I can just bind the slider handles instead. I can use #slider-range like this: ``` var $leftslider = $("#slider-range"); $leftslider.bind("mouseup", sliderHandler); function sliderHandler() { ``` but I guess I would need to bind mouseups to each handle, left and right separately, to call a different function for each. So, after the slider changes #min, the left handle mouseup would call a function that uses the value of #min. Variations on this theme ``` $(#slider-range).children('.ui-slider-handle').first().offset(); ``` seem not to work.
2013/07/15
[ "https://Stackoverflow.com/questions/17654302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1877124/" ]
Sitecore confirmed that they can reproduce the issue. When setting dynamicCompressionBeforeCache="true", the encoding does not work correctly for some reason. One solution is to remove this setting. After applying dynamicCompressionBeforeCache="false" it works fine.
You should probably enable gzip in your web.config ``` <system.webServer> <httpCompression directory="%SystemDrive%\inetpub\ temp\IIS Temporary Compressed Files"> <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/> <dynamicTypes> <add mimeType="text/*" enabled="true"/> <add mimeType="message/*" enabled="true"/> <add mimeType="application/javascript" enabled="true"/> <add mimeType="*/*" enabled="false"/> </dynamicTypes> <staticTypes> <add mimeType="text/*" enabled="true"/> <add mimeType="message/*" enabled="true"/> <add mimeType="application/javascript" enabled="true"/> <add mimeType="*/*" enabled="false"/> </staticTypes> </httpCompression> <urlCompression doStaticCompression="true" doDynamicCompression="true"/> </system.webServer> ``` There are a few more tricks here [Setting the gzip compression in asp.net](https://stackoverflow.com/questions/1324481/setting-the-gzip-compression-in-asp-net)
9,119,572
I am using bootstrap-sass, formtastic-bootstrap, rails 3.2, and ruby 1.9.3p0 on a new project. I want create a multi-column form and multi-column media grid for the list of products. Code below. I used two separate methods. The first is using the row < .span for the form and the second is by adding my own multi-column css code to the media-grid and that's not working either. Help? **First method on form:** ``` <%= semantic_form_for @product do |f| %> <%= f.inputs do %> <div class="row"> <div class="span8"> <%= f.input :name %> <%= ... %> </div> </div> <div class="row"> <div class="span8"> <%= f.input :description %> <%= ... %> </div> </div> <% end %> <% end %> ``` **Second method on media-grid:** ``` <div class="row multi-column"> <ul class="media-grid span4"> <% @products.each do |prod| %> <li class="media-grid"> <div class="well"> <%= link_to prod.name, prod, :class => "strong" %></br> $<%= prod.price %></br> <%= prod.available ? "Available" : "Out of Stock" %> </div> </li> <% end %> </ul> </div> ``` Here's the code for the multi-column css: ``` .multi-column { -moz-column-count: 3; -webkit-column-count: 3; column-count: 3;} ``` Help...
2012/02/02
[ "https://Stackoverflow.com/questions/9119572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/793116/" ]
Do you have a `float:left` on anything in there? I was just playing around with a multi-column thing in Twitter Bootstrap today and noticed that that broke it.
I'm currently working on a helper to do this for rails, im extracting from the following code: ``` - (0..items.size - 1).each do |i| - if i % 3 == 0 \<div class="row"> =render "items/show_small", item: items.at(i) - if i % 3 == 2 || i == items.size - 1 \</div> ``` and ``` .span4.show-small ``` i think i did my mods correct there...
43,540,159
I am trying to build an executable out of my .py script using Pyinstaller. The problem is that it builds it using Python 2.7 instead of Python 3.5, so my executable won't even run. ``` cali@californiki-pc ~/Desktop $ pyinstaller --onefile Vocabulary.py 25 INFO: PyInstaller: 3.2.1 25 INFO: Python: 2.7.12 26 INFO: Platform: Linux-4.4.0-72-generic-x86_64-with-LinuxMint-18.1-serena 26 INFO: wrote /home/cali/Desktop/Vocabulary.spec 31 INFO: UPX is not available. 32 INFO: Extending PYTHONPATH with paths ['/home/cali/Desktop', '/home/cali/Desktop'] 32 INFO: checking Analysis 33 INFO: Building Analysis because out00-Analysis.toc is non existent 33 INFO: Initializing module dependency graph... 34 INFO: Initializing module graph hooks... 139 INFO: running Analysis out00-Analysis.toc 160 INFO: Caching module hooks... 164 INFO: Analyzing /home/cali/Desktop/Vocabulary.py 246 INFO: Processing pre-safe import module hook _xmlplus 1991 INFO: Processing pre-find module path hook distutils 2209 INFO: Loading module hooks... 2209 INFO: Loading module hook "hook-distutils.py"... 2210 INFO: Loading module hook "hook-xml.py"... 2959 INFO: Loading module hook "hook-httplib.py"... 2960 INFO: Loading module hook "hook-encodings.py"... 3427 INFO: Looking for ctypes DLLs 3428 INFO: Analyzing run-time hooks ... 3435 INFO: Looking for dynamic libraries 3663 INFO: Looking for eggs 3663 INFO: Python library not in binary depedencies. Doing additional searching... 3707 INFO: Using Python library /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0 3710 INFO: Warnings written to /home/cali/Desktop/build/Vocabulary/warnVocabulary.txt 3768 INFO: checking PYZ 3768 INFO: Building PYZ because out00-PYZ.toc is non existent 3768 INFO: Building PYZ (ZlibArchive) /home/cali/Desktop/build/Vocabulary/out00-PYZ.pyz 4122 INFO: Building PYZ (ZlibArchive) /home/cali/Desktop/build/Vocabulary/out00-PYZ.pyz completed successfully. 4172 INFO: checking PKG 4172 INFO: Building PKG because out00-PKG.toc is non existent 4172 INFO: Building PKG (CArchive) out00-PKG.pkg 7322 INFO: Building PKG (CArchive) out00-PKG.pkg completed successfully. 7336 INFO: Bootloader /usr/local/lib/python2.7/dist-packages/PyInstaller/bootloader/Linux-64bit/run 7336 INFO: checking EXE 7336 INFO: Building EXE because out00-EXE.toc is non existent 7336 INFO: Building EXE from out00-EXE.toc 7337 INFO: Appending archive to ELF section in EXE /home/cali/Desktop/dist/Vocabulary 7352 INFO: Building EXE from out00-EXE.toc completed successfully. ``` How can I overcome the issue? @EDIT: I tried to install Pyinstaller using `pip3 install pyinstaller` as Claudio suggested, but I am getting: ``` cali@californiki-pc ~/Desktop $ pip3 install pyinstaller Collecting pyinstaller Using cached PyInstaller-3.2.1.tar.bz2 Collecting setuptools (from pyinstaller) Using cached setuptools-35.0.1-py2.py3-none-any.whl Collecting appdirs>=1.4.0 (from setuptools->pyinstaller) Using cached appdirs-1.4.3-py2.py3-none-any.whl Collecting packaging>=16.8 (from setuptools->pyinstaller) Using cached packaging-16.8-py2.py3-none-any.whl Collecting six>=1.6.0 (from setuptools->pyinstaller) Using cached six-1.10.0-py2.py3-none-any.whl Collecting pyparsing (from packaging>=16.8->setuptools->pyinstaller) Using cached pyparsing-2.2.0-py2.py3-none-any.whl Building wheels for collected packages: pyinstaller Running setup.py bdist_wheel for pyinstaller ... error Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-42qpk7iy/pyinstaller/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /tmp/tmpmmn5007ppip-wheel- --python-tag cp35: usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: -c --help [cmd1 cmd2 ...] or: -c --help-commands or: -c cmd --help error: invalid command 'bdist_wheel' ---------------------------------------- Failed building wheel for pyinstaller Running setup.py clean for pyinstaller Failed to build pyinstaller Installing collected packages: appdirs, six, pyparsing, packaging, setuptools, pyinstaller Running setup.py install for pyinstaller ... done Successfully installed appdirs-1.4.3 packaging-16.8 pyinstaller-3.2.1 pyparsing-2.2.0 setuptools-35.0.1 six-1.10.0 You are using pip version 8.1.1, however version 9.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. ```
2017/04/21
[ "https://Stackoverflow.com/questions/43540159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
To overcome the problem you face install PyInstaller using: > > pip3 install pyinstaller > > > Then take care that you run the right one (there will then be two of them in different locations, one in the path of Python2.7 modules and one in the path of Python3.5 modules) Just installed PyInstaller for Python 3.5 on my machine: ``` $ pip3 install pyinstaller Collecting pyinstaller Collecting setuptools (from pyinstaller) Using cached setuptools-35.0.1-py2.py3-none-any.whl Collecting six>=1.6.0 (from setuptools->pyinstaller) Using cached six-1.10.0-py2.py3-none-any.whl Collecting appdirs>=1.4.0 (from setuptools->pyinstaller) Using cached appdirs-1.4.3-py2.py3-none-any.whl Collecting packaging>=16.8 (from setuptools->pyinstaller) Using cached packaging-16.8-py2.py3-none-any.whl Collecting pyparsing (from packaging>=16.8->setuptools->pyinstaller) Using cached pyparsing-2.2.0-py2.py3-none-any.whl Installing collected packages: six, appdirs, pyparsing, packaging, setuptools, pyinstaller Successfully installed appdirs-1.4.3 packaging-16.8 pyinstaller-3.2.1 pyparsing-2.0.3 setuptools-20.7.0 six-1.10.0 ``` It installs without problems ... Hmmm ... Try: ``` sudo -H pip3 install setuptools --upgrade ``` (see for more [here](https://stackoverflow.com/questions/34819221/why-is-python-setup-py-saying-invalid-command-bdist-wheel-on-travis-ci) - you are not alone with this problem)
Just set an option -upx-dir in pyinstaller specifying your path for python 3.5. It can be the virtual environment too. For instance: ``` pyinstaller --upx-dir="$HOME/virtual-envs/<your-virtual-env>/lib/python3.5/site-packages/" <your-script>.py' ```
43,540,159
I am trying to build an executable out of my .py script using Pyinstaller. The problem is that it builds it using Python 2.7 instead of Python 3.5, so my executable won't even run. ``` cali@californiki-pc ~/Desktop $ pyinstaller --onefile Vocabulary.py 25 INFO: PyInstaller: 3.2.1 25 INFO: Python: 2.7.12 26 INFO: Platform: Linux-4.4.0-72-generic-x86_64-with-LinuxMint-18.1-serena 26 INFO: wrote /home/cali/Desktop/Vocabulary.spec 31 INFO: UPX is not available. 32 INFO: Extending PYTHONPATH with paths ['/home/cali/Desktop', '/home/cali/Desktop'] 32 INFO: checking Analysis 33 INFO: Building Analysis because out00-Analysis.toc is non existent 33 INFO: Initializing module dependency graph... 34 INFO: Initializing module graph hooks... 139 INFO: running Analysis out00-Analysis.toc 160 INFO: Caching module hooks... 164 INFO: Analyzing /home/cali/Desktop/Vocabulary.py 246 INFO: Processing pre-safe import module hook _xmlplus 1991 INFO: Processing pre-find module path hook distutils 2209 INFO: Loading module hooks... 2209 INFO: Loading module hook "hook-distutils.py"... 2210 INFO: Loading module hook "hook-xml.py"... 2959 INFO: Loading module hook "hook-httplib.py"... 2960 INFO: Loading module hook "hook-encodings.py"... 3427 INFO: Looking for ctypes DLLs 3428 INFO: Analyzing run-time hooks ... 3435 INFO: Looking for dynamic libraries 3663 INFO: Looking for eggs 3663 INFO: Python library not in binary depedencies. Doing additional searching... 3707 INFO: Using Python library /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0 3710 INFO: Warnings written to /home/cali/Desktop/build/Vocabulary/warnVocabulary.txt 3768 INFO: checking PYZ 3768 INFO: Building PYZ because out00-PYZ.toc is non existent 3768 INFO: Building PYZ (ZlibArchive) /home/cali/Desktop/build/Vocabulary/out00-PYZ.pyz 4122 INFO: Building PYZ (ZlibArchive) /home/cali/Desktop/build/Vocabulary/out00-PYZ.pyz completed successfully. 4172 INFO: checking PKG 4172 INFO: Building PKG because out00-PKG.toc is non existent 4172 INFO: Building PKG (CArchive) out00-PKG.pkg 7322 INFO: Building PKG (CArchive) out00-PKG.pkg completed successfully. 7336 INFO: Bootloader /usr/local/lib/python2.7/dist-packages/PyInstaller/bootloader/Linux-64bit/run 7336 INFO: checking EXE 7336 INFO: Building EXE because out00-EXE.toc is non existent 7336 INFO: Building EXE from out00-EXE.toc 7337 INFO: Appending archive to ELF section in EXE /home/cali/Desktop/dist/Vocabulary 7352 INFO: Building EXE from out00-EXE.toc completed successfully. ``` How can I overcome the issue? @EDIT: I tried to install Pyinstaller using `pip3 install pyinstaller` as Claudio suggested, but I am getting: ``` cali@californiki-pc ~/Desktop $ pip3 install pyinstaller Collecting pyinstaller Using cached PyInstaller-3.2.1.tar.bz2 Collecting setuptools (from pyinstaller) Using cached setuptools-35.0.1-py2.py3-none-any.whl Collecting appdirs>=1.4.0 (from setuptools->pyinstaller) Using cached appdirs-1.4.3-py2.py3-none-any.whl Collecting packaging>=16.8 (from setuptools->pyinstaller) Using cached packaging-16.8-py2.py3-none-any.whl Collecting six>=1.6.0 (from setuptools->pyinstaller) Using cached six-1.10.0-py2.py3-none-any.whl Collecting pyparsing (from packaging>=16.8->setuptools->pyinstaller) Using cached pyparsing-2.2.0-py2.py3-none-any.whl Building wheels for collected packages: pyinstaller Running setup.py bdist_wheel for pyinstaller ... error Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-42qpk7iy/pyinstaller/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /tmp/tmpmmn5007ppip-wheel- --python-tag cp35: usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: -c --help [cmd1 cmd2 ...] or: -c --help-commands or: -c cmd --help error: invalid command 'bdist_wheel' ---------------------------------------- Failed building wheel for pyinstaller Running setup.py clean for pyinstaller Failed to build pyinstaller Installing collected packages: appdirs, six, pyparsing, packaging, setuptools, pyinstaller Running setup.py install for pyinstaller ... done Successfully installed appdirs-1.4.3 packaging-16.8 pyinstaller-3.2.1 pyparsing-2.2.0 setuptools-35.0.1 six-1.10.0 You are using pip version 8.1.1, however version 9.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. ```
2017/04/21
[ "https://Stackoverflow.com/questions/43540159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Try: ``` py -3.5 -m PyInstaller Vocabulary.py --onefile ``` I think it is case sensitive
Just set an option -upx-dir in pyinstaller specifying your path for python 3.5. It can be the virtual environment too. For instance: ``` pyinstaller --upx-dir="$HOME/virtual-envs/<your-virtual-env>/lib/python3.5/site-packages/" <your-script>.py' ```
47,965,797
I am using a program called [`SlideSort`](https://github.com/iskana/SlideSort), which does not compile anymore on a recent Debian system using GCC 6.3.0. Instead, it throws the following error: ``` mstree.cpp:228:11: error: no match for ‘operator==’ (operand types are ‘std::ofstream {aka std::basic_ofstream<char>}’ and ‘long int’) if(dFile==NULL){ ^ ``` Not being a C programmer, I tried to bypass the problem by gently telling the compiler that the code is old; in my understanding this is roughly what GCC's option `-std=c++98` does. (See in GitHub's [issue tracker](https://github.com/iskana/SlideSort/issues/1) for the patch to the Makefile). Then the code compiles. but it segfaults in some corner cases (Test data and command available in GitHub's [issue tracker](https://github.com/iskana/SlideSort/issues/1)). The same test command works fine when the program is compiled with GCC 4.9.4. Thus, passing `-std=c++98` to GCC was either not enough or a wrong idea altogether. Is there an alternative to either compile on an old system or updated the code to the latest standards (which I can not do by myself) ?
2017/12/25
[ "https://Stackoverflow.com/questions/47965797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309786/" ]
I do not know why this code ever worked. In no version of the C++ standard is a scalar stream object comparable to an integer *or* to `nullptr_t`. That being said, your question is not how to fix the code you've found but how to bypass the error. **I do not recommend doing what I'm about to say here in production code.** It's a hack, and it's only designed to get an unusual library like this working. The `==` operator can be defined outside of any class, as a standalone function. The library you're using compares `std::ofstream` to `long int`. Let's make that comparison valid. ``` bool operator==(const std::ofstream&, long int) { return false; } ``` Now your code will compile. But it will probably run incorrectly. You could try making the comparison smarter by having it check whether the `std::ofstream` is truthy. ``` bool operator==(const std::ofstream& out, long int n) { return (bool)out == (bool)n; } ``` Now it's a bit smarter. But there's no silver bullet here. The code you were given is *not working and not standard C++*, so there's no fullproof way to get it working without changing the actual library code. So my suggestion is to fork the repository and fix the broken line of code yourself.
Without knowing the rest of the code, you can just try to rephrase that line such as: if(!dFile) See what happens next.
47,965,797
I am using a program called [`SlideSort`](https://github.com/iskana/SlideSort), which does not compile anymore on a recent Debian system using GCC 6.3.0. Instead, it throws the following error: ``` mstree.cpp:228:11: error: no match for ‘operator==’ (operand types are ‘std::ofstream {aka std::basic_ofstream<char>}’ and ‘long int’) if(dFile==NULL){ ^ ``` Not being a C programmer, I tried to bypass the problem by gently telling the compiler that the code is old; in my understanding this is roughly what GCC's option `-std=c++98` does. (See in GitHub's [issue tracker](https://github.com/iskana/SlideSort/issues/1) for the patch to the Makefile). Then the code compiles. but it segfaults in some corner cases (Test data and command available in GitHub's [issue tracker](https://github.com/iskana/SlideSort/issues/1)). The same test command works fine when the program is compiled with GCC 4.9.4. Thus, passing `-std=c++98` to GCC was either not enough or a wrong idea altogether. Is there an alternative to either compile on an old system or updated the code to the latest standards (which I can not do by myself) ?
2017/12/25
[ "https://Stackoverflow.com/questions/47965797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309786/" ]
My guess is this (`if(dFile==NULL){`) if condition is trying to check whether a file was open successfully for writing, if so you use function `is_open` which is available in c++. So simply replace the condition by `if (dFile.is_open())`. This should do the trick.
Without knowing the rest of the code, you can just try to rephrase that line such as: if(!dFile) See what happens next.
47,965,797
I am using a program called [`SlideSort`](https://github.com/iskana/SlideSort), which does not compile anymore on a recent Debian system using GCC 6.3.0. Instead, it throws the following error: ``` mstree.cpp:228:11: error: no match for ‘operator==’ (operand types are ‘std::ofstream {aka std::basic_ofstream<char>}’ and ‘long int’) if(dFile==NULL){ ^ ``` Not being a C programmer, I tried to bypass the problem by gently telling the compiler that the code is old; in my understanding this is roughly what GCC's option `-std=c++98` does. (See in GitHub's [issue tracker](https://github.com/iskana/SlideSort/issues/1) for the patch to the Makefile). Then the code compiles. but it segfaults in some corner cases (Test data and command available in GitHub's [issue tracker](https://github.com/iskana/SlideSort/issues/1)). The same test command works fine when the program is compiled with GCC 4.9.4. Thus, passing `-std=c++98` to GCC was either not enough or a wrong idea altogether. Is there an alternative to either compile on an old system or updated the code to the latest standards (which I can not do by myself) ?
2017/12/25
[ "https://Stackoverflow.com/questions/47965797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309786/" ]
In C++ 98 the streams used to have an `operator void*()` to check the stream state. It returned a null pointer when the stream was in an error state. Turned out that this implicit conversion caused some unexpected results when accidentally invoked in odd places. So in C++11, which gained explicit operators, it was turned into an [`explicit operator bool()`](http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool) instead. This returns `true` for a good state and `false` when the stream is in a failed state. Being `explicit` it can also only be used in places where a `bool` is expected. This removes most of the unexpected conversions from the old operator. So `if(dFile==NULL)`, testing for a non-good state of the stream, is now written `if (!dFile)`. And actually, the tests `if (dfile)` (good state) and `if (!dFile)` (non-good state) have always worked. The comparison against `NULL` has never been required, it just happened to work when the operator returned a `void*`.
Without knowing the rest of the code, you can just try to rephrase that line such as: if(!dFile) See what happens next.
47,965,797
I am using a program called [`SlideSort`](https://github.com/iskana/SlideSort), which does not compile anymore on a recent Debian system using GCC 6.3.0. Instead, it throws the following error: ``` mstree.cpp:228:11: error: no match for ‘operator==’ (operand types are ‘std::ofstream {aka std::basic_ofstream<char>}’ and ‘long int’) if(dFile==NULL){ ^ ``` Not being a C programmer, I tried to bypass the problem by gently telling the compiler that the code is old; in my understanding this is roughly what GCC's option `-std=c++98` does. (See in GitHub's [issue tracker](https://github.com/iskana/SlideSort/issues/1) for the patch to the Makefile). Then the code compiles. but it segfaults in some corner cases (Test data and command available in GitHub's [issue tracker](https://github.com/iskana/SlideSort/issues/1)). The same test command works fine when the program is compiled with GCC 4.9.4. Thus, passing `-std=c++98` to GCC was either not enough or a wrong idea altogether. Is there an alternative to either compile on an old system or updated the code to the latest standards (which I can not do by myself) ?
2017/12/25
[ "https://Stackoverflow.com/questions/47965797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309786/" ]
In C++ 98 the streams used to have an `operator void*()` to check the stream state. It returned a null pointer when the stream was in an error state. Turned out that this implicit conversion caused some unexpected results when accidentally invoked in odd places. So in C++11, which gained explicit operators, it was turned into an [`explicit operator bool()`](http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool) instead. This returns `true` for a good state and `false` when the stream is in a failed state. Being `explicit` it can also only be used in places where a `bool` is expected. This removes most of the unexpected conversions from the old operator. So `if(dFile==NULL)`, testing for a non-good state of the stream, is now written `if (!dFile)`. And actually, the tests `if (dfile)` (good state) and `if (!dFile)` (non-good state) have always worked. The comparison against `NULL` has never been required, it just happened to work when the operator returned a `void*`.
I do not know why this code ever worked. In no version of the C++ standard is a scalar stream object comparable to an integer *or* to `nullptr_t`. That being said, your question is not how to fix the code you've found but how to bypass the error. **I do not recommend doing what I'm about to say here in production code.** It's a hack, and it's only designed to get an unusual library like this working. The `==` operator can be defined outside of any class, as a standalone function. The library you're using compares `std::ofstream` to `long int`. Let's make that comparison valid. ``` bool operator==(const std::ofstream&, long int) { return false; } ``` Now your code will compile. But it will probably run incorrectly. You could try making the comparison smarter by having it check whether the `std::ofstream` is truthy. ``` bool operator==(const std::ofstream& out, long int n) { return (bool)out == (bool)n; } ``` Now it's a bit smarter. But there's no silver bullet here. The code you were given is *not working and not standard C++*, so there's no fullproof way to get it working without changing the actual library code. So my suggestion is to fork the repository and fix the broken line of code yourself.
47,965,797
I am using a program called [`SlideSort`](https://github.com/iskana/SlideSort), which does not compile anymore on a recent Debian system using GCC 6.3.0. Instead, it throws the following error: ``` mstree.cpp:228:11: error: no match for ‘operator==’ (operand types are ‘std::ofstream {aka std::basic_ofstream<char>}’ and ‘long int’) if(dFile==NULL){ ^ ``` Not being a C programmer, I tried to bypass the problem by gently telling the compiler that the code is old; in my understanding this is roughly what GCC's option `-std=c++98` does. (See in GitHub's [issue tracker](https://github.com/iskana/SlideSort/issues/1) for the patch to the Makefile). Then the code compiles. but it segfaults in some corner cases (Test data and command available in GitHub's [issue tracker](https://github.com/iskana/SlideSort/issues/1)). The same test command works fine when the program is compiled with GCC 4.9.4. Thus, passing `-std=c++98` to GCC was either not enough or a wrong idea altogether. Is there an alternative to either compile on an old system or updated the code to the latest standards (which I can not do by myself) ?
2017/12/25
[ "https://Stackoverflow.com/questions/47965797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309786/" ]
In C++ 98 the streams used to have an `operator void*()` to check the stream state. It returned a null pointer when the stream was in an error state. Turned out that this implicit conversion caused some unexpected results when accidentally invoked in odd places. So in C++11, which gained explicit operators, it was turned into an [`explicit operator bool()`](http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool) instead. This returns `true` for a good state and `false` when the stream is in a failed state. Being `explicit` it can also only be used in places where a `bool` is expected. This removes most of the unexpected conversions from the old operator. So `if(dFile==NULL)`, testing for a non-good state of the stream, is now written `if (!dFile)`. And actually, the tests `if (dfile)` (good state) and `if (!dFile)` (non-good state) have always worked. The comparison against `NULL` has never been required, it just happened to work when the operator returned a `void*`.
My guess is this (`if(dFile==NULL){`) if condition is trying to check whether a file was open successfully for writing, if so you use function `is_open` which is available in c++. So simply replace the condition by `if (dFile.is_open())`. This should do the trick.
3,698,733
> > **Theorem.** If two figures are similar and have the same orientation then there exists a homothecy that takes one of them into the other. > > > I see this result is being used pretty often in problems involving homothecy, but I don't know how to prove it. I know the reciprocal is true. If we have two figures and there exists a homothecy that takes one into the other, then the figures are similar and have the same orientation. Please help me with a proof of the theorem. I am a beginner in homothecy.
2020/05/30
[ "https://math.stackexchange.com/questions/3698733", "https://math.stackexchange.com", "https://math.stackexchange.com/users/463062/" ]
Let's assume that the two figures aren't congruent (the "center" of the homothety will be at infinity). Let's call the corresponding points on the two figures $A$ and $A'$. Firstly, let's prove the theorem is true for triangles. > > **Theorem:** If two triangles $ABC$ and $A'B'C'$ are similar with ratio $r$ with the same orientation, then there is a homothety from one to the other. > > > **Proof:** [![enter image description here](https://i.stack.imgur.com/B5rgp.png)](https://i.stack.imgur.com/B5rgp.png) Let $P$ be the intersection of $AA'$ and $BB'$, and consider the homothety $\varphi$ sending $A\to A'$ and $B\to B'$ (because $AB||A'B',\triangle PAB\sim \triangle PA'B'$ so the ratios $$\frac{PA}{PA'}=\frac{PB}{PB'}$$ are equal, and thus such a homothety exists. Let's consider where $\varphi(C)$ is. Because $\varphi$ sends $A\to A'$ and $AC||AC'$, we know that $\varphi(C)$ lies on ray $A'C'$. How far along this ray? Well, we know that $A'B'C'=rABC$ is the scaling up factor, and thus $C'$ lies at distance $rAC$ from $A'$. However, we also know that $\varphi$ takes $AB$ to $A'B'$ so $\varphi$ also scales everything up by $r$. Hence, $$|\varphi(AC)|=r|AC|=|A'C'|$$ and thus $$C\xrightarrow{\;\;\;\varphi\;\;\;}C'\;\;\square$$ How does this help with the general case? Well, consider two similar figures $\mathcal F$ and $\mathcal F'$. If each of these is a single point, then obviously there's a homothety between them. Otherwise, fix any $A,B\in\mathcal F$, find the corresponding $A',B'\in\mathcal F'$, and consider defining $P,\varphi$ as before. Then for any other $C\in\mathcal F$, we know by the triangle theorem that $\varphi(C)=C'$, the corresponding point on $\mathcal F'$. Hence the two figures are related by the homothety $\varphi$ centered at $P$.
You can just join two pairs of corresponding points. The obtained lines meet at the center of homothety. If they are parallel, your center is located at infinity.
3,153,400
if all Styles and Converters are stored in shared resource dictionary file (styles.xaml), and this file is used from various windows. Is it possible, to pass a parameter to that file, and propagate that parameter to the converters? I am looking for a way to pass a *"origin"* type parameter, so that the converters could be aware which place they are being used from? Just a hint of which window/grid is using the converter at the moment..
2010/06/30
[ "https://Stackoverflow.com/questions/3153400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349100/" ]
It doesn't make a difference in this case, because + is a special case that can apply to any number of arguments. Reduce is a way to apply a function that expects a fixed number of arguments (2) to an arbitrarily long list of arguments.
A bit late, but... In this case, there is not a big difference. But in general they are not equivalent. Further more reduce can be more performant. Why? reduce checks if a collection or type implements [IReduced](https://github.com/clojure/clojure/blob/clojure-1.10.1/src/clj/clojure/core.clj#L6810) interface. That means a type knows how provide its values to the reducing function in the most performant why. reduce can be stopped prematurely by returning a Reduced value. Apply on the other hand, is invoked by [applyToHelper](https://github.com/clojure/clojure/blob/38bafca9e76cd6625d8dce5fb6d16b87845c8b9d/src/jvm/clojure/lang/AFn.java#L147). Which dispatches to the right arity by counting the args, unpacking the values from the collection. Is it a big performance impact? Probably not. My opinion is as others already pointed out. Use reduce if you want to semantically "reduce" a collection to a single value. Otherwise use apply.
3,153,400
if all Styles and Converters are stored in shared resource dictionary file (styles.xaml), and this file is used from various windows. Is it possible, to pass a parameter to that file, and propagate that parameter to the converters? I am looking for a way to pass a *"origin"* type parameter, so that the converters could be aware which place they are being used from? Just a hint of which window/grid is using the converter at the moment..
2010/06/30
[ "https://Stackoverflow.com/questions/3153400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349100/" ]
`reduce` and `apply` are of course only equivalent (in terms of the ultimate result returned) for associative functions which need to see all their arguments in the variable-arity case. When they are result-wise equivalent, I'd say that `apply` is always perfectly idiomatic, while `reduce` is equivalent -- and might shave off a fraction of a blink of an eye -- in a lot of the common cases. What follows is my rationale for believing this. `+` is itself implemented in terms of `reduce` for the variable-arity case (more than 2 arguments). Indeed, this seems like an immensely sensible "default" way to go for any variable-arity, associative function: `reduce` has the potential to perform some optimisations to speed things up -- perhaps through something like `internal-reduce`, a 1.2 novelty recently disabled in master, but hopefully to be reintroduced in the future -- which it would be silly to replicate in every function which might benefit from them in the vararg case. In such common cases, `apply` will just add a little overhead. (Note it's nothing to be really worried about.) On the other hand, a complex function might take advantage of some optimisation opportunities which aren't general enough to be built into `reduce`; then `apply` would let you take advantage of those while `reduce` might actually slow you down. A good example of the latter scenario occuring in practice is provided by `str`: it uses a `StringBuilder` internally and will benefit significantly from the use of `apply` rather than `reduce`. So, I'd say use `apply` when in doubt; and if you happen to know that it's not buying you anything over `reduce` (and that this is unlikely to change very soon), feel free to use `reduce` to shave off that diminutive unnecessary overhead if you feel like it.
For newbies looking at this answer, be careful, they are not the same: ``` (apply hash-map [:a 5 :b 6]) ;= {:a 5, :b 6} (reduce hash-map [:a 5 :b 6]) ;= {{{:a 5} :b} 6} ```
3,153,400
if all Styles and Converters are stored in shared resource dictionary file (styles.xaml), and this file is used from various windows. Is it possible, to pass a parameter to that file, and propagate that parameter to the converters? I am looking for a way to pass a *"origin"* type parameter, so that the converters could be aware which place they are being used from? Just a hint of which window/grid is using the converter at the moment..
2010/06/30
[ "https://Stackoverflow.com/questions/3153400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349100/" ]
For newbies looking at this answer, be careful, they are not the same: ``` (apply hash-map [:a 5 :b 6]) ;= {:a 5, :b 6} (reduce hash-map [:a 5 :b 6]) ;= {{{:a 5} :b} 6} ```
Opinions vary- In the greater Lisp world, `reduce` is definitely considered more idiomatic. First, there is the variadic issues already discussed. Also, some Common Lisp compilers will actually fail when `apply` is applied against very long lists because of how they handle argument lists. Amongst Clojurists in my circle, though, using `apply` in this case seems more common. I find it easier to grok and prefer it also.
3,153,400
if all Styles and Converters are stored in shared resource dictionary file (styles.xaml), and this file is used from various windows. Is it possible, to pass a parameter to that file, and propagate that parameter to the converters? I am looking for a way to pass a *"origin"* type parameter, so that the converters could be aware which place they are being used from? Just a hint of which window/grid is using the converter at the moment..
2010/06/30
[ "https://Stackoverflow.com/questions/3153400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349100/" ]
I normally find myself preferring reduce when acting on any kind of collection - it performs well, and is a pretty useful function in general. The main reason I would use apply is if the parameters mean different things in different positions, or if you have a couple of initial parameters but want to get the rest from a collection, e.g. ``` (apply + 1 2 other-number-list) ```
When using a simple function like +, it really doesn't matter which one you use. In general, the idea is that `reduce` is an accumulating operation. You present the current accumulation value and one new value to your accumulating function The result of the function is the cumulative value for the next iteration. So, your iterations look like: ``` cum-val[i+1] = F( cum-val[i], input-val[i] ) ; please forgive the java-like syntax! ``` For apply, the idea is that you are attempting to call a function expecting a number of scalar arguments, but they are currently in a collection and need to be pulled out. So, instead of saying: ``` vals = [ val1 val2 val3 ] (some-fn (vals 0) (vals 1) (vals 2)) ``` we can say: ``` (apply some-fn vals) ``` and it is converted to be equivalent to: ``` (some-fn val1 val2 val3) ``` So, using "apply" is like "removing the parentheses" around the sequence.
3,153,400
if all Styles and Converters are stored in shared resource dictionary file (styles.xaml), and this file is used from various windows. Is it possible, to pass a parameter to that file, and propagate that parameter to the converters? I am looking for a way to pass a *"origin"* type parameter, so that the converters could be aware which place they are being used from? Just a hint of which window/grid is using the converter at the moment..
2010/06/30
[ "https://Stackoverflow.com/questions/3153400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349100/" ]
When using a simple function like +, it really doesn't matter which one you use. In general, the idea is that `reduce` is an accumulating operation. You present the current accumulation value and one new value to your accumulating function The result of the function is the cumulative value for the next iteration. So, your iterations look like: ``` cum-val[i+1] = F( cum-val[i], input-val[i] ) ; please forgive the java-like syntax! ``` For apply, the idea is that you are attempting to call a function expecting a number of scalar arguments, but they are currently in a collection and need to be pulled out. So, instead of saying: ``` vals = [ val1 val2 val3 ] (some-fn (vals 0) (vals 1) (vals 2)) ``` we can say: ``` (apply some-fn vals) ``` and it is converted to be equivalent to: ``` (some-fn val1 val2 val3) ``` So, using "apply" is like "removing the parentheses" around the sequence.
The beauty of apply is given function (+ in this case) can be applied to argument list formed by pre-pending intervening arguments with an ending collection. Reduce is an abstraction to process collection items applying the function for each and doesn't work with variable args case. ``` (apply + 1 2 3 [3 4]) => 13 (reduce + 1 2 3 [3 4]) ArityException Wrong number of args (5) passed to: core/reduce clojure.lang.AFn.throwArity (AFn.java:429) ```
3,153,400
if all Styles and Converters are stored in shared resource dictionary file (styles.xaml), and this file is used from various windows. Is it possible, to pass a parameter to that file, and propagate that parameter to the converters? I am looking for a way to pass a *"origin"* type parameter, so that the converters could be aware which place they are being used from? Just a hint of which window/grid is using the converter at the moment..
2010/06/30
[ "https://Stackoverflow.com/questions/3153400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349100/" ]
Opinions vary- In the greater Lisp world, `reduce` is definitely considered more idiomatic. First, there is the variadic issues already discussed. Also, some Common Lisp compilers will actually fail when `apply` is applied against very long lists because of how they handle argument lists. Amongst Clojurists in my circle, though, using `apply` in this case seems more common. I find it easier to grok and prefer it also.
A bit late, but... In this case, there is not a big difference. But in general they are not equivalent. Further more reduce can be more performant. Why? reduce checks if a collection or type implements [IReduced](https://github.com/clojure/clojure/blob/clojure-1.10.1/src/clj/clojure/core.clj#L6810) interface. That means a type knows how provide its values to the reducing function in the most performant why. reduce can be stopped prematurely by returning a Reduced value. Apply on the other hand, is invoked by [applyToHelper](https://github.com/clojure/clojure/blob/38bafca9e76cd6625d8dce5fb6d16b87845c8b9d/src/jvm/clojure/lang/AFn.java#L147). Which dispatches to the right arity by counting the args, unpacking the values from the collection. Is it a big performance impact? Probably not. My opinion is as others already pointed out. Use reduce if you want to semantically "reduce" a collection to a single value. Otherwise use apply.
3,153,400
if all Styles and Converters are stored in shared resource dictionary file (styles.xaml), and this file is used from various windows. Is it possible, to pass a parameter to that file, and propagate that parameter to the converters? I am looking for a way to pass a *"origin"* type parameter, so that the converters could be aware which place they are being used from? Just a hint of which window/grid is using the converter at the moment..
2010/06/30
[ "https://Stackoverflow.com/questions/3153400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349100/" ]
`reduce` and `apply` are of course only equivalent (in terms of the ultimate result returned) for associative functions which need to see all their arguments in the variable-arity case. When they are result-wise equivalent, I'd say that `apply` is always perfectly idiomatic, while `reduce` is equivalent -- and might shave off a fraction of a blink of an eye -- in a lot of the common cases. What follows is my rationale for believing this. `+` is itself implemented in terms of `reduce` for the variable-arity case (more than 2 arguments). Indeed, this seems like an immensely sensible "default" way to go for any variable-arity, associative function: `reduce` has the potential to perform some optimisations to speed things up -- perhaps through something like `internal-reduce`, a 1.2 novelty recently disabled in master, but hopefully to be reintroduced in the future -- which it would be silly to replicate in every function which might benefit from them in the vararg case. In such common cases, `apply` will just add a little overhead. (Note it's nothing to be really worried about.) On the other hand, a complex function might take advantage of some optimisation opportunities which aren't general enough to be built into `reduce`; then `apply` would let you take advantage of those while `reduce` might actually slow you down. A good example of the latter scenario occuring in practice is provided by `str`: it uses a `StringBuilder` internally and will benefit significantly from the use of `apply` rather than `reduce`. So, I'd say use `apply` when in doubt; and if you happen to know that it's not buying you anything over `reduce` (and that this is unlikely to change very soon), feel free to use `reduce` to shave off that diminutive unnecessary overhead if you feel like it.
I normally find myself preferring reduce when acting on any kind of collection - it performs well, and is a pretty useful function in general. The main reason I would use apply is if the parameters mean different things in different positions, or if you have a couple of initial parameters but want to get the rest from a collection, e.g. ``` (apply + 1 2 other-number-list) ```
3,153,400
if all Styles and Converters are stored in shared resource dictionary file (styles.xaml), and this file is used from various windows. Is it possible, to pass a parameter to that file, and propagate that parameter to the converters? I am looking for a way to pass a *"origin"* type parameter, so that the converters could be aware which place they are being used from? Just a hint of which window/grid is using the converter at the moment..
2010/06/30
[ "https://Stackoverflow.com/questions/3153400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349100/" ]
`reduce` and `apply` are of course only equivalent (in terms of the ultimate result returned) for associative functions which need to see all their arguments in the variable-arity case. When they are result-wise equivalent, I'd say that `apply` is always perfectly idiomatic, while `reduce` is equivalent -- and might shave off a fraction of a blink of an eye -- in a lot of the common cases. What follows is my rationale for believing this. `+` is itself implemented in terms of `reduce` for the variable-arity case (more than 2 arguments). Indeed, this seems like an immensely sensible "default" way to go for any variable-arity, associative function: `reduce` has the potential to perform some optimisations to speed things up -- perhaps through something like `internal-reduce`, a 1.2 novelty recently disabled in master, but hopefully to be reintroduced in the future -- which it would be silly to replicate in every function which might benefit from them in the vararg case. In such common cases, `apply` will just add a little overhead. (Note it's nothing to be really worried about.) On the other hand, a complex function might take advantage of some optimisation opportunities which aren't general enough to be built into `reduce`; then `apply` would let you take advantage of those while `reduce` might actually slow you down. A good example of the latter scenario occuring in practice is provided by `str`: it uses a `StringBuilder` internally and will benefit significantly from the use of `apply` rather than `reduce`. So, I'd say use `apply` when in doubt; and if you happen to know that it's not buying you anything over `reduce` (and that this is unlikely to change very soon), feel free to use `reduce` to shave off that diminutive unnecessary overhead if you feel like it.
The beauty of apply is given function (+ in this case) can be applied to argument list formed by pre-pending intervening arguments with an ending collection. Reduce is an abstraction to process collection items applying the function for each and doesn't work with variable args case. ``` (apply + 1 2 3 [3 4]) => 13 (reduce + 1 2 3 [3 4]) ArityException Wrong number of args (5) passed to: core/reduce clojure.lang.AFn.throwArity (AFn.java:429) ```
3,153,400
if all Styles and Converters are stored in shared resource dictionary file (styles.xaml), and this file is used from various windows. Is it possible, to pass a parameter to that file, and propagate that parameter to the converters? I am looking for a way to pass a *"origin"* type parameter, so that the converters could be aware which place they are being used from? Just a hint of which window/grid is using the converter at the moment..
2010/06/30
[ "https://Stackoverflow.com/questions/3153400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349100/" ]
For newbies looking at this answer, be careful, they are not the same: ``` (apply hash-map [:a 5 :b 6]) ;= {:a 5, :b 6} (reduce hash-map [:a 5 :b 6]) ;= {{{:a 5} :b} 6} ```
When using a simple function like +, it really doesn't matter which one you use. In general, the idea is that `reduce` is an accumulating operation. You present the current accumulation value and one new value to your accumulating function The result of the function is the cumulative value for the next iteration. So, your iterations look like: ``` cum-val[i+1] = F( cum-val[i], input-val[i] ) ; please forgive the java-like syntax! ``` For apply, the idea is that you are attempting to call a function expecting a number of scalar arguments, but they are currently in a collection and need to be pulled out. So, instead of saying: ``` vals = [ val1 val2 val3 ] (some-fn (vals 0) (vals 1) (vals 2)) ``` we can say: ``` (apply some-fn vals) ``` and it is converted to be equivalent to: ``` (some-fn val1 val2 val3) ``` So, using "apply" is like "removing the parentheses" around the sequence.
3,153,400
if all Styles and Converters are stored in shared resource dictionary file (styles.xaml), and this file is used from various windows. Is it possible, to pass a parameter to that file, and propagate that parameter to the converters? I am looking for a way to pass a *"origin"* type parameter, so that the converters could be aware which place they are being used from? Just a hint of which window/grid is using the converter at the moment..
2010/06/30
[ "https://Stackoverflow.com/questions/3153400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/349100/" ]
In this specific case I prefer `reduce` because it's more **readable**: when I read ``` (reduce + some-numbers) ``` I know immediately that you're turning a sequence into a value. With `apply` I have to consider which function is being applied: "ah, it's the `+` function, so I'm getting... a single number". Slightly less straightforward.
When using a simple function like +, it really doesn't matter which one you use. In general, the idea is that `reduce` is an accumulating operation. You present the current accumulation value and one new value to your accumulating function The result of the function is the cumulative value for the next iteration. So, your iterations look like: ``` cum-val[i+1] = F( cum-val[i], input-val[i] ) ; please forgive the java-like syntax! ``` For apply, the idea is that you are attempting to call a function expecting a number of scalar arguments, but they are currently in a collection and need to be pulled out. So, instead of saying: ``` vals = [ val1 val2 val3 ] (some-fn (vals 0) (vals 1) (vals 2)) ``` we can say: ``` (apply some-fn vals) ``` and it is converted to be equivalent to: ``` (some-fn val1 val2 val3) ``` So, using "apply" is like "removing the parentheses" around the sequence.
22,932
I would like to include a file on every block but the last three. How can I accomplish this?
2017/11/22
[ "https://craftcms.stackexchange.com/questions/22932", "https://craftcms.stackexchange.com", "https://craftcms.stackexchange.com/users/7395/" ]
95% of the time you see a 400 Bad Request error, it's because it's a CSRF token validation error (or you're just missing the token all-together). Craft 3 has CSRF validation enabled by default. Here's how to pass the CSRF token to your JS in Craft 2: <https://craftcms.com/support/csrf-protection#updating-your-javascript> Here's the CSRF token changes in Craft 3 you'll need to change: <https://docs.craftcms.com/v3/changes-in-craft-3.html#csrf-token-params>
For Craft3 in JS you can use `var tokenInput = Craft.getCsrfInput();` to get the HTML input or `Craft.csrfTokenName` and `Craft.csrfTokenValue` for the Name and Value. Then your post url should be `<form method="post" action="actions/plugin/default/ajax-call" accept-charset="UTF-8">` And finally in the controller ``` public function actionAjaxCall() { $result = 'Welcome to the DefaultController actionAjaxCall() method'; return $result; } ``` That should be all you need
6,742,567
I have a [jqGrid](http://www.trirand.com/jqgridwiki/doku.php) where I get data at once from server (java) in JSON format. I want the data in the jqGrid to be exported into Excel format. Till now I saw this [page](http://www.trirand.net/documentation/php/_2v212tis2.htm) which gives me an error in IE `'o.url is null or not an object' grid.import.js` Also I saw [this demo](http://www.trirand.com/blog/phpjqgrid/examples/functionality/excel/default.php) where on the tool tip of export button it says `Export To Excel` but the file saved is in xml format. So I would like any suggestions that can either transform my JSON string into excel using javascript or jquery plugin or using jqgrid's inbuilt feature. My jqGrid ![enter image description here](https://i.stack.imgur.com/fKFo1.png) My jqGrid Code ``` grid = jQuery("#list2"); grid.jqGrid({ datastr : comparePatchData, datatype: 'jsonstring', colNames:['Name',starheader, header1, header2], colModel:[ {name:'elementName',index:'elementName', width:90}, {name:'isPrasentinXml1',index:'isPrasentinXml1', width:100, align:'center', formatter: patchPresent}, {name:'isPrasentinXml2',index:'isPrasentinXml2', width:100, align:'center', formatter: patchPresent}, {name:'isPrasentinXml3',index:'isPrasentinXml3', width:100, align:'center', formatter: patchPresent} ], pager : '#gridpager2', rowNum:12, scrollOffset:0, height: 320, autowidth:true, viewrecords: true, gridview: true, loadonce:true, jsonReader: { repeatitems: false, page: function() { return 1; }, root: "response" }, subGrid: true, // define the icons in subgrid subGridOptions: { "plusicon" : "ui-icon-triangle-1-e", "minusicon" : "ui-icon-triangle-1-s", "openicon" : "ui-icon-arrowreturn-1-e", //expand all rows on load "expandOnLoad" : false }, subGridRowExpanded: function(subgrid_id, row_id) { //console.info(subgrid_id+", "+row_id); var subgrid_table_id, pager_id, iData = -1; subgrid_table_id = subgrid_id+"_t"; //pager_id = "p_"+subgrid_table_id; $("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' style='overflow-y:auto' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>"); $.each(comparePatchData.response,function(i,item){ if(item.id === row_id) { iData = i; return false; } }); if (iData == -1) { return; // no data for the subgrid } jQuery("#"+subgrid_table_id).jqGrid({ datastr : comparePatchData.response[iData], datatype: 'jsonstring', colNames: ['Name','Value1','Value2','Value3'], colModel: [ {name:"name",index:"name",width:90}, {name:"firstValue",index:"firstValue",width:100}, {name:"secondValue",index:"secondValue",width:100}, {name:"thirdValue",index:"thirdValue",width:100} ], rowNum:10, //pager: pager_id, sortname: 'name', sortorder: "asc", height: 'auto', autowidth:true, jsonReader: { repeatitems: false, //page: function() { return 1; }, root: "attribute" } }); jQuery("#"+subgrid_table_id).jqGrid('navGrid',{edit:false,add:false,del:false}); } }); grid.jqGrid('navGrid','#gridpager2',{add:false,edit:false,del:false}); grid.jqGrid('navButtonAdd','#gridpager2',{ caption:"Export to Excel", onClickButton : function () { jQuery("#list2").excelExport(); } }); ``` Part of my Json ``` { "response": [ { "id": "1", "elementName": "libgtop2-devel-2.14.4-3.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "libgtop2-devel-2.14.4-3.el5" } ] }, { "id": "2", "elementName": "ifd-egate-0.05-15", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "ifd-egate-0.05-15" } ] }, { "id": "3", "elementName": "libXScrnSaver-devel-1.1.0-3.1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "libXScrnSaver-devel-1.1.0-3.1" } ] }, { "id": "4", "elementName": "kde-i18n-Chinese-Big5-3.5.4-1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "kde-i18n-Chinese-Big5-3.5.4-1", "secondValue": "kde-i18n-Chinese-Big5-3.5.4-1" } ] }, { "id": "5", "elementName": "cpio-2.6-20", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "cpio-2.6-20", "secondValue": "cpio-2.6-20", "thirdValue": "cpio-2.6-20" } ] }, { "id": "6", "elementName": "grep-2.5.1-54.2.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "grep-2.5.1-54.2.el5", "secondValue": "grep-2.5.1-54.2.el5", "thirdValue": "grep-2.5.1-54.2.el5" } ] }, { "id": "7", "elementName": "avahi-compat-libdns_sd-0.6.16-1.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "avahi-compat-libdns_sd-0.6.16-1.el5", "secondValue": "avahi-compat-libdns_sd-0.6.16-1.el5", "thirdValue": "avahi-compat-libdns_sd-0.6.16-1.el5" } ] }, { "id": "8", "elementName": "gpm-devel-1.20.1-74.1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "gpm-devel-1.20.1-74.1", "secondValue": "gpm-devel-1.20.1-74.1", "thirdValue": "gpm-devel-1.20.1-74.1" } ] }, { "id": "9", "elementName": "esc-1.0.0-39.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "esc-1.0.0-39.el5" } ] }, { "id": "10", "elementName": "kde-i18n-Spanish-3.5.4-1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "kde-i18n-Spanish-3.5.4-1", "secondValue": "kde-i18n-Spanish-3.5.4-1" } ] } ] } ```
2011/07/19
[ "https://Stackoverflow.com/questions/6742567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/707414/" ]
You don't have to export a file using the Excel format in order to get the data into Excel. It is generally much easier to export to `CSV`. `CSV` files should be associated with Excel by default, so it should have the Excel icon by it and everything. `XML` would work the same way, I think, but the `CSV` format is much lighter, and does the same job in this case. Converting `JSON` to `CSV` is simple: ``` var response = JSON.parse(responseJSON).response; var csv = arrayToCSV(response); function arrayToCSV(arr) { var columnNames = []; var rows = []; for (var i=0, len=arr.length; i<len; i++) { // Each obj represents a row in the table var obj = arr[i]; // row will collect data from obj var row = []; for (var key in obj) { // Don't iterate through prototype stuff if (!obj.hasOwnProperty(key)) continue; // Collect the column names only once if (i === 0) columnNames.push(prepareValueForCSV(key)); // Collect the data row.push(prepareValueForCSV(obj[key])); } // Push each row to the main collection as csv string rows.push(row.join(',')); } // Put the columnNames at the beginning of all the rows rows.unshift(columnNames.join(',')); // Return the csv string return rows.join('\n'); } // This function allows us to have commas, line breaks, and double // quotes in our value without breaking CSV format. function prepareValueForCSV(val) { val = '' + val; // Escape quotes to avoid ending the value prematurely. val = val.replace(/"/g, '""'); return '"' + val + '"'; } ```
I'm working with MOSS 2007 to export some lists(say 5 lists) to excel.My requirement is i need more than one lists to be exported to excel.I have added a CEWP in my page with a button so that by one click i can export more than one list datas to excel.nw i get a run time error when i use jquery if( $('#WebPartWPQ3').is(':visible') )--->object expected error. I dont find any div id to trace..so is anybody know the answer,pls be come out of it.. ans related to this issue is really really really appreciated..my code is as follows. ``` <button type="button" onclick=exportToExcel();>Click<br> </button><br> <script type="text/javascript"><br> function exportToExcel() <br> { <br> alert('Hi');<br> //alert($("#WebPartWPQ3").attr("visibility"));<br> if( $('#WebPartWPQ3').is(':visible') )<br> { <br> contentType = "application/vnd.ms-excel";<br> var oExcel = new ActiveXObject("Excel.Application");<br> var oBook = oExcel.Workbooks.Add;<br> var oSheet = oBook.Worksheets(1);<br> var VESSApplications =document.getElementById<br>('ctl00_m_g_e3f5d791_5651_40ca_a03a_1c511c7f2b28_ctl00_ctl00_toolBarTbl');<br> alert(document.getElementById('WebPartWPQ3'));<br> var OtherApplications =document.getElementById('tblOtherApplications');<br> // var MFGApplications =document.getElementById('tblMFGApplications');<br> var row=3;<br> var col=1;<br> //Define criteria - start<br> oSheet.Cells(row, col)="Business Function";<br> oSheet.Cells(row, col+1)="VESS";<br> oSheet.Cells(row, col+2)=selectedVESSBusinessFunction;<br> // oSheet.Cells(row, col+3)="Manufacturing";<br> // if(selectedMFGBusinessFunction != "-Select-")<br> // oSheet.Cells(row, col+4)=selectedMFGBusinessFunction;<br> row +=2;<br> oSheet.Cells(row, col)="Operating System";<br> oSheet.Cells(row, col+1)="First Choice";<br> if(selectedOperatingSystemFirstChoice != "-Select-")<br> oSheet.Cells(row, col+2)=selectedOperatingSystemFirstChoice;<br> oSheet.Cells(row, col+3)="Second Choice";<br> if(selectedOperatingSystemSecondChoice != "-Select-")<br> oSheet.Cells(row, col+4)=selectedOperatingSystemSecondChoice;<br> row +=2;<br> oSheet.Cells(row, col)="Platform";<br> oSheet.Cells(row, col+1)="First Choice";<br> oSheet.Cells(row, col+2)=selectedPlatformFirstChoice;<br> oSheet.Cells(row, col+3)="Second Choice";<br> if(selectedPlatformSecondChoice != "-Select-")<br> oSheet.Cells(row, col+4)=selectedPlatformSecondChoice;<br> row +=2;<br> oSheet.Cells(row, col)="Delivery Method";<br> oSheet.Cells(row, col+1)="First Choice";<br> oSheet.Cells(row, col+2)=selectedDeliveryFirstChoice;<br> oSheet.Cells(row, col+3)="Second Choice";<br> if(selectedDeliverySecondChoice != "-Select-")<br> oSheet.Cells(row, col+4)=selectedDeliverySecondChoice;<br> row +=2;<br> //alert(VESSApplications.rows.length);<br> if(VESSApplications.rows.length>0)<br> {<br> for (var y = 0; y < VESSApplications.rows.length; y++) <br> {<br> for (var x = 0; x < VESSApplications .rows(y).cells.length; x++) <br> {<br> // oSheet.Cells(y + 1, x + 1) = VESSApplications .rows(y).cells(x).innerText;<br> oSheet.Cells(row, x + 1) = VESSApplications .rows(y).cells(x).innerText;<br> }<br> row++;<br> }<br> // oExcel.Visible = true;<br> // oExcel.UserControl = true;<br> }<br> else<br> {<br> alert("There is no VESS/Other Applications to Export!");<br> }<br> row +=2;<br> //Other Applications<br> /* for (var y = 0; y < OtherApplications.rows.length; y++) <br> {<br> for (var x = 0; x < OtherApplications.rows(y).cells.length; x++) <br> {<br> oSheet.Cells(row, x + 1) = OtherApplications.rows(y).cells(x).innerText;<br> }<br> row++;<br> }<br> row +=2;<br> //MFG Applications<br> for (var y = 0; y < MFGApplications.rows.length; y++) <br> {<br> for (var x = 0; x < MFGApplications.rows(y).cells.length; x++) <br> {<br> // oSheet.Cells(y + 1, x + 1) = VESSApplications .rows(y).cells(x).innerText;<br> oSheet.Cells(row, x + 1) = MFGApplications.rows(y).cells(x).innerText;<br> }<br> row++;<br> }<br> */ oSheet.columns.autofit;<br> oExcel.Visible = true;<br> oExcel.UserControl = true;<br> }<br> else<br> {<br> alert('No VESS/Other applications available to export');<br> }<br> }<br> ```
6,742,567
I have a [jqGrid](http://www.trirand.com/jqgridwiki/doku.php) where I get data at once from server (java) in JSON format. I want the data in the jqGrid to be exported into Excel format. Till now I saw this [page](http://www.trirand.net/documentation/php/_2v212tis2.htm) which gives me an error in IE `'o.url is null or not an object' grid.import.js` Also I saw [this demo](http://www.trirand.com/blog/phpjqgrid/examples/functionality/excel/default.php) where on the tool tip of export button it says `Export To Excel` but the file saved is in xml format. So I would like any suggestions that can either transform my JSON string into excel using javascript or jquery plugin or using jqgrid's inbuilt feature. My jqGrid ![enter image description here](https://i.stack.imgur.com/fKFo1.png) My jqGrid Code ``` grid = jQuery("#list2"); grid.jqGrid({ datastr : comparePatchData, datatype: 'jsonstring', colNames:['Name',starheader, header1, header2], colModel:[ {name:'elementName',index:'elementName', width:90}, {name:'isPrasentinXml1',index:'isPrasentinXml1', width:100, align:'center', formatter: patchPresent}, {name:'isPrasentinXml2',index:'isPrasentinXml2', width:100, align:'center', formatter: patchPresent}, {name:'isPrasentinXml3',index:'isPrasentinXml3', width:100, align:'center', formatter: patchPresent} ], pager : '#gridpager2', rowNum:12, scrollOffset:0, height: 320, autowidth:true, viewrecords: true, gridview: true, loadonce:true, jsonReader: { repeatitems: false, page: function() { return 1; }, root: "response" }, subGrid: true, // define the icons in subgrid subGridOptions: { "plusicon" : "ui-icon-triangle-1-e", "minusicon" : "ui-icon-triangle-1-s", "openicon" : "ui-icon-arrowreturn-1-e", //expand all rows on load "expandOnLoad" : false }, subGridRowExpanded: function(subgrid_id, row_id) { //console.info(subgrid_id+", "+row_id); var subgrid_table_id, pager_id, iData = -1; subgrid_table_id = subgrid_id+"_t"; //pager_id = "p_"+subgrid_table_id; $("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' style='overflow-y:auto' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>"); $.each(comparePatchData.response,function(i,item){ if(item.id === row_id) { iData = i; return false; } }); if (iData == -1) { return; // no data for the subgrid } jQuery("#"+subgrid_table_id).jqGrid({ datastr : comparePatchData.response[iData], datatype: 'jsonstring', colNames: ['Name','Value1','Value2','Value3'], colModel: [ {name:"name",index:"name",width:90}, {name:"firstValue",index:"firstValue",width:100}, {name:"secondValue",index:"secondValue",width:100}, {name:"thirdValue",index:"thirdValue",width:100} ], rowNum:10, //pager: pager_id, sortname: 'name', sortorder: "asc", height: 'auto', autowidth:true, jsonReader: { repeatitems: false, //page: function() { return 1; }, root: "attribute" } }); jQuery("#"+subgrid_table_id).jqGrid('navGrid',{edit:false,add:false,del:false}); } }); grid.jqGrid('navGrid','#gridpager2',{add:false,edit:false,del:false}); grid.jqGrid('navButtonAdd','#gridpager2',{ caption:"Export to Excel", onClickButton : function () { jQuery("#list2").excelExport(); } }); ``` Part of my Json ``` { "response": [ { "id": "1", "elementName": "libgtop2-devel-2.14.4-3.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "libgtop2-devel-2.14.4-3.el5" } ] }, { "id": "2", "elementName": "ifd-egate-0.05-15", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "ifd-egate-0.05-15" } ] }, { "id": "3", "elementName": "libXScrnSaver-devel-1.1.0-3.1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "libXScrnSaver-devel-1.1.0-3.1" } ] }, { "id": "4", "elementName": "kde-i18n-Chinese-Big5-3.5.4-1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "kde-i18n-Chinese-Big5-3.5.4-1", "secondValue": "kde-i18n-Chinese-Big5-3.5.4-1" } ] }, { "id": "5", "elementName": "cpio-2.6-20", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "cpio-2.6-20", "secondValue": "cpio-2.6-20", "thirdValue": "cpio-2.6-20" } ] }, { "id": "6", "elementName": "grep-2.5.1-54.2.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "grep-2.5.1-54.2.el5", "secondValue": "grep-2.5.1-54.2.el5", "thirdValue": "grep-2.5.1-54.2.el5" } ] }, { "id": "7", "elementName": "avahi-compat-libdns_sd-0.6.16-1.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "avahi-compat-libdns_sd-0.6.16-1.el5", "secondValue": "avahi-compat-libdns_sd-0.6.16-1.el5", "thirdValue": "avahi-compat-libdns_sd-0.6.16-1.el5" } ] }, { "id": "8", "elementName": "gpm-devel-1.20.1-74.1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "gpm-devel-1.20.1-74.1", "secondValue": "gpm-devel-1.20.1-74.1", "thirdValue": "gpm-devel-1.20.1-74.1" } ] }, { "id": "9", "elementName": "esc-1.0.0-39.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "esc-1.0.0-39.el5" } ] }, { "id": "10", "elementName": "kde-i18n-Spanish-3.5.4-1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "kde-i18n-Spanish-3.5.4-1", "secondValue": "kde-i18n-Spanish-3.5.4-1" } ] } ] } ```
2011/07/19
[ "https://Stackoverflow.com/questions/6742567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/707414/" ]
You don't have to export a file using the Excel format in order to get the data into Excel. It is generally much easier to export to `CSV`. `CSV` files should be associated with Excel by default, so it should have the Excel icon by it and everything. `XML` would work the same way, I think, but the `CSV` format is much lighter, and does the same job in this case. Converting `JSON` to `CSV` is simple: ``` var response = JSON.parse(responseJSON).response; var csv = arrayToCSV(response); function arrayToCSV(arr) { var columnNames = []; var rows = []; for (var i=0, len=arr.length; i<len; i++) { // Each obj represents a row in the table var obj = arr[i]; // row will collect data from obj var row = []; for (var key in obj) { // Don't iterate through prototype stuff if (!obj.hasOwnProperty(key)) continue; // Collect the column names only once if (i === 0) columnNames.push(prepareValueForCSV(key)); // Collect the data row.push(prepareValueForCSV(obj[key])); } // Push each row to the main collection as csv string rows.push(row.join(',')); } // Put the columnNames at the beginning of all the rows rows.unshift(columnNames.join(',')); // Return the csv string return rows.join('\n'); } // This function allows us to have commas, line breaks, and double // quotes in our value without breaking CSV format. function prepareValueForCSV(val) { val = '' + val; // Escape quotes to avoid ending the value prematurely. val = val.replace(/"/g, '""'); return '"' + val + '"'; } ```
> > I have a jqGrid where I get data at once from server (java) in JSON > format. I want the data in the jqGrid to be exported into Excel > format. > > > Here's a nice article, showing you how to export from jqGrid to Excel... <http://www.codeproject.com/Articles/784342/Export-data-from-jqGrid-into-a-real-Excel-file>
6,742,567
I have a [jqGrid](http://www.trirand.com/jqgridwiki/doku.php) where I get data at once from server (java) in JSON format. I want the data in the jqGrid to be exported into Excel format. Till now I saw this [page](http://www.trirand.net/documentation/php/_2v212tis2.htm) which gives me an error in IE `'o.url is null or not an object' grid.import.js` Also I saw [this demo](http://www.trirand.com/blog/phpjqgrid/examples/functionality/excel/default.php) where on the tool tip of export button it says `Export To Excel` but the file saved is in xml format. So I would like any suggestions that can either transform my JSON string into excel using javascript or jquery plugin or using jqgrid's inbuilt feature. My jqGrid ![enter image description here](https://i.stack.imgur.com/fKFo1.png) My jqGrid Code ``` grid = jQuery("#list2"); grid.jqGrid({ datastr : comparePatchData, datatype: 'jsonstring', colNames:['Name',starheader, header1, header2], colModel:[ {name:'elementName',index:'elementName', width:90}, {name:'isPrasentinXml1',index:'isPrasentinXml1', width:100, align:'center', formatter: patchPresent}, {name:'isPrasentinXml2',index:'isPrasentinXml2', width:100, align:'center', formatter: patchPresent}, {name:'isPrasentinXml3',index:'isPrasentinXml3', width:100, align:'center', formatter: patchPresent} ], pager : '#gridpager2', rowNum:12, scrollOffset:0, height: 320, autowidth:true, viewrecords: true, gridview: true, loadonce:true, jsonReader: { repeatitems: false, page: function() { return 1; }, root: "response" }, subGrid: true, // define the icons in subgrid subGridOptions: { "plusicon" : "ui-icon-triangle-1-e", "minusicon" : "ui-icon-triangle-1-s", "openicon" : "ui-icon-arrowreturn-1-e", //expand all rows on load "expandOnLoad" : false }, subGridRowExpanded: function(subgrid_id, row_id) { //console.info(subgrid_id+", "+row_id); var subgrid_table_id, pager_id, iData = -1; subgrid_table_id = subgrid_id+"_t"; //pager_id = "p_"+subgrid_table_id; $("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' style='overflow-y:auto' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>"); $.each(comparePatchData.response,function(i,item){ if(item.id === row_id) { iData = i; return false; } }); if (iData == -1) { return; // no data for the subgrid } jQuery("#"+subgrid_table_id).jqGrid({ datastr : comparePatchData.response[iData], datatype: 'jsonstring', colNames: ['Name','Value1','Value2','Value3'], colModel: [ {name:"name",index:"name",width:90}, {name:"firstValue",index:"firstValue",width:100}, {name:"secondValue",index:"secondValue",width:100}, {name:"thirdValue",index:"thirdValue",width:100} ], rowNum:10, //pager: pager_id, sortname: 'name', sortorder: "asc", height: 'auto', autowidth:true, jsonReader: { repeatitems: false, //page: function() { return 1; }, root: "attribute" } }); jQuery("#"+subgrid_table_id).jqGrid('navGrid',{edit:false,add:false,del:false}); } }); grid.jqGrid('navGrid','#gridpager2',{add:false,edit:false,del:false}); grid.jqGrid('navButtonAdd','#gridpager2',{ caption:"Export to Excel", onClickButton : function () { jQuery("#list2").excelExport(); } }); ``` Part of my Json ``` { "response": [ { "id": "1", "elementName": "libgtop2-devel-2.14.4-3.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "libgtop2-devel-2.14.4-3.el5" } ] }, { "id": "2", "elementName": "ifd-egate-0.05-15", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "ifd-egate-0.05-15" } ] }, { "id": "3", "elementName": "libXScrnSaver-devel-1.1.0-3.1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "libXScrnSaver-devel-1.1.0-3.1" } ] }, { "id": "4", "elementName": "kde-i18n-Chinese-Big5-3.5.4-1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "kde-i18n-Chinese-Big5-3.5.4-1", "secondValue": "kde-i18n-Chinese-Big5-3.5.4-1" } ] }, { "id": "5", "elementName": "cpio-2.6-20", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "cpio-2.6-20", "secondValue": "cpio-2.6-20", "thirdValue": "cpio-2.6-20" } ] }, { "id": "6", "elementName": "grep-2.5.1-54.2.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "grep-2.5.1-54.2.el5", "secondValue": "grep-2.5.1-54.2.el5", "thirdValue": "grep-2.5.1-54.2.el5" } ] }, { "id": "7", "elementName": "avahi-compat-libdns_sd-0.6.16-1.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "avahi-compat-libdns_sd-0.6.16-1.el5", "secondValue": "avahi-compat-libdns_sd-0.6.16-1.el5", "thirdValue": "avahi-compat-libdns_sd-0.6.16-1.el5" } ] }, { "id": "8", "elementName": "gpm-devel-1.20.1-74.1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "gpm-devel-1.20.1-74.1", "secondValue": "gpm-devel-1.20.1-74.1", "thirdValue": "gpm-devel-1.20.1-74.1" } ] }, { "id": "9", "elementName": "esc-1.0.0-39.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "esc-1.0.0-39.el5" } ] }, { "id": "10", "elementName": "kde-i18n-Spanish-3.5.4-1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "kde-i18n-Spanish-3.5.4-1", "secondValue": "kde-i18n-Spanish-3.5.4-1" } ] } ] } ```
2011/07/19
[ "https://Stackoverflow.com/questions/6742567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/707414/" ]
You don't have to export a file using the Excel format in order to get the data into Excel. It is generally much easier to export to `CSV`. `CSV` files should be associated with Excel by default, so it should have the Excel icon by it and everything. `XML` would work the same way, I think, but the `CSV` format is much lighter, and does the same job in this case. Converting `JSON` to `CSV` is simple: ``` var response = JSON.parse(responseJSON).response; var csv = arrayToCSV(response); function arrayToCSV(arr) { var columnNames = []; var rows = []; for (var i=0, len=arr.length; i<len; i++) { // Each obj represents a row in the table var obj = arr[i]; // row will collect data from obj var row = []; for (var key in obj) { // Don't iterate through prototype stuff if (!obj.hasOwnProperty(key)) continue; // Collect the column names only once if (i === 0) columnNames.push(prepareValueForCSV(key)); // Collect the data row.push(prepareValueForCSV(obj[key])); } // Push each row to the main collection as csv string rows.push(row.join(',')); } // Put the columnNames at the beginning of all the rows rows.unshift(columnNames.join(',')); // Return the csv string return rows.join('\n'); } // This function allows us to have commas, line breaks, and double // quotes in our value without breaking CSV format. function prepareValueForCSV(val) { val = '' + val; // Escape quotes to avoid ending the value prematurely. val = val.replace(/"/g, '""'); return '"' + val + '"'; } ```
I solved this like this: 1. **Read** <https://w3lessons.info/2015/07/13/export-html-table-to-excel-csv-json-pdf-png-using-jquery/#Installation> 2. Here is **github** <https://github.com/kayalshri/tableExport.jquery.plugin> 3. Here is a **demo** <http://demos.w3lessons.info/jquery-table-export#> It works perfectly i tried the **Export Excel**. In my case i just used the id selector for the jqgrid table. **BTW** This will export only visible part so if you 100 pages it need server side because info is just not there !.
6,742,567
I have a [jqGrid](http://www.trirand.com/jqgridwiki/doku.php) where I get data at once from server (java) in JSON format. I want the data in the jqGrid to be exported into Excel format. Till now I saw this [page](http://www.trirand.net/documentation/php/_2v212tis2.htm) which gives me an error in IE `'o.url is null or not an object' grid.import.js` Also I saw [this demo](http://www.trirand.com/blog/phpjqgrid/examples/functionality/excel/default.php) where on the tool tip of export button it says `Export To Excel` but the file saved is in xml format. So I would like any suggestions that can either transform my JSON string into excel using javascript or jquery plugin or using jqgrid's inbuilt feature. My jqGrid ![enter image description here](https://i.stack.imgur.com/fKFo1.png) My jqGrid Code ``` grid = jQuery("#list2"); grid.jqGrid({ datastr : comparePatchData, datatype: 'jsonstring', colNames:['Name',starheader, header1, header2], colModel:[ {name:'elementName',index:'elementName', width:90}, {name:'isPrasentinXml1',index:'isPrasentinXml1', width:100, align:'center', formatter: patchPresent}, {name:'isPrasentinXml2',index:'isPrasentinXml2', width:100, align:'center', formatter: patchPresent}, {name:'isPrasentinXml3',index:'isPrasentinXml3', width:100, align:'center', formatter: patchPresent} ], pager : '#gridpager2', rowNum:12, scrollOffset:0, height: 320, autowidth:true, viewrecords: true, gridview: true, loadonce:true, jsonReader: { repeatitems: false, page: function() { return 1; }, root: "response" }, subGrid: true, // define the icons in subgrid subGridOptions: { "plusicon" : "ui-icon-triangle-1-e", "minusicon" : "ui-icon-triangle-1-s", "openicon" : "ui-icon-arrowreturn-1-e", //expand all rows on load "expandOnLoad" : false }, subGridRowExpanded: function(subgrid_id, row_id) { //console.info(subgrid_id+", "+row_id); var subgrid_table_id, pager_id, iData = -1; subgrid_table_id = subgrid_id+"_t"; //pager_id = "p_"+subgrid_table_id; $("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' style='overflow-y:auto' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>"); $.each(comparePatchData.response,function(i,item){ if(item.id === row_id) { iData = i; return false; } }); if (iData == -1) { return; // no data for the subgrid } jQuery("#"+subgrid_table_id).jqGrid({ datastr : comparePatchData.response[iData], datatype: 'jsonstring', colNames: ['Name','Value1','Value2','Value3'], colModel: [ {name:"name",index:"name",width:90}, {name:"firstValue",index:"firstValue",width:100}, {name:"secondValue",index:"secondValue",width:100}, {name:"thirdValue",index:"thirdValue",width:100} ], rowNum:10, //pager: pager_id, sortname: 'name', sortorder: "asc", height: 'auto', autowidth:true, jsonReader: { repeatitems: false, //page: function() { return 1; }, root: "attribute" } }); jQuery("#"+subgrid_table_id).jqGrid('navGrid',{edit:false,add:false,del:false}); } }); grid.jqGrid('navGrid','#gridpager2',{add:false,edit:false,del:false}); grid.jqGrid('navButtonAdd','#gridpager2',{ caption:"Export to Excel", onClickButton : function () { jQuery("#list2").excelExport(); } }); ``` Part of my Json ``` { "response": [ { "id": "1", "elementName": "libgtop2-devel-2.14.4-3.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "libgtop2-devel-2.14.4-3.el5" } ] }, { "id": "2", "elementName": "ifd-egate-0.05-15", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "ifd-egate-0.05-15" } ] }, { "id": "3", "elementName": "libXScrnSaver-devel-1.1.0-3.1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "libXScrnSaver-devel-1.1.0-3.1" } ] }, { "id": "4", "elementName": "kde-i18n-Chinese-Big5-3.5.4-1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "kde-i18n-Chinese-Big5-3.5.4-1", "secondValue": "kde-i18n-Chinese-Big5-3.5.4-1" } ] }, { "id": "5", "elementName": "cpio-2.6-20", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "cpio-2.6-20", "secondValue": "cpio-2.6-20", "thirdValue": "cpio-2.6-20" } ] }, { "id": "6", "elementName": "grep-2.5.1-54.2.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "grep-2.5.1-54.2.el5", "secondValue": "grep-2.5.1-54.2.el5", "thirdValue": "grep-2.5.1-54.2.el5" } ] }, { "id": "7", "elementName": "avahi-compat-libdns_sd-0.6.16-1.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "avahi-compat-libdns_sd-0.6.16-1.el5", "secondValue": "avahi-compat-libdns_sd-0.6.16-1.el5", "thirdValue": "avahi-compat-libdns_sd-0.6.16-1.el5" } ] }, { "id": "8", "elementName": "gpm-devel-1.20.1-74.1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "gpm-devel-1.20.1-74.1", "secondValue": "gpm-devel-1.20.1-74.1", "thirdValue": "gpm-devel-1.20.1-74.1" } ] }, { "id": "9", "elementName": "esc-1.0.0-39.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "esc-1.0.0-39.el5" } ] }, { "id": "10", "elementName": "kde-i18n-Spanish-3.5.4-1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "kde-i18n-Spanish-3.5.4-1", "secondValue": "kde-i18n-Spanish-3.5.4-1" } ] } ] } ```
2011/07/19
[ "https://Stackoverflow.com/questions/6742567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/707414/" ]
> > I have a jqGrid where I get data at once from server (java) in JSON > format. I want the data in the jqGrid to be exported into Excel > format. > > > Here's a nice article, showing you how to export from jqGrid to Excel... <http://www.codeproject.com/Articles/784342/Export-data-from-jqGrid-into-a-real-Excel-file>
I'm working with MOSS 2007 to export some lists(say 5 lists) to excel.My requirement is i need more than one lists to be exported to excel.I have added a CEWP in my page with a button so that by one click i can export more than one list datas to excel.nw i get a run time error when i use jquery if( $('#WebPartWPQ3').is(':visible') )--->object expected error. I dont find any div id to trace..so is anybody know the answer,pls be come out of it.. ans related to this issue is really really really appreciated..my code is as follows. ``` <button type="button" onclick=exportToExcel();>Click<br> </button><br> <script type="text/javascript"><br> function exportToExcel() <br> { <br> alert('Hi');<br> //alert($("#WebPartWPQ3").attr("visibility"));<br> if( $('#WebPartWPQ3').is(':visible') )<br> { <br> contentType = "application/vnd.ms-excel";<br> var oExcel = new ActiveXObject("Excel.Application");<br> var oBook = oExcel.Workbooks.Add;<br> var oSheet = oBook.Worksheets(1);<br> var VESSApplications =document.getElementById<br>('ctl00_m_g_e3f5d791_5651_40ca_a03a_1c511c7f2b28_ctl00_ctl00_toolBarTbl');<br> alert(document.getElementById('WebPartWPQ3'));<br> var OtherApplications =document.getElementById('tblOtherApplications');<br> // var MFGApplications =document.getElementById('tblMFGApplications');<br> var row=3;<br> var col=1;<br> //Define criteria - start<br> oSheet.Cells(row, col)="Business Function";<br> oSheet.Cells(row, col+1)="VESS";<br> oSheet.Cells(row, col+2)=selectedVESSBusinessFunction;<br> // oSheet.Cells(row, col+3)="Manufacturing";<br> // if(selectedMFGBusinessFunction != "-Select-")<br> // oSheet.Cells(row, col+4)=selectedMFGBusinessFunction;<br> row +=2;<br> oSheet.Cells(row, col)="Operating System";<br> oSheet.Cells(row, col+1)="First Choice";<br> if(selectedOperatingSystemFirstChoice != "-Select-")<br> oSheet.Cells(row, col+2)=selectedOperatingSystemFirstChoice;<br> oSheet.Cells(row, col+3)="Second Choice";<br> if(selectedOperatingSystemSecondChoice != "-Select-")<br> oSheet.Cells(row, col+4)=selectedOperatingSystemSecondChoice;<br> row +=2;<br> oSheet.Cells(row, col)="Platform";<br> oSheet.Cells(row, col+1)="First Choice";<br> oSheet.Cells(row, col+2)=selectedPlatformFirstChoice;<br> oSheet.Cells(row, col+3)="Second Choice";<br> if(selectedPlatformSecondChoice != "-Select-")<br> oSheet.Cells(row, col+4)=selectedPlatformSecondChoice;<br> row +=2;<br> oSheet.Cells(row, col)="Delivery Method";<br> oSheet.Cells(row, col+1)="First Choice";<br> oSheet.Cells(row, col+2)=selectedDeliveryFirstChoice;<br> oSheet.Cells(row, col+3)="Second Choice";<br> if(selectedDeliverySecondChoice != "-Select-")<br> oSheet.Cells(row, col+4)=selectedDeliverySecondChoice;<br> row +=2;<br> //alert(VESSApplications.rows.length);<br> if(VESSApplications.rows.length>0)<br> {<br> for (var y = 0; y < VESSApplications.rows.length; y++) <br> {<br> for (var x = 0; x < VESSApplications .rows(y).cells.length; x++) <br> {<br> // oSheet.Cells(y + 1, x + 1) = VESSApplications .rows(y).cells(x).innerText;<br> oSheet.Cells(row, x + 1) = VESSApplications .rows(y).cells(x).innerText;<br> }<br> row++;<br> }<br> // oExcel.Visible = true;<br> // oExcel.UserControl = true;<br> }<br> else<br> {<br> alert("There is no VESS/Other Applications to Export!");<br> }<br> row +=2;<br> //Other Applications<br> /* for (var y = 0; y < OtherApplications.rows.length; y++) <br> {<br> for (var x = 0; x < OtherApplications.rows(y).cells.length; x++) <br> {<br> oSheet.Cells(row, x + 1) = OtherApplications.rows(y).cells(x).innerText;<br> }<br> row++;<br> }<br> row +=2;<br> //MFG Applications<br> for (var y = 0; y < MFGApplications.rows.length; y++) <br> {<br> for (var x = 0; x < MFGApplications.rows(y).cells.length; x++) <br> {<br> // oSheet.Cells(y + 1, x + 1) = VESSApplications .rows(y).cells(x).innerText;<br> oSheet.Cells(row, x + 1) = MFGApplications.rows(y).cells(x).innerText;<br> }<br> row++;<br> }<br> */ oSheet.columns.autofit;<br> oExcel.Visible = true;<br> oExcel.UserControl = true;<br> }<br> else<br> {<br> alert('No VESS/Other applications available to export');<br> }<br> }<br> ```
6,742,567
I have a [jqGrid](http://www.trirand.com/jqgridwiki/doku.php) where I get data at once from server (java) in JSON format. I want the data in the jqGrid to be exported into Excel format. Till now I saw this [page](http://www.trirand.net/documentation/php/_2v212tis2.htm) which gives me an error in IE `'o.url is null or not an object' grid.import.js` Also I saw [this demo](http://www.trirand.com/blog/phpjqgrid/examples/functionality/excel/default.php) where on the tool tip of export button it says `Export To Excel` but the file saved is in xml format. So I would like any suggestions that can either transform my JSON string into excel using javascript or jquery plugin or using jqgrid's inbuilt feature. My jqGrid ![enter image description here](https://i.stack.imgur.com/fKFo1.png) My jqGrid Code ``` grid = jQuery("#list2"); grid.jqGrid({ datastr : comparePatchData, datatype: 'jsonstring', colNames:['Name',starheader, header1, header2], colModel:[ {name:'elementName',index:'elementName', width:90}, {name:'isPrasentinXml1',index:'isPrasentinXml1', width:100, align:'center', formatter: patchPresent}, {name:'isPrasentinXml2',index:'isPrasentinXml2', width:100, align:'center', formatter: patchPresent}, {name:'isPrasentinXml3',index:'isPrasentinXml3', width:100, align:'center', formatter: patchPresent} ], pager : '#gridpager2', rowNum:12, scrollOffset:0, height: 320, autowidth:true, viewrecords: true, gridview: true, loadonce:true, jsonReader: { repeatitems: false, page: function() { return 1; }, root: "response" }, subGrid: true, // define the icons in subgrid subGridOptions: { "plusicon" : "ui-icon-triangle-1-e", "minusicon" : "ui-icon-triangle-1-s", "openicon" : "ui-icon-arrowreturn-1-e", //expand all rows on load "expandOnLoad" : false }, subGridRowExpanded: function(subgrid_id, row_id) { //console.info(subgrid_id+", "+row_id); var subgrid_table_id, pager_id, iData = -1; subgrid_table_id = subgrid_id+"_t"; //pager_id = "p_"+subgrid_table_id; $("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' style='overflow-y:auto' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>"); $.each(comparePatchData.response,function(i,item){ if(item.id === row_id) { iData = i; return false; } }); if (iData == -1) { return; // no data for the subgrid } jQuery("#"+subgrid_table_id).jqGrid({ datastr : comparePatchData.response[iData], datatype: 'jsonstring', colNames: ['Name','Value1','Value2','Value3'], colModel: [ {name:"name",index:"name",width:90}, {name:"firstValue",index:"firstValue",width:100}, {name:"secondValue",index:"secondValue",width:100}, {name:"thirdValue",index:"thirdValue",width:100} ], rowNum:10, //pager: pager_id, sortname: 'name', sortorder: "asc", height: 'auto', autowidth:true, jsonReader: { repeatitems: false, //page: function() { return 1; }, root: "attribute" } }); jQuery("#"+subgrid_table_id).jqGrid('navGrid',{edit:false,add:false,del:false}); } }); grid.jqGrid('navGrid','#gridpager2',{add:false,edit:false,del:false}); grid.jqGrid('navButtonAdd','#gridpager2',{ caption:"Export to Excel", onClickButton : function () { jQuery("#list2").excelExport(); } }); ``` Part of my Json ``` { "response": [ { "id": "1", "elementName": "libgtop2-devel-2.14.4-3.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "libgtop2-devel-2.14.4-3.el5" } ] }, { "id": "2", "elementName": "ifd-egate-0.05-15", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "ifd-egate-0.05-15" } ] }, { "id": "3", "elementName": "libXScrnSaver-devel-1.1.0-3.1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "libXScrnSaver-devel-1.1.0-3.1" } ] }, { "id": "4", "elementName": "kde-i18n-Chinese-Big5-3.5.4-1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "kde-i18n-Chinese-Big5-3.5.4-1", "secondValue": "kde-i18n-Chinese-Big5-3.5.4-1" } ] }, { "id": "5", "elementName": "cpio-2.6-20", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "cpio-2.6-20", "secondValue": "cpio-2.6-20", "thirdValue": "cpio-2.6-20" } ] }, { "id": "6", "elementName": "grep-2.5.1-54.2.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "grep-2.5.1-54.2.el5", "secondValue": "grep-2.5.1-54.2.el5", "thirdValue": "grep-2.5.1-54.2.el5" } ] }, { "id": "7", "elementName": "avahi-compat-libdns_sd-0.6.16-1.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "avahi-compat-libdns_sd-0.6.16-1.el5", "secondValue": "avahi-compat-libdns_sd-0.6.16-1.el5", "thirdValue": "avahi-compat-libdns_sd-0.6.16-1.el5" } ] }, { "id": "8", "elementName": "gpm-devel-1.20.1-74.1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "gpm-devel-1.20.1-74.1", "secondValue": "gpm-devel-1.20.1-74.1", "thirdValue": "gpm-devel-1.20.1-74.1" } ] }, { "id": "9", "elementName": "esc-1.0.0-39.el5", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": false, "isPrasentinXml2": false, "isPrasentinXml3": true, "attribute": [ { "name": "name", "thirdValue": "esc-1.0.0-39.el5" } ] }, { "id": "10", "elementName": "kde-i18n-Spanish-3.5.4-1", "subCategory": "patch", "isEqual": false, "isPrasentinXml1": true, "isPrasentinXml2": true, "isPrasentinXml3": true, "attribute": [ { "name": "name", "firstValue": "kde-i18n-Spanish-3.5.4-1", "secondValue": "kde-i18n-Spanish-3.5.4-1" } ] } ] } ```
2011/07/19
[ "https://Stackoverflow.com/questions/6742567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/707414/" ]
I solved this like this: 1. **Read** <https://w3lessons.info/2015/07/13/export-html-table-to-excel-csv-json-pdf-png-using-jquery/#Installation> 2. Here is **github** <https://github.com/kayalshri/tableExport.jquery.plugin> 3. Here is a **demo** <http://demos.w3lessons.info/jquery-table-export#> It works perfectly i tried the **Export Excel**. In my case i just used the id selector for the jqgrid table. **BTW** This will export only visible part so if you 100 pages it need server side because info is just not there !.
I'm working with MOSS 2007 to export some lists(say 5 lists) to excel.My requirement is i need more than one lists to be exported to excel.I have added a CEWP in my page with a button so that by one click i can export more than one list datas to excel.nw i get a run time error when i use jquery if( $('#WebPartWPQ3').is(':visible') )--->object expected error. I dont find any div id to trace..so is anybody know the answer,pls be come out of it.. ans related to this issue is really really really appreciated..my code is as follows. ``` <button type="button" onclick=exportToExcel();>Click<br> </button><br> <script type="text/javascript"><br> function exportToExcel() <br> { <br> alert('Hi');<br> //alert($("#WebPartWPQ3").attr("visibility"));<br> if( $('#WebPartWPQ3').is(':visible') )<br> { <br> contentType = "application/vnd.ms-excel";<br> var oExcel = new ActiveXObject("Excel.Application");<br> var oBook = oExcel.Workbooks.Add;<br> var oSheet = oBook.Worksheets(1);<br> var VESSApplications =document.getElementById<br>('ctl00_m_g_e3f5d791_5651_40ca_a03a_1c511c7f2b28_ctl00_ctl00_toolBarTbl');<br> alert(document.getElementById('WebPartWPQ3'));<br> var OtherApplications =document.getElementById('tblOtherApplications');<br> // var MFGApplications =document.getElementById('tblMFGApplications');<br> var row=3;<br> var col=1;<br> //Define criteria - start<br> oSheet.Cells(row, col)="Business Function";<br> oSheet.Cells(row, col+1)="VESS";<br> oSheet.Cells(row, col+2)=selectedVESSBusinessFunction;<br> // oSheet.Cells(row, col+3)="Manufacturing";<br> // if(selectedMFGBusinessFunction != "-Select-")<br> // oSheet.Cells(row, col+4)=selectedMFGBusinessFunction;<br> row +=2;<br> oSheet.Cells(row, col)="Operating System";<br> oSheet.Cells(row, col+1)="First Choice";<br> if(selectedOperatingSystemFirstChoice != "-Select-")<br> oSheet.Cells(row, col+2)=selectedOperatingSystemFirstChoice;<br> oSheet.Cells(row, col+3)="Second Choice";<br> if(selectedOperatingSystemSecondChoice != "-Select-")<br> oSheet.Cells(row, col+4)=selectedOperatingSystemSecondChoice;<br> row +=2;<br> oSheet.Cells(row, col)="Platform";<br> oSheet.Cells(row, col+1)="First Choice";<br> oSheet.Cells(row, col+2)=selectedPlatformFirstChoice;<br> oSheet.Cells(row, col+3)="Second Choice";<br> if(selectedPlatformSecondChoice != "-Select-")<br> oSheet.Cells(row, col+4)=selectedPlatformSecondChoice;<br> row +=2;<br> oSheet.Cells(row, col)="Delivery Method";<br> oSheet.Cells(row, col+1)="First Choice";<br> oSheet.Cells(row, col+2)=selectedDeliveryFirstChoice;<br> oSheet.Cells(row, col+3)="Second Choice";<br> if(selectedDeliverySecondChoice != "-Select-")<br> oSheet.Cells(row, col+4)=selectedDeliverySecondChoice;<br> row +=2;<br> //alert(VESSApplications.rows.length);<br> if(VESSApplications.rows.length>0)<br> {<br> for (var y = 0; y < VESSApplications.rows.length; y++) <br> {<br> for (var x = 0; x < VESSApplications .rows(y).cells.length; x++) <br> {<br> // oSheet.Cells(y + 1, x + 1) = VESSApplications .rows(y).cells(x).innerText;<br> oSheet.Cells(row, x + 1) = VESSApplications .rows(y).cells(x).innerText;<br> }<br> row++;<br> }<br> // oExcel.Visible = true;<br> // oExcel.UserControl = true;<br> }<br> else<br> {<br> alert("There is no VESS/Other Applications to Export!");<br> }<br> row +=2;<br> //Other Applications<br> /* for (var y = 0; y < OtherApplications.rows.length; y++) <br> {<br> for (var x = 0; x < OtherApplications.rows(y).cells.length; x++) <br> {<br> oSheet.Cells(row, x + 1) = OtherApplications.rows(y).cells(x).innerText;<br> }<br> row++;<br> }<br> row +=2;<br> //MFG Applications<br> for (var y = 0; y < MFGApplications.rows.length; y++) <br> {<br> for (var x = 0; x < MFGApplications.rows(y).cells.length; x++) <br> {<br> // oSheet.Cells(y + 1, x + 1) = VESSApplications .rows(y).cells(x).innerText;<br> oSheet.Cells(row, x + 1) = MFGApplications.rows(y).cells(x).innerText;<br> }<br> row++;<br> }<br> */ oSheet.columns.autofit;<br> oExcel.Visible = true;<br> oExcel.UserControl = true;<br> }<br> else<br> {<br> alert('No VESS/Other applications available to export');<br> }<br> }<br> ```
10,393,457
I took out my arduino chip from my board and followed the instructions to put it on a breadboard here: <http://itp.nyu.edu/physcomp/uploads/arduinobb_09.jpg> Everything works fine but when I plug in an XBee, the code doesnt work the way it should. The code I was using was two simple statements in the `setup()` function 1. Starting the Serial port: `Serial.begin(9600);` 2. Printing a line: `Serial.println("Hello World");` The problem is that it repeatedly sends this message over the XBee and I can see from the receiver XBee that it rapidly sends `"Hello World"` over and over. Also, if I check the voltage supplied by the voltage regulator, it is only 3.7 volts rather than 5 volts. Why is this happening?
2012/05/01
[ "https://Stackoverflow.com/questions/10393457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986955/" ]
The likely explanation as to why `setup()` is being executed continually is that the chip is being repeatedly reset. This is likely to be related to the low voltage you are seeing.
Yea sorry about this guys. I finally figured out the problem. The batteries I was using were not delivering enough current and power to supply both the arduino and xbee. The thing is, since the batteries were cheap, they ran out really quick of charge and I thought that it was a problem. Better batteries were the solution however.
1,156,915
I have to find all the unit vectors that are orthogonal to the vectors $\overrightarrow{a}=(2, -4, 3), \overrightarrow{b}=(-4, 8, -6)$ . I calculated that the cross product $\overrightarrow{a} \times \overrightarrow{b}=0$. Does this mean that the vector $(0, 0, 0)$ is a unit vector that is perpendicular to $\overrightarrow{a}$ and $\overrightarrow{b}$ ??
2015/02/20
[ "https://math.stackexchange.com/questions/1156915", "https://math.stackexchange.com", "https://math.stackexchange.com/users/80708/" ]
Given two sequences $x\_n$ and $y\_n$, we have the relation $$ x\_n\leq y\_n\Rightarrow \sum\_n x\_n\leq \sum\_n y\_n. $$ Therefore, if we set $x\_n=\sum^{\infty}\_{j=1}|I\_{n\_j}|$ and $y\_n=\frac{\epsilon }{2^n}$, applying the above gives $$ \sum\_n\sum^{\infty}\_{j=1}|I\_{n\_j}|<\sum\_n\frac{\epsilon}{2^n} $$
Equalities and inequalities with series of series are preserved under exchanging order of summation indices and also taking inner limits before outer limits, vs. summing all the terms in any order you want, so long as the series are either all positive or all negative terms. Thus you don't have to worry about the double summation and how it affects the inequality.
1,156,915
I have to find all the unit vectors that are orthogonal to the vectors $\overrightarrow{a}=(2, -4, 3), \overrightarrow{b}=(-4, 8, -6)$ . I calculated that the cross product $\overrightarrow{a} \times \overrightarrow{b}=0$. Does this mean that the vector $(0, 0, 0)$ is a unit vector that is perpendicular to $\overrightarrow{a}$ and $\overrightarrow{b}$ ??
2015/02/20
[ "https://math.stackexchange.com/questions/1156915", "https://math.stackexchange.com", "https://math.stackexchange.com/users/80708/" ]
We're exploiting Zeno's Paradox. Since each set has measure $0$, we can cover it by intervals whose total length is less than any positive real number. Since the union is countable, we can enumerate our sets of measure $0$ as $\{I\_1, I\_2, I\_3, \ldots, \}$. Let $\mu(S) = (b-a)$ for $S=(a,b)$. Let $\epsilon > 0$. Let $I\_j$ be covered by an open covering so that $$\mu(A\_j) < \frac{\epsilon}{2^j}$$ $$I\_j \subset A\_j$$ Then, since $\mu$ is countably sub-additive, $$\mu\left(\bigcup\_{j=1}^{\infty} I\_j \right) \leq \sum\_{j=1}^{\infty} \mu(I\_j) \leq \sum\_{j=1}^{\infty} \mu(A\_j) = \sum\_{j=1}^{\infty} \frac{\epsilon}{2^j} = \epsilon.$$ Thus, our set has measure 0. This is nice because we're able to do a countable number of ''things'' with only an epsilon of room.
Equalities and inequalities with series of series are preserved under exchanging order of summation indices and also taking inner limits before outer limits, vs. summing all the terms in any order you want, so long as the series are either all positive or all negative terms. Thus you don't have to worry about the double summation and how it affects the inequality.
1,156,915
I have to find all the unit vectors that are orthogonal to the vectors $\overrightarrow{a}=(2, -4, 3), \overrightarrow{b}=(-4, 8, -6)$ . I calculated that the cross product $\overrightarrow{a} \times \overrightarrow{b}=0$. Does this mean that the vector $(0, 0, 0)$ is a unit vector that is perpendicular to $\overrightarrow{a}$ and $\overrightarrow{b}$ ??
2015/02/20
[ "https://math.stackexchange.com/questions/1156915", "https://math.stackexchange.com", "https://math.stackexchange.com/users/80708/" ]
That's just how measures work. We start by defining that the measure of an open interval $(a,b)$ is $b-a$. Then we can attempt to define the (outer) measure of an arbitrary set $A$ as the infimum of all $\sum\_{i\in J}\mu(I\_i)$ where the $I\_j$ are open intervals and $A\subseteq \bigcup\_{i\in J}I\_i$. A few observations: * If more than countably many of the $\mu(I\_i)$ are nonzero, then certainly $\sum\_{i\in J}\mu(I\_i)=\infty$. Therefore and as any set $A\subseteq \mathbb R$ allows a countable cover, we nay restrict to the case that $J$ is countable. * With the extended definition, we still have $\mu((a,b))=b-a$. One shows by induction that $\sum\_{i\in J}\mu(I\_i)\ge b-a$ if $A\subseteq \bigcup\_{i\in J}I\_i$ with finite $J$, and then extends this to the case of countable $J$ (and larger $J$ need not be considered) Now given countably many $X\_k$, $k\in\mathbb N$, with $\mu(X\_k)=0$, and given $\epsilon>0$, by definition as infimum we find covers $X\_k\subseteq \bigcup\_{j\in J\_k}I\_{k,j}$ with $\sum\_{j\in J\_k}\mu(I\_{k,j})<2^{-k}\epsilon$. By the above we may assume that $J\_k=\mathbb N$. Then $$ X:=\bigcup\_{k\in\mathbb N}X\_k\subseteq\bigcup\_{k\in\mathbb N}\bigcup\_{j\in\mathbb N}I\_{k,j}=\bigcup\_{(k,j)\in\mathbb N\times\mathbb N}I\_{k,j}$$ with $$ \sum\_{(k,j)\in\mathbb N\times\mathbb N}\mu(I\_{k,j})=\sum\_{k\in\mathbb N}\sum\_{j\in\mathbb N}\mu(I\_{k,j})<\sum\_{k\in\mathbb N}2^{-k}\epsilon=\epsilon$$ so that $\mu(X)<\epsilon$. As $\epsilon$ was an arbitrary positive number, the infimum over all $\sum\_{i\in J}\mu(I\_i)$ for covers $X\subseteq \bigcup\_{i\in J}\mu(I\_j)$ is certainly $0$.
Equalities and inequalities with series of series are preserved under exchanging order of summation indices and also taking inner limits before outer limits, vs. summing all the terms in any order you want, so long as the series are either all positive or all negative terms. Thus you don't have to worry about the double summation and how it affects the inequality.
146,274
So I have a bunch of database users who should be able to execute a procedure with a call to xp\_cmdshell. They are not windows domain accounts, they are just sql-server logins. I want to do it using a proxy `##xp_cmdshell_proxy_account##`. I am aware of security threats that it may bring. I cannot use 'WITH EXECUTE AS admin' due to our company inner version control and I obviously do not want to grant all of the users rights to execute `xp_cmdshell`, that is why my only choice (am I right here?) is using the proxy account. I have a special windows-domain account for it, to whom I granted xp\_cmdshell execution rights. I can successfully execute cmdshell using this account. I created the proxy account using the following command: ``` EXEC sp_xp_cmdshell_proxy_account [my_domain\special_account],'SuperSecretPassword' ``` When I try to execute any xp\_cmdshell command as a database user with no xp\_cmdshell rights an error appears: ``` The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'. ``` My question is - can I execute a xp\_cmdshell command using an sql server login and I am simply missing something here or is it only possible using a domain account? Is there any other procedure to follow here to make it happen? If I fail to make the above work I will have to switch some logic to a CLR procedure, but I am determined to make it work. I am using sql-server 2012. Any help will be appreciated, thanks!
2016/08/09
[ "https://dba.stackexchange.com/questions/146274", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/88793/" ]
It appears you need to grant access to xp\_cmdshell for your sql server login. Once the user has permission to run xp\_cmdshell, it will use your proxy account to run it since it is a non-privileged user. Another alternative would be to use certificates to sign your stored procedures, allowing you to grant additional privileges for users executing that stored procedure. <https://msdn.microsoft.com/en-us/library/bb283630.aspx> The downside of certificates is that the procedure needs to be re-signed every time you make a change to it, which can be a pain.
The question is: what exactly are you using `xp_cmdshell` for? Is it to run a random program, or get a directory listing, or something else? You seem to be avoiding SQLCLR but you don't say why. In many cases, SQLCLR is more secure and more efficient. But it is not possible to be more specific unless additional details are provided regarding what the ultimate goal is. Outside of that, you can grant permissions in a highly targeted manner using signatures (@Shane also mentioned this). You can find an example of doing this in my answer to the following question, also here on DBA.StackExchange: [What minimum permissions do I need to provide to a user so that it can check the status of SQL Server Agent Service?](https://dba.stackexchange.com/questions/62230/what-minimum-permissions-do-i-need-to-provide-to-a-user-so-that-it-can-check-the/103275#103275) The basic concept is that you will: 1. Create a Certificate in the `master` Database 2. Create a Login based on this Certificate 3. Grant this Login the appropriate permission to run `xp_cmdshell` 4. Backup the Certificate 5. Restore the Certificate into the Database that has the Stored Procedure that is calling `xp_cmdshell` 6. Sign the Stored Procedure that is calling `xp_cmdshell` via [ADD SIGNATURE](https://msdn.microsoft.com/en-us/library/ms181700.aspx) Additional links to other variations of examples can be found in my answer to this question: [stored procedure can select and update tables in other databases - minimal permissions granted](https://dba.stackexchange.com/questions/131005/stored-procedure-can-select-and-update-tables-in-other-databases-minimal-permi/131026#131026)
146,274
So I have a bunch of database users who should be able to execute a procedure with a call to xp\_cmdshell. They are not windows domain accounts, they are just sql-server logins. I want to do it using a proxy `##xp_cmdshell_proxy_account##`. I am aware of security threats that it may bring. I cannot use 'WITH EXECUTE AS admin' due to our company inner version control and I obviously do not want to grant all of the users rights to execute `xp_cmdshell`, that is why my only choice (am I right here?) is using the proxy account. I have a special windows-domain account for it, to whom I granted xp\_cmdshell execution rights. I can successfully execute cmdshell using this account. I created the proxy account using the following command: ``` EXEC sp_xp_cmdshell_proxy_account [my_domain\special_account],'SuperSecretPassword' ``` When I try to execute any xp\_cmdshell command as a database user with no xp\_cmdshell rights an error appears: ``` The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'. ``` My question is - can I execute a xp\_cmdshell command using an sql server login and I am simply missing something here or is it only possible using a domain account? Is there any other procedure to follow here to make it happen? If I fail to make the above work I will have to switch some logic to a CLR procedure, but I am determined to make it work. I am using sql-server 2012. Any help will be appreciated, thanks!
2016/08/09
[ "https://dba.stackexchange.com/questions/146274", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/88793/" ]
You can use a SQL Server login. The following procedure is explained in [MSDN](https://msdn.microsoft.com/en-us/library/ms175046(v=sql.110).aspx): > > To allow non-administrators to use xp\_cmdshell, and allow SQL Server > to create child processes with the security token of a less-privileged > account, follow these steps: > > > 1. Create and customize a Windows local user account or a domain account with the least privileges that your processes require. > 2. Use the sp\_xp\_cmdshell\_proxy\_account system procedure to configure xp\_cmdshell to use that least-privileged account. > Note You can also configure this proxy account using SQL > Server Management Studio by right-clicking Properties on your server > name in Object Explorer, and looking on the Security tab for the > Server proxy account section. > 3. In Management Studio, using the master > database, execute the GRANT exec ON xp\_cmdshell TO '' > statement to give specific non-sysadmin users the ability to execute > xp\_cmdshell. The specified login must be mapped to a user in the > master database. > > >
The question is: what exactly are you using `xp_cmdshell` for? Is it to run a random program, or get a directory listing, or something else? You seem to be avoiding SQLCLR but you don't say why. In many cases, SQLCLR is more secure and more efficient. But it is not possible to be more specific unless additional details are provided regarding what the ultimate goal is. Outside of that, you can grant permissions in a highly targeted manner using signatures (@Shane also mentioned this). You can find an example of doing this in my answer to the following question, also here on DBA.StackExchange: [What minimum permissions do I need to provide to a user so that it can check the status of SQL Server Agent Service?](https://dba.stackexchange.com/questions/62230/what-minimum-permissions-do-i-need-to-provide-to-a-user-so-that-it-can-check-the/103275#103275) The basic concept is that you will: 1. Create a Certificate in the `master` Database 2. Create a Login based on this Certificate 3. Grant this Login the appropriate permission to run `xp_cmdshell` 4. Backup the Certificate 5. Restore the Certificate into the Database that has the Stored Procedure that is calling `xp_cmdshell` 6. Sign the Stored Procedure that is calling `xp_cmdshell` via [ADD SIGNATURE](https://msdn.microsoft.com/en-us/library/ms181700.aspx) Additional links to other variations of examples can be found in my answer to this question: [stored procedure can select and update tables in other databases - minimal permissions granted](https://dba.stackexchange.com/questions/131005/stored-procedure-can-select-and-update-tables-in-other-databases-minimal-permi/131026#131026)
2,581,664
I have two fields that need to multiply each other and fill a third form's value. Here's the HTML: ``` <input type="text" name="estimate[concrete][price]" value="" onBlur="calc_concreteprice(document.forms.mainform);" /> per SF <strong>times</strong> <input type="text" name="estimate[concrete][sqft]" value="" onBlur="calc_concreteprice(document.forms.mainform);" /> SF = <input type="text" name="estimate[concrete][quick_total]" value="" /> ``` Here's my JavaScript: ``` function calc_concreteprice(mainform) { var oprice; var ototal; oprice = ((mainform.estimate[concrete][sqft].value) * (mainform.estimate[concrete][price].value)); ototal = (oprice); mainform.estimate[concrete][quick_total].value = ototal; } ``` I want the first two forms to be multiplied together and output to the third. I think my problem may be within how I am referencing the input field names, with brackets (I'm taking results from this form as an array so I'm already used to working with the results as a multi-dimensional array).
2010/04/05
[ "https://Stackoverflow.com/questions/2581664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/60318/" ]
When you write things like `mainform.estimate[concrete][quick_total].value`, it's attempting to access properties called `concrete` and `quick_total`. Try using this format instead to distinguish between a property and a string containing square brackets: `mainform['estimate[concrete][quick_total]'].value`
I'm pretty sure it's the square brackets. Try changing your names on your input fields. If you want definite separation between the names to show some sort of hierarchy, try using underscores like `<input type="text" name="estimate_concrete_price" />`. In your javascript change it to `mainform.estimate_concrete_price.value`..... Give that a shot. I'm pretty sure it will work.
58,992,027
I have a table with clients and I need to show the first country of each client like a default country. ``` Table Clients ID_Client | Name_Client 1 | Mike 2 | Jon 3 | Ben Table Countries ID_Country | ID_Client | Name_Country 1 | 1 | France 2 | 1 | USA 3 | 1 | England 4 | 2 | Portugal 5 | 2 | Spain 6 | 3 | Germany ``` I only want the first row of each country. ``` Example: Mike - France Jon - Portugal Ben - Germany ``` I tried this but only retry 1 row: ``` SELECT Name_Client, Name_Country FROM Clients WHERE ID_Client = (SELECT TOP 1 ID_Client From Countries order by ID_Country) Result: Mike | France ```
2019/11/22
[ "https://Stackoverflow.com/questions/58992027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6538386/" ]
You can use Outer APPLY or CROSS APPLY as per Below example, ``` SELECT C.Name_Client + ' - ' + V.Name_Country FROM Clients C OUTER APPLY( SELECT TOP 1 * FROM Countries CO WHERE CO.ID_Client = C.ID_Client ORDER BY ID_Country ) V ```
[SQL Fiddle](http://sqlfiddle.com/#!18/2ee07/7) **MS SQL Server 2017 Schema Setup**: ``` CREATE TABLE CLIENTS (ID_Client int,Name_Client varchar(255)) CREATE TABLE COUNTRIES(ID_Country int,ID_Client int,Name_Country varchar(255)) INSERT INTO CLIENTS(ID_Client,Name_Client)VALUES(1,'Mike'),(2,'Jon'),(3,'Ben') INSERT INTO COUNTRIES(ID_Country,ID_Client,Name_Country)VALUES(1,1,'France'), (2,1,'USA'),(3,1,'England'), (4,2,'Portugal'),(5,2,'Spain'), (6,3,'Germany') ``` **Query 1**: ``` with CTE as ( select c.Name_Client, ct.Name_Country, row_number() over(partition by c.ID_Client order by ct.ID_Country) as rn FROM CLIENTS c left join COUNTRIES ct on c.ID_Client=ct.ID_Client ) select CTE.Name_Client,CTE.Name_Country from CTE where rn=1 ``` **[Results](http://sqlfiddle.com/#!18/2ee07/7/0)**: ``` | Name_Client | Name_Country | |-------------|--------------| | Mike | France | | Jon | Portugal | | Ben | Germany | ```
58,992,027
I have a table with clients and I need to show the first country of each client like a default country. ``` Table Clients ID_Client | Name_Client 1 | Mike 2 | Jon 3 | Ben Table Countries ID_Country | ID_Client | Name_Country 1 | 1 | France 2 | 1 | USA 3 | 1 | England 4 | 2 | Portugal 5 | 2 | Spain 6 | 3 | Germany ``` I only want the first row of each country. ``` Example: Mike - France Jon - Portugal Ben - Germany ``` I tried this but only retry 1 row: ``` SELECT Name_Client, Name_Country FROM Clients WHERE ID_Client = (SELECT TOP 1 ID_Client From Countries order by ID_Country) Result: Mike | France ```
2019/11/22
[ "https://Stackoverflow.com/questions/58992027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6538386/" ]
Your sub-query isn't correlated, try to use `APPLY` : ``` SELECT c.Name_Client, cn.Name_Country FROM Clients C OUTER APPLY (SELECT TOP (1) cn.Name_Country From Countries CN WHERE cn.ID_Client = c.ID_Client ORDER BY cn.ID_Country ) cn; ```
use row\_number() ``` with cte as ( select c.Name_Client, cn.Name_Country, row_number() over(partition by c.ID_Client order by ID_Country) rn clients c join country cn on c.client_id=cn.client_id ) select * form cte where rn=1 ```