qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
51,915,320
`var string = "3y4jd424jfm` Ideally, I'd want it to be `["3","y","4","j","d","4","24","j","f","m"]` but when I split: `string.split("")`, the `2` and the `4` in `24` are separated. How can I account for double digits? Edit: Here is the question I was trying to solve from a coding practice: *Using the JavaScript language, have the function EvenPairs(str) take the str parameter being passed and determine if a pair of adjacent even numbers exists anywhere in the string. If a pair exists, return the string true, otherwise return false. For example: if str is "f178svg3k19k46" then there are two even numbers at the end of the string, "46" so your program should return the string true. Another example: if str is "7r5gg812" then the pair is "812" (8 and 12) so your program should return the string true.*
2018/08/19
[ "https://Stackoverflow.com/questions/51915320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10245232/" ]
Use regex for number extract then split for char as following: ``` var regex = /\d+/g; var string = "3y4jd424jfm"; var numbers = string.match(regex); var chars = string.replace(/\d+/g, "").split(""); var parts = numbers.concat(chars); console.log(parts); ```
Starting from this example `7r5gg812`, the answer is true because there's a couple of even numbers `8` and `12` next to each other. A possible solution is to iterate over the string with a counter that is incremented when you see an even digit, reset to 0 when it's not a digit. Odd digits are simply ignored: ``` function EvenPairs(str) { let counter = 0; for (let i = 0; i < str.length; i++) { if (isNaN(str[i] % 2)) { counter = 0; } else if (str[i] % 2 === 0) { counter++; } if (counter === 2) { return true; } } return false; } ``` Other solution, using regexps: ``` function EvenPairs(str) { return /\d\d/.test(str.replace(/[13579]/g, '')); } ```
51,915,320
`var string = "3y4jd424jfm` Ideally, I'd want it to be `["3","y","4","j","d","4","24","j","f","m"]` but when I split: `string.split("")`, the `2` and the `4` in `24` are separated. How can I account for double digits? Edit: Here is the question I was trying to solve from a coding practice: *Using the JavaScript language, have the function EvenPairs(str) take the str parameter being passed and determine if a pair of adjacent even numbers exists anywhere in the string. If a pair exists, return the string true, otherwise return false. For example: if str is "f178svg3k19k46" then there are two even numbers at the end of the string, "46" so your program should return the string true. Another example: if str is "7r5gg812" then the pair is "812" (8 and 12) so your program should return the string true.*
2018/08/19
[ "https://Stackoverflow.com/questions/51915320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10245232/" ]
You could take a staged approach by * getting only numbers of the string in an array * filer by length of the string, * check if two of the digits are even ```js function even(n) { return !(n % 2); } function checkEvenPair(string) { return string .match(/\d+/g) .filter(s => s.length > 1) .some(s => [...s].some((c => v => even(v) && !--c)(2)) ); } console.log(checkEvenPair('2f35fq1p97y931')); // false console.log(checkEvenPair('3y4jd424jfm')); // true 4 2 console.log(checkEvenPair('f178svg3k19k46')); // true 4 6 console.log(checkEvenPair('7r5gg812')); // true 8 12 console.log(checkEvenPair('2f35fq1p97y92321')); // true (9)2 32 ``` A regular expression solution by taking only even numbers for matching. ```js function checkEvenPair(string) { return /[02468]\d*[02468]/.test(string); } console.log(checkEvenPair('2f35fq1p97y931')); // false console.log(checkEvenPair('3y4jd424jfm')); // true console.log(checkEvenPair('f178svg3k19k46')); // true console.log(checkEvenPair('7r5gg812')); // true console.log(checkEvenPair('2f35fq1p97y92321')); // true ```
Use regex for number extract then split for char as following: ``` var regex = /\d+/g; var string = "3y4jd424jfm"; var numbers = string.match(regex); var chars = string.replace(/\d+/g, "").split(""); var parts = numbers.concat(chars); console.log(parts); ```
51,915,320
`var string = "3y4jd424jfm` Ideally, I'd want it to be `["3","y","4","j","d","4","24","j","f","m"]` but when I split: `string.split("")`, the `2` and the `4` in `24` are separated. How can I account for double digits? Edit: Here is the question I was trying to solve from a coding practice: *Using the JavaScript language, have the function EvenPairs(str) take the str parameter being passed and determine if a pair of adjacent even numbers exists anywhere in the string. If a pair exists, return the string true, otherwise return false. For example: if str is "f178svg3k19k46" then there are two even numbers at the end of the string, "46" so your program should return the string true. Another example: if str is "7r5gg812" then the pair is "812" (8 and 12) so your program should return the string true.*
2018/08/19
[ "https://Stackoverflow.com/questions/51915320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10245232/" ]
Use regex for number extract then split for char as following: ``` var regex = /\d+/g; var string = "3y4jd424jfm"; var numbers = string.match(regex); var chars = string.replace(/\d+/g, "").split(""); var parts = numbers.concat(chars); console.log(parts); ```
You can use `RegExp` for that, you don't need to check if two numbers are even, you just need to check two constitutive chars (which is numbers) are even. so for `1234` you don't have to check `12` and `34` in that case the question could have been more complicated (what will be solved here). you just need to check [`1 & 2`], [`2 & 3`], [`3 & 4`] where none of them are even pairs. And we can avoid parsing string and read as number, arithmetic calculation for even,.. and such things. So, for the the simple one (consicutive even chars) Regex for even digit is : `/[02468]/` `<your string>.match(/[02468]{2}/)` would give you the result. Example: ```js function EvenPairs(str) { let evensDigit = '[02468]', consecutiveEvenRegex = new RegExp(evensDigit + "{2}"); return !!str.match(consecutiveEvenRegex); } let str1 = "f178svg3k19k46"; //should be true as 4 then 6 let str2 = "7r5gg812"; // should be false, as 8 -> 1 -> 2 (and not 8 then 12) console.log(`Test EvenPairs for ${str1}: `, EvenPairs(str1)); console.log(`Test EvenPairs for ${str2}: `, EvenPairs(str2)); ``` Now back to the actual (probable) problem to check for 2 constitutive even numbers (not only chars) we just need to check the existence of: `<any even char><empty or 0-9 char><any even char>` i.e. `/[02468][0-9]{0,}[02468]/` let's create a working example for it ```js function EvenPairs(str) { let evenDigit = '[02468]', digitsOrEmpty = '[0-9]{0,}', consecutiveEvenRegex = new RegExp(evenDigit + digitsOrEmpty + evenDigit); return !!str.match(consecutiveEvenRegex); } let str1 = "f178svg3k19k46"; //should be true as 4 then 6 let str2 = "7r5gg812"; // should be true as well, as 8 -> 12 console.log(`Test EvenPairs for ${str1}: `, EvenPairs(str1)); console.log(`Test EvenPairs for ${str2}: `, EvenPairs(str2)); ```
51,915,320
`var string = "3y4jd424jfm` Ideally, I'd want it to be `["3","y","4","j","d","4","24","j","f","m"]` but when I split: `string.split("")`, the `2` and the `4` in `24` are separated. How can I account for double digits? Edit: Here is the question I was trying to solve from a coding practice: *Using the JavaScript language, have the function EvenPairs(str) take the str parameter being passed and determine if a pair of adjacent even numbers exists anywhere in the string. If a pair exists, return the string true, otherwise return false. For example: if str is "f178svg3k19k46" then there are two even numbers at the end of the string, "46" so your program should return the string true. Another example: if str is "7r5gg812" then the pair is "812" (8 and 12) so your program should return the string true.*
2018/08/19
[ "https://Stackoverflow.com/questions/51915320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10245232/" ]
You could take a staged approach by * getting only numbers of the string in an array * filer by length of the string, * check if two of the digits are even ```js function even(n) { return !(n % 2); } function checkEvenPair(string) { return string .match(/\d+/g) .filter(s => s.length > 1) .some(s => [...s].some((c => v => even(v) && !--c)(2)) ); } console.log(checkEvenPair('2f35fq1p97y931')); // false console.log(checkEvenPair('3y4jd424jfm')); // true 4 2 console.log(checkEvenPair('f178svg3k19k46')); // true 4 6 console.log(checkEvenPair('7r5gg812')); // true 8 12 console.log(checkEvenPair('2f35fq1p97y92321')); // true (9)2 32 ``` A regular expression solution by taking only even numbers for matching. ```js function checkEvenPair(string) { return /[02468]\d*[02468]/.test(string); } console.log(checkEvenPair('2f35fq1p97y931')); // false console.log(checkEvenPair('3y4jd424jfm')); // true console.log(checkEvenPair('f178svg3k19k46')); // true console.log(checkEvenPair('7r5gg812')); // true console.log(checkEvenPair('2f35fq1p97y92321')); // true ```
Starting from this example `7r5gg812`, the answer is true because there's a couple of even numbers `8` and `12` next to each other. A possible solution is to iterate over the string with a counter that is incremented when you see an even digit, reset to 0 when it's not a digit. Odd digits are simply ignored: ``` function EvenPairs(str) { let counter = 0; for (let i = 0; i < str.length; i++) { if (isNaN(str[i] % 2)) { counter = 0; } else if (str[i] % 2 === 0) { counter++; } if (counter === 2) { return true; } } return false; } ``` Other solution, using regexps: ``` function EvenPairs(str) { return /\d\d/.test(str.replace(/[13579]/g, '')); } ```
51,915,320
`var string = "3y4jd424jfm` Ideally, I'd want it to be `["3","y","4","j","d","4","24","j","f","m"]` but when I split: `string.split("")`, the `2` and the `4` in `24` are separated. How can I account for double digits? Edit: Here is the question I was trying to solve from a coding practice: *Using the JavaScript language, have the function EvenPairs(str) take the str parameter being passed and determine if a pair of adjacent even numbers exists anywhere in the string. If a pair exists, return the string true, otherwise return false. For example: if str is "f178svg3k19k46" then there are two even numbers at the end of the string, "46" so your program should return the string true. Another example: if str is "7r5gg812" then the pair is "812" (8 and 12) so your program should return the string true.*
2018/08/19
[ "https://Stackoverflow.com/questions/51915320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10245232/" ]
You could take a staged approach by * getting only numbers of the string in an array * filer by length of the string, * check if two of the digits are even ```js function even(n) { return !(n % 2); } function checkEvenPair(string) { return string .match(/\d+/g) .filter(s => s.length > 1) .some(s => [...s].some((c => v => even(v) && !--c)(2)) ); } console.log(checkEvenPair('2f35fq1p97y931')); // false console.log(checkEvenPair('3y4jd424jfm')); // true 4 2 console.log(checkEvenPair('f178svg3k19k46')); // true 4 6 console.log(checkEvenPair('7r5gg812')); // true 8 12 console.log(checkEvenPair('2f35fq1p97y92321')); // true (9)2 32 ``` A regular expression solution by taking only even numbers for matching. ```js function checkEvenPair(string) { return /[02468]\d*[02468]/.test(string); } console.log(checkEvenPair('2f35fq1p97y931')); // false console.log(checkEvenPair('3y4jd424jfm')); // true console.log(checkEvenPair('f178svg3k19k46')); // true console.log(checkEvenPair('7r5gg812')); // true console.log(checkEvenPair('2f35fq1p97y92321')); // true ```
You can use `RegExp` for that, you don't need to check if two numbers are even, you just need to check two constitutive chars (which is numbers) are even. so for `1234` you don't have to check `12` and `34` in that case the question could have been more complicated (what will be solved here). you just need to check [`1 & 2`], [`2 & 3`], [`3 & 4`] where none of them are even pairs. And we can avoid parsing string and read as number, arithmetic calculation for even,.. and such things. So, for the the simple one (consicutive even chars) Regex for even digit is : `/[02468]/` `<your string>.match(/[02468]{2}/)` would give you the result. Example: ```js function EvenPairs(str) { let evensDigit = '[02468]', consecutiveEvenRegex = new RegExp(evensDigit + "{2}"); return !!str.match(consecutiveEvenRegex); } let str1 = "f178svg3k19k46"; //should be true as 4 then 6 let str2 = "7r5gg812"; // should be false, as 8 -> 1 -> 2 (and not 8 then 12) console.log(`Test EvenPairs for ${str1}: `, EvenPairs(str1)); console.log(`Test EvenPairs for ${str2}: `, EvenPairs(str2)); ``` Now back to the actual (probable) problem to check for 2 constitutive even numbers (not only chars) we just need to check the existence of: `<any even char><empty or 0-9 char><any even char>` i.e. `/[02468][0-9]{0,}[02468]/` let's create a working example for it ```js function EvenPairs(str) { let evenDigit = '[02468]', digitsOrEmpty = '[0-9]{0,}', consecutiveEvenRegex = new RegExp(evenDigit + digitsOrEmpty + evenDigit); return !!str.match(consecutiveEvenRegex); } let str1 = "f178svg3k19k46"; //should be true as 4 then 6 let str2 = "7r5gg812"; // should be true as well, as 8 -> 12 console.log(`Test EvenPairs for ${str1}: `, EvenPairs(str1)); console.log(`Test EvenPairs for ${str2}: `, EvenPairs(str2)); ```
968,806
How can xkb or some other tool be used to permanently bind Caps Lock to `ctrl`+`b` while in terminal? (This is to make `Caps Lock` the default prefix key for tmux. It could also be mapped to a specific key if that's too difficult, e.g. a function key, which could then be made the tmux prefix instead.)
2017/10/24
[ "https://askubuntu.com/questions/968806", "https://askubuntu.com", "https://askubuntu.com/users/40428/" ]
XKB will be appropriate for Xwindows or Wayland GUIs. It will not affect virtual consoles, but GUI terminal emulators will be fine. For XKB background I'll point you to [some (overview, system vs user)](https://askubuntu.com/a/896297/669043) .. [other (custom options)](https://superuser.com/a/1168603/685512) .. [answers (custom rules)](https://unix.stackexchange.com/a/355404/222377). The following will allow you to add a new option like `caps:myf13` to an existing XKB layout with whatever tools you'd normally use (`setxkbmap`, `localectl` settings, GNOME panel, etc). --- ### Defining the option Existing XKB capslock options are listed in `/usr/share/X11/xkb/rules/evdev.lst`. Looking at the corresponding options in the `.../rules/evdev` file, you can see these options are all loaded from the file `.../symbols/capslock`. All of them are modifier keys, which probably aren't the best example, but `caps:backspace` might be a good comparison. Looking at the file, we find the stanza defining this option: ``` hidden partial modifier_keys xkb_symbols "backspace" { key <CAPS> { [ BackSpace ] }; }; ``` `grep`'ing through the other symbol files, we can see that the F13 symbol is simply `F13`. The new option stanza might look like this: ``` hidden partial modifier_keys xkb_symbols "myf13" { key <CAPS> { [ F13 ] }; }; ``` As you can see, we only changed the name of the option and the symbol assigned to the key. --- ### Hooking it up The only thing left to do is hook up the new stanza. On a basic Xwindows system, using commandline tools like `setxkbmap` and `xkbcomp`, a [custom user location](https://askubuntu.com/a/896298/669043) will do fine; for GNOME, KDE or a Wayland system you'll need to make your changes in the system XKB database. As an example for system changes (you will need `sudo` access to create or edit these files): * Place the custom stanza in a new symbol file, eg `/usr/share/X11/xkb/symbols/mycaps`. * Add this to `/usr/share/X11/xkb/rules/evdev` just below the line for `caps:backspace`: ``` caps:myf13 = +mycaps(myf13) ``` * ... add to `/usr/share/X11/xkb/rules/evdev.lst`: ``` caps:myf13 Caps Lock is F13 ``` * ... add to `/usr/share/X11/xkb/rules/evdev.xml`: ``` <option> <configItem> <name>caps:myf13</name> <description>Caps Lock is F13</description> </configItem> </option> ``` * Finally, make backups of your `.../rules/evdev*` files, or create a patch file. Your changes will be overwritten whenever the `xkb-data` package is updated. If you saved your modification stanza into the `.../symbols/capslock` file, it will need to be backed up as well. Once these changes are made, you should be able to set this option as if it were any other XKB option. You may need to restart any GNOME/KDE session for control panels to pick up the changes, but tools like `setxkbmap` should find it immediately: `setxkbmap -option caps:myf13`
I upvoted @quixotic, but the method is too difficult, and you need to do it again and again. Because: > > Your changes will be overwritten whenever the xkb-data package is > updated. > > > Finally, savior came out, simply: 1. Install `input-remapper` 2. Click, Click! Done! <https://github.com/sezanzeb/input-remapper> By the way, if you are on Arch Linux, just `yay -S input-remapper-git`
5,216,370
So my problem is simple, the data i am initalizing in my constructor is not saving at all. basically I have pin pointed to this one point. I have a constructor in a class ``` strSet::strSet(std::string s){ std::vector<std::string> strVector; strVector.push_back(s); } ``` and in my main file i have ``` else if(command == "s"){ cout << "Declare (to be singleton). Give set element:"; cin >> input >> single_element; vector_info temp; temp.name = input; strSet set(single_element); set.output(); temp.vector = set; list.push_back(temp); } ``` when my constructor is called and i check the length of my vector the answer is appropriate, but then when i check the length of my vector in output, it resets to 0? can anyone help me, much appreciated!!!!!!! EDIT this is my .h file ``` class strSet { private: std::vector<std::string> strVector; // This is initially empty (when constructed) bool isSorted () const; public: strSet (); // Create empty set strSet (std::string s); // Create singleton set void nullify (); // Make a set be empty bool isNull () const; int SIZE() const; void output() const; bool isMember (std::string s) const; strSet operator + (const strSet& rtSide); // Union strSet operator * (const strSet& rtSide); // Intersection strSet operator - (const strSet& rtSide); // Set subtraction strSet& operator = (const strSet& rtSide); // Assignment }; // End of strSet class ```
2011/03/07
[ "https://Stackoverflow.com/questions/5216370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647682/" ]
``` strSet::strSet(std::string s){ std::vector<std::string> strVector; //line 1 strVector.push_back(s); //line 2 } ``` This is your constructor, and here you're storing the value in the local vector which gets destroyed on returning from the constructor. How do you expect your data to be saved in strSet? I believe you need to know the basic of C++ and class, by reading an introductory C++ book yourself. So please get a book and read it first; here is a list of really good books: [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) EDIT: If you've declared `strVector` as class member, then you need to remove the `line 1`. Then it will work.
``` std::vector<std::string> strVector; strVector.push_back(s); ``` That creates a new local vector of strings in your constructor and adds a string to it. When the constructor exits, it will destroy your vector. If you want strVector to last longer than the constructor, make it a class member.
5,216,370
So my problem is simple, the data i am initalizing in my constructor is not saving at all. basically I have pin pointed to this one point. I have a constructor in a class ``` strSet::strSet(std::string s){ std::vector<std::string> strVector; strVector.push_back(s); } ``` and in my main file i have ``` else if(command == "s"){ cout << "Declare (to be singleton). Give set element:"; cin >> input >> single_element; vector_info temp; temp.name = input; strSet set(single_element); set.output(); temp.vector = set; list.push_back(temp); } ``` when my constructor is called and i check the length of my vector the answer is appropriate, but then when i check the length of my vector in output, it resets to 0? can anyone help me, much appreciated!!!!!!! EDIT this is my .h file ``` class strSet { private: std::vector<std::string> strVector; // This is initially empty (when constructed) bool isSorted () const; public: strSet (); // Create empty set strSet (std::string s); // Create singleton set void nullify (); // Make a set be empty bool isNull () const; int SIZE() const; void output() const; bool isMember (std::string s) const; strSet operator + (const strSet& rtSide); // Union strSet operator * (const strSet& rtSide); // Intersection strSet operator - (const strSet& rtSide); // Set subtraction strSet& operator = (const strSet& rtSide); // Assignment }; // End of strSet class ```
2011/03/07
[ "https://Stackoverflow.com/questions/5216370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647682/" ]
looks, like your class body already has strVector, so you was declaring it again in constructor, which was wrong, because compiler referenced your new local strVector and not class strVector. you need to change constructor to: ``` strSet::strSet(std::string s){ strVector.push_back(s); } ```
``` std::vector<std::string> strVector; strVector.push_back(s); ``` That creates a new local vector of strings in your constructor and adds a string to it. When the constructor exits, it will destroy your vector. If you want strVector to last longer than the constructor, make it a class member.
5,216,370
So my problem is simple, the data i am initalizing in my constructor is not saving at all. basically I have pin pointed to this one point. I have a constructor in a class ``` strSet::strSet(std::string s){ std::vector<std::string> strVector; strVector.push_back(s); } ``` and in my main file i have ``` else if(command == "s"){ cout << "Declare (to be singleton). Give set element:"; cin >> input >> single_element; vector_info temp; temp.name = input; strSet set(single_element); set.output(); temp.vector = set; list.push_back(temp); } ``` when my constructor is called and i check the length of my vector the answer is appropriate, but then when i check the length of my vector in output, it resets to 0? can anyone help me, much appreciated!!!!!!! EDIT this is my .h file ``` class strSet { private: std::vector<std::string> strVector; // This is initially empty (when constructed) bool isSorted () const; public: strSet (); // Create empty set strSet (std::string s); // Create singleton set void nullify (); // Make a set be empty bool isNull () const; int SIZE() const; void output() const; bool isMember (std::string s) const; strSet operator + (const strSet& rtSide); // Union strSet operator * (const strSet& rtSide); // Intersection strSet operator - (const strSet& rtSide); // Set subtraction strSet& operator = (const strSet& rtSide); // Assignment }; // End of strSet class ```
2011/03/07
[ "https://Stackoverflow.com/questions/5216370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647682/" ]
Tip: GCC has a compiler warning for this. Use -Wshadow to catch such problems in the future.
``` std::vector<std::string> strVector; strVector.push_back(s); ``` That creates a new local vector of strings in your constructor and adds a string to it. When the constructor exits, it will destroy your vector. If you want strVector to last longer than the constructor, make it a class member.
5,216,370
So my problem is simple, the data i am initalizing in my constructor is not saving at all. basically I have pin pointed to this one point. I have a constructor in a class ``` strSet::strSet(std::string s){ std::vector<std::string> strVector; strVector.push_back(s); } ``` and in my main file i have ``` else if(command == "s"){ cout << "Declare (to be singleton). Give set element:"; cin >> input >> single_element; vector_info temp; temp.name = input; strSet set(single_element); set.output(); temp.vector = set; list.push_back(temp); } ``` when my constructor is called and i check the length of my vector the answer is appropriate, but then when i check the length of my vector in output, it resets to 0? can anyone help me, much appreciated!!!!!!! EDIT this is my .h file ``` class strSet { private: std::vector<std::string> strVector; // This is initially empty (when constructed) bool isSorted () const; public: strSet (); // Create empty set strSet (std::string s); // Create singleton set void nullify (); // Make a set be empty bool isNull () const; int SIZE() const; void output() const; bool isMember (std::string s) const; strSet operator + (const strSet& rtSide); // Union strSet operator * (const strSet& rtSide); // Intersection strSet operator - (const strSet& rtSide); // Set subtraction strSet& operator = (const strSet& rtSide); // Assignment }; // End of strSet class ```
2011/03/07
[ "https://Stackoverflow.com/questions/5216370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647682/" ]
``` strSet::strSet(std::string s){ std::vector<std::string> strVector; //line 1 strVector.push_back(s); //line 2 } ``` This is your constructor, and here you're storing the value in the local vector which gets destroyed on returning from the constructor. How do you expect your data to be saved in strSet? I believe you need to know the basic of C++ and class, by reading an introductory C++ book yourself. So please get a book and read it first; here is a list of really good books: [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) EDIT: If you've declared `strVector` as class member, then you need to remove the `line 1`. Then it will work.
You're initializing a stack local variable in your `strSet::strSet` constructor. When you are returning from your constructor, all stack local variables are destroyed. The way to fix this would be to declare the `strVector` variable as a class member variable. An example: ``` class strSet { public: strSet(std::string s) { this->strVector.push_back(s); } private: std::vector<std::string> strVector; }; ```
5,216,370
So my problem is simple, the data i am initalizing in my constructor is not saving at all. basically I have pin pointed to this one point. I have a constructor in a class ``` strSet::strSet(std::string s){ std::vector<std::string> strVector; strVector.push_back(s); } ``` and in my main file i have ``` else if(command == "s"){ cout << "Declare (to be singleton). Give set element:"; cin >> input >> single_element; vector_info temp; temp.name = input; strSet set(single_element); set.output(); temp.vector = set; list.push_back(temp); } ``` when my constructor is called and i check the length of my vector the answer is appropriate, but then when i check the length of my vector in output, it resets to 0? can anyone help me, much appreciated!!!!!!! EDIT this is my .h file ``` class strSet { private: std::vector<std::string> strVector; // This is initially empty (when constructed) bool isSorted () const; public: strSet (); // Create empty set strSet (std::string s); // Create singleton set void nullify (); // Make a set be empty bool isNull () const; int SIZE() const; void output() const; bool isMember (std::string s) const; strSet operator + (const strSet& rtSide); // Union strSet operator * (const strSet& rtSide); // Intersection strSet operator - (const strSet& rtSide); // Set subtraction strSet& operator = (const strSet& rtSide); // Assignment }; // End of strSet class ```
2011/03/07
[ "https://Stackoverflow.com/questions/5216370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647682/" ]
``` strSet::strSet(std::string s){ std::vector<std::string> strVector; //line 1 strVector.push_back(s); //line 2 } ``` This is your constructor, and here you're storing the value in the local vector which gets destroyed on returning from the constructor. How do you expect your data to be saved in strSet? I believe you need to know the basic of C++ and class, by reading an introductory C++ book yourself. So please get a book and read it first; here is a list of really good books: [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) EDIT: If you've declared `strVector` as class member, then you need to remove the `line 1`. Then it will work.
Tip: GCC has a compiler warning for this. Use -Wshadow to catch such problems in the future.
5,216,370
So my problem is simple, the data i am initalizing in my constructor is not saving at all. basically I have pin pointed to this one point. I have a constructor in a class ``` strSet::strSet(std::string s){ std::vector<std::string> strVector; strVector.push_back(s); } ``` and in my main file i have ``` else if(command == "s"){ cout << "Declare (to be singleton). Give set element:"; cin >> input >> single_element; vector_info temp; temp.name = input; strSet set(single_element); set.output(); temp.vector = set; list.push_back(temp); } ``` when my constructor is called and i check the length of my vector the answer is appropriate, but then when i check the length of my vector in output, it resets to 0? can anyone help me, much appreciated!!!!!!! EDIT this is my .h file ``` class strSet { private: std::vector<std::string> strVector; // This is initially empty (when constructed) bool isSorted () const; public: strSet (); // Create empty set strSet (std::string s); // Create singleton set void nullify (); // Make a set be empty bool isNull () const; int SIZE() const; void output() const; bool isMember (std::string s) const; strSet operator + (const strSet& rtSide); // Union strSet operator * (const strSet& rtSide); // Intersection strSet operator - (const strSet& rtSide); // Set subtraction strSet& operator = (const strSet& rtSide); // Assignment }; // End of strSet class ```
2011/03/07
[ "https://Stackoverflow.com/questions/5216370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647682/" ]
looks, like your class body already has strVector, so you was declaring it again in constructor, which was wrong, because compiler referenced your new local strVector and not class strVector. you need to change constructor to: ``` strSet::strSet(std::string s){ strVector.push_back(s); } ```
You're initializing a stack local variable in your `strSet::strSet` constructor. When you are returning from your constructor, all stack local variables are destroyed. The way to fix this would be to declare the `strVector` variable as a class member variable. An example: ``` class strSet { public: strSet(std::string s) { this->strVector.push_back(s); } private: std::vector<std::string> strVector; }; ```
5,216,370
So my problem is simple, the data i am initalizing in my constructor is not saving at all. basically I have pin pointed to this one point. I have a constructor in a class ``` strSet::strSet(std::string s){ std::vector<std::string> strVector; strVector.push_back(s); } ``` and in my main file i have ``` else if(command == "s"){ cout << "Declare (to be singleton). Give set element:"; cin >> input >> single_element; vector_info temp; temp.name = input; strSet set(single_element); set.output(); temp.vector = set; list.push_back(temp); } ``` when my constructor is called and i check the length of my vector the answer is appropriate, but then when i check the length of my vector in output, it resets to 0? can anyone help me, much appreciated!!!!!!! EDIT this is my .h file ``` class strSet { private: std::vector<std::string> strVector; // This is initially empty (when constructed) bool isSorted () const; public: strSet (); // Create empty set strSet (std::string s); // Create singleton set void nullify (); // Make a set be empty bool isNull () const; int SIZE() const; void output() const; bool isMember (std::string s) const; strSet operator + (const strSet& rtSide); // Union strSet operator * (const strSet& rtSide); // Intersection strSet operator - (const strSet& rtSide); // Set subtraction strSet& operator = (const strSet& rtSide); // Assignment }; // End of strSet class ```
2011/03/07
[ "https://Stackoverflow.com/questions/5216370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647682/" ]
Tip: GCC has a compiler warning for this. Use -Wshadow to catch such problems in the future.
You're initializing a stack local variable in your `strSet::strSet` constructor. When you are returning from your constructor, all stack local variables are destroyed. The way to fix this would be to declare the `strVector` variable as a class member variable. An example: ``` class strSet { public: strSet(std::string s) { this->strVector.push_back(s); } private: std::vector<std::string> strVector; }; ```
5,216,370
So my problem is simple, the data i am initalizing in my constructor is not saving at all. basically I have pin pointed to this one point. I have a constructor in a class ``` strSet::strSet(std::string s){ std::vector<std::string> strVector; strVector.push_back(s); } ``` and in my main file i have ``` else if(command == "s"){ cout << "Declare (to be singleton). Give set element:"; cin >> input >> single_element; vector_info temp; temp.name = input; strSet set(single_element); set.output(); temp.vector = set; list.push_back(temp); } ``` when my constructor is called and i check the length of my vector the answer is appropriate, but then when i check the length of my vector in output, it resets to 0? can anyone help me, much appreciated!!!!!!! EDIT this is my .h file ``` class strSet { private: std::vector<std::string> strVector; // This is initially empty (when constructed) bool isSorted () const; public: strSet (); // Create empty set strSet (std::string s); // Create singleton set void nullify (); // Make a set be empty bool isNull () const; int SIZE() const; void output() const; bool isMember (std::string s) const; strSet operator + (const strSet& rtSide); // Union strSet operator * (const strSet& rtSide); // Intersection strSet operator - (const strSet& rtSide); // Set subtraction strSet& operator = (const strSet& rtSide); // Assignment }; // End of strSet class ```
2011/03/07
[ "https://Stackoverflow.com/questions/5216370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647682/" ]
looks, like your class body already has strVector, so you was declaring it again in constructor, which was wrong, because compiler referenced your new local strVector and not class strVector. you need to change constructor to: ``` strSet::strSet(std::string s){ strVector.push_back(s); } ```
Tip: GCC has a compiler warning for this. Use -Wshadow to catch such problems in the future.
37,414,994
I am looking for a way to stop a higher-level function after evaluating part of its input sequence. Consider a situation when you look for the first index in a sequence that satisfies a certain condition. For example, let's say we are looking for the first position in an array `a` of `Int`s where the sum of two consecutive values is above 100. You can do it with a loop, like this: ``` func firstAbove100(a:[Int]) -> Int? { if a.count < 2 { return nil } for i in 0..<a.count-1 { if a[i]+a[i+1] > 100 { return i } } return nil } ``` The looping stops as soon as the position of interest is discovered. We can rewrite this code using `reduce` as follows: ``` func firstAbove100(a:[Int]) -> Int? { if a.count < 2 { return nil } return (0..<a.count-1).reduce(nil) { prev, i in prev ?? (a[i]+a[i+1] > 100 ? i : nil) } } ``` However, the disadvantage of this approach is that `reduce` goes all the way up to `a.count-2` even if it finds a match at the very first index. The result is going to be the same, but it would be nice to cut the unnecessary work. Is there a way to make `reduce` stop trying further matches, or perhaps a different function that lets you stop after finding the first match?
2016/05/24
[ "https://Stackoverflow.com/questions/37414994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/335858/" ]
The issue with your code lies in `readingTheFile()`: This is the return-statement: ``` return null; ``` Which - Captain Obvious here - returns `null`. Thus `secret` is `null` and the `IllegalArgumentException` is thrown. If you absolutely want to stick to the `BufferedReader`-solution, this should solve the problem: ``` byte[] readingTheFile(){ byte[] result = null; try(BufferedReader br = new BufferedReader(new FileReader(path))){ StringBuilder sb = new StringBuilder(); String line; while((line = br.readLine()) != null) sb.append(line).append(System.getProperty("line.separator")); result = sb.toString().getBytes(); }catch(IOException e){ e.printStackTrace(); } return result; ``` } Some general advice: `BufferedReader` isn't built for the purpose of reading a file `byte` for `byte` anyways. E.g. `'\n'` will be ignored, since you're reading line-wise. This may cause you to corrupt data while loading. Next problem: you're only closing the `FileReader` in `readingTheFile()`, but not the `BufferedReader`. **Always** close the ToplevelReader, not the underlying one. By using `try-with-resources`, you're saving yourself quite some work and the danger of leaving the `FileReader` open, if something is coded improperly. If you want to read the bytes from a file, use `FileReader` instead. That'll allow you to load the entire file as `byte[]`: ``` byte[] readingTheFile(){ byte[] result = new byte[new File(path).length()]; try(FileReader fr = new FileReader(path)){ fr.read(result , result.length); }catch(IOException e){ e.printStackTrace(); } return result; } ``` Or alternatively and even simpler: use `java.nio` ``` byte[] readingTheFile(){ try{ return Files.readAllBytes(FileSystem.getDefault().getPath(path)); }catch(IOException e){ e.printStackTrace(); return null; } } ```
Change your Class "File" like below, this is how it will provide you the desire mechanism. I've modified the same class you have written. ``` public class File { public byte[] readingTheFile() throws IOException { java.io.File file = new java.io.File("/Users/user/Desktop/altiy.pdf"); /*FileReader in = new FileReader("/Users/user/Desktop/altiy.pdf"); BufferedReader br = new BufferedReader(in); String line; while ((line = br.readLine()) != null) { System.out.println(line); } in.close(); */ FileInputStream fin = null; try { // create FileInputStream object fin = new FileInputStream(file); byte fileContent[] = new byte[(int) file.length()]; // Reads bytes of data from this input stream into an array of // bytes. fin.read(fileContent); // returning the file content in form of byte array return fileContent; } catch (FileNotFoundException e) { System.out.println("File not found" + e); } catch (IOException ioe) { System.out.println("Exception while reading file " + ioe); } finally { // close the streams using close method try { if (fin != null) { fin.close(); } } catch (IOException ioe) { System.out.println("Error while closing stream: " + ioe); } } return null; } } ```
45,714,606
Usually the question is for the main thread to wait for child thread which I can use `await` on the `Task`. But I have a situation where the child thread must wait for some method in the main thread to complete before continuing. How to make this communication possible? ``` public void MainThread() { Task t = Task.Run(ChildThread); //not using await because we want to continue doing work that must be only on the main thread WorkA(); WorkB(); ??? WorkC(); } public async Task ChildThread() { WorkD(); ??? Need_WorkB_ToBeCompletedBeforeThisOne(); } ``` `WorkA` `WorkB` `WorkC` are all necessary to be on the main thread. All of them would be issue indirectly from the child thread in my real code because child thread need them done but could not do it because of thread restriction. I have a way for my child thread to tell main thread to do work already (so I simplify the code to what you see here, as soon as the task start the work will immediately follows) but I need some way for the issuer (child thread) to know about the progress of those commands. PS. Thanks to answers from this thread I have created `CoroutineHost` for Unity, which you are able to `await` the `yield IEnumerator` method that you can issue to your main thread to do from any of your child threads : <https://github.com/5argon/E7Unity/tree/master/CoroutineHost>
2017/08/16
[ "https://Stackoverflow.com/questions/45714606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/862147/" ]
You're looking for a "signal". Since the child is asynchronous and the signal is used only one time, a `TaskCompletionSource<T>` would work nicely: ``` public void MainThread() { var tcs = new TaskCompletionSource<object>(); // Create the signal Task t = Task.Run(() => ChildThread(tcs.Task)); // Pass the "receiver" end to ChildThread WorkA(); WorkB(); tcs.SetResult(null); // Send the signal WorkC(); } public async Task ChildThread(Task workBCompleted) { WorkD(); await workBCompleted; // (asynchronously) wait for the signal to be sent Need_WorkB_ToBeCompletedBeforeThisOne(); } ``` See recipe 11.4 "Async Signals" in [my book](https://stephencleary.com/book/) for more information. If you need a "signal" that can become set and unset multiple times, then you should use [`AsyncManualResetEvent`](https://github.com/StephenCleary/AsyncEx).
I would imagine something like this if WorkB was a Task: ``` public void MainThread() { Task workB = WorkB(); ChildThread(workB); // you don't need to use Task.Run here, the task is ran automatically WorkA(); WorkC(); } public async Task ChildThread(Task otherTaskToWait) { WorkD(); await otherTaskToWait; Need_WorkB_ToBeCompletedBeforeThisOne(); } ```
65,477,564
In `opentelemetery-api` version `0.8.0`, we used to set a new `SpanContext` in current `Context` via following code: ```scala TracingContextUtils.currentContextWith(DefaultSpan.create(newSpanCtx)) ``` However, in version `0.13.1`, both - `TracingContextUtils` and `DefaultSpan` are removed. Then how can I set a new `SpanContext` in the current `Context`?
2020/12/28
[ "https://Stackoverflow.com/questions/65477564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3620633/" ]
From [opentelemetry-java](https://github.com/open-telemetry/opentelemetry-java) version [0.10.0 release notes](https://github.com/open-telemetry/opentelemetry-java/releases/tag/v0.10.0): > > * `TracingContextUtils` and `BaggageUtils` were removed from the public API. Instead, use the appropriate static methods on the `Span` and `Baggage` classes, or use methods on the `Context` itself. > * `DefaultSpan` was removed from the public API. Instead, use `Span.wrap(spanContext)` if you need a non-functional span that propagates the trace context. > > > You can try something like: ```scala val newSpanCtx: SpanContext = null val span: Span = Span.wrap(newSpanCtx) Context.current().`with`(span).makeCurrent() ```
How about using the `scope` and calling the `makeCurrent` method? ```java Span span = tracer.spanBuilder("my span").startSpan(); // put the span into the current Context try (Scope scope = span.makeCurrent()) { // your use case ... } catch (Throwable t) { span.setStatus(StatusCode.ERROR, "Change it to your error message"); } finally { span.end(); // closing the scope does not end the span, this has to be done manually } ``` This is what the [quickstart](https://github.com/open-telemetry/opentelemetry-java/blob/master/QUICKSTART.md) also states.
37,651,258
I try to make WebApp using php & R . this is my php code: ``` exec("/usr/bin/Rscript /home/bella/Downloads/htdocs/laut/script.r $N"); $nocache = rand(); echo("<img src='tmp.png?$nocache' />"); ``` And this is my script.r code: ``` slices <- c(10, 12,4, 16, 8) lbls <- c("US", "UK", "Australia", "Germany", "France") png(filename="tmp.png", width=600, height=600) pie(slices, labels = lbls, main="Pie Chart of Countries") dev.off() ``` Everything work fine. Then, i change slices data and store it in csv. I change script.r code: ``` setwd("/home/bella/Downloads/DATA") slices<-read.csv("country.csv",header=T,sep=";",dec=",") lbls <- c("US", "UK", "Australia", "Germany", "France") png(filename="tmp.png", width=600, height=600) pie(as.matrix(slices), labels = lbls, main="Pie Chart of Countries") dev.off() ``` I run it, but tmp.png file not updated. It seem that my R code "`setwd`" and "`read.csv`" didn't run. (i try both script in R and running well) Why this happen? How to get data from csv file using R script in php?
2016/06/06
[ "https://Stackoverflow.com/questions/37651258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6428913/" ]
> > Note: If you want to convert a callback API to promises see [this question](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises). > > > Let's start with something that should be said from the get go. An executor is *not* required in order to design promises. It is *entirely* possible to design a promises implementation that does something like: ``` let {promise, resolve, reject} = Promise.get(); ``` If you promise not to tell anyone, I'll even let you in on a little secret - this API even exists from a previous iteration of the spec and in fact even still works in Chrome: ``` let {promise, resolve, reject} = Promise.defer(); ``` However, it is being removed. ### So, why do I need to pass an executor? I [just answered your other question](https://stackoverflow.com/questions/37651780/why-does-the-promise-constructor-need-an-executor) about why an executor is an interesting design. It's throw-safe and it lets you take care of interesting things. ### Can I still get the resolve, reject functions? I need those In my experience, most of the times I *needed* resolve/reject I didn't *actually* need them. That said - I did in fact actually *need* them a couple of times. The specifiers recognized this and for this reason the executor function *is always run synchronously*. You can get the `.defer` interface it just isn't the default: ``` function defer() { let resolve, reject, promise = new Promise((res, rej) => { [resolve, reject] = [res, rej]; }); return {resolve, reject, promise}; } ``` Again, this is *typically* not something you want to do but it is *entirely possible* that you have a justifiable use case which is why it's not the default but completely possible. ### Your actual code I would start with implementing things like timeout and a request as primitives and then compose functions and chain promises: ``` function delay(ms) { return new Promise(r => setTimeout(r, ms)); } function timeout(promise, ms) { return Promise.race([ promise, delay(ms).then(x => { throw new Error("timeout"); }) ]); } function ajax(url) { // note browsers do this natively with `fetch` today return new Promise((resolve, reject) => { // handle errors! makeAjaxRequest(url, (result) => { // if(result.isFailure) reject(...); if(result.status >= 400) reject(new Error(result.status)); else resolve(result.data); }); }); } ``` Now when we promisified *the lowest level API surface* we can write the above code quite declaratively: ``` function getDetails (someHash) { var ajax = makeAjaxRequest("http://somewebsite.com/" + someHash); return timeout(ajax, 500); } ```
You need to pass a function to the `Promise` constructor ([more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)), which will get called to provide the `resolve` and `reject` functions: ``` function getDetails (someHash) { var url = "http://somewebsite.com/" + someHash; return new Promise(function(resolve, reject) { makeAjaxRequest(url, function(err, response) { if (err) reject(err); else resolve(response.data); }); setTimeout(function () { reject("timeout"); }, 500); }); } function makeAjaxRequest (url, callback) { var someResponse = {data: "some data"}; setTimeout(function () { callback(null, someResponse); }, 200); } ``` I've also taken the liberty to make `makeAjaxRequest` use the standard convention of passing errors as first argument (because I assume that at some point you want to replace the `setTimeout()` with an actual AJAX request).
444,871
Using a stand alone Windows Server 2012 Standard edition (no Active Directory), I succeded to add a new rule to allow sql server connection, by entering the .exe file When I edited the rule property to specify the port number, text zones for ports are greyed and no way to write in them. Is there a new feature in Windows Server 2012 that by default disables port numbers editing ? Any advices please ?
2012/11/02
[ "https://serverfault.com/questions/444871", "https://serverfault.com", "https://serverfault.com/users/140342/" ]
setfacl on linux has the `-d` and `-k` options for manipulating default permissions which are probably what you are looking for (see man for more info).
It is easy to recursively set simple UNIX permissions at upon demand of an appropriately authorized user, the permissions of directories and files. It is not possible to automatically impose this. You could tell users to use the set the umask of 0002, and that helps to make new files at 0775 (depending on the application). But it is not enforcable. My understanding is that ACLs are not inherited on UNIX/Linux systems. They are set upon demand. As for file/directory ownership, you are pretty much out of luck here. As for file/directory group ownership, by setting the directory set-gid bit (i.e. g+s on DIRECTORIES), this does cause the group ownership to be inherited. What I have done in such situations is to execute a periodic root cron script which resets non-conforming permissions/ownerships to the standard in such directories. Another (NOT RECOMMENDED) process is to have the same user-id be used when working on these files. This could be accomplished by the user logging into the system under his own UID, and then using sudo or su to run as the id. This still is not 100% especially concerning ACLs and permission bits.
444,871
Using a stand alone Windows Server 2012 Standard edition (no Active Directory), I succeded to add a new rule to allow sql server connection, by entering the .exe file When I edited the rule property to specify the port number, text zones for ports are greyed and no way to write in them. Is there a new feature in Windows Server 2012 that by default disables port numbers editing ? Any advices please ?
2012/11/02
[ "https://serverfault.com/questions/444871", "https://serverfault.com", "https://serverfault.com/users/140342/" ]
I actually found something that so far does what I asked for, sharing here so anyone who runs into this issue can try out this solution: ``` sudo setfacl -Rdm g:groupnamehere:rwx /base/path/members/ sudo setfacl -Rm g:groupnamehere:rwx /base/path/members/ ``` **R** is recursive, which means everything under that directory will have the rule applied to it. **d** is default, which means for all future items created under that directory, have these rules apply by default. **m** is needed to add/modify rules. The first command, is for new items (hence the d), the second command, is for old/existing items under the folder. Hope this helps someone out as this stuff is a bit complicated and not very intuitive.
It is easy to recursively set simple UNIX permissions at upon demand of an appropriately authorized user, the permissions of directories and files. It is not possible to automatically impose this. You could tell users to use the set the umask of 0002, and that helps to make new files at 0775 (depending on the application). But it is not enforcable. My understanding is that ACLs are not inherited on UNIX/Linux systems. They are set upon demand. As for file/directory ownership, you are pretty much out of luck here. As for file/directory group ownership, by setting the directory set-gid bit (i.e. g+s on DIRECTORIES), this does cause the group ownership to be inherited. What I have done in such situations is to execute a periodic root cron script which resets non-conforming permissions/ownerships to the standard in such directories. Another (NOT RECOMMENDED) process is to have the same user-id be used when working on these files. This could be accomplished by the user logging into the system under his own UID, and then using sudo or su to run as the id. This still is not 100% especially concerning ACLs and permission bits.
444,871
Using a stand alone Windows Server 2012 Standard edition (no Active Directory), I succeded to add a new rule to allow sql server connection, by entering the .exe file When I edited the rule property to specify the port number, text zones for ports are greyed and no way to write in them. Is there a new feature in Windows Server 2012 that by default disables port numbers editing ? Any advices please ?
2012/11/02
[ "https://serverfault.com/questions/444871", "https://serverfault.com", "https://serverfault.com/users/140342/" ]
To go with your accepted answer ... You can combine those commands together as: ``` sudo setfacl -Rm d:g:groupnamehere:rwx,g:groupnamehere:rwx /base/path/members/ ```
It is easy to recursively set simple UNIX permissions at upon demand of an appropriately authorized user, the permissions of directories and files. It is not possible to automatically impose this. You could tell users to use the set the umask of 0002, and that helps to make new files at 0775 (depending on the application). But it is not enforcable. My understanding is that ACLs are not inherited on UNIX/Linux systems. They are set upon demand. As for file/directory ownership, you are pretty much out of luck here. As for file/directory group ownership, by setting the directory set-gid bit (i.e. g+s on DIRECTORIES), this does cause the group ownership to be inherited. What I have done in such situations is to execute a periodic root cron script which resets non-conforming permissions/ownerships to the standard in such directories. Another (NOT RECOMMENDED) process is to have the same user-id be used when working on these files. This could be accomplished by the user logging into the system under his own UID, and then using sudo or su to run as the id. This still is not 100% especially concerning ACLs and permission bits.
444,871
Using a stand alone Windows Server 2012 Standard edition (no Active Directory), I succeded to add a new rule to allow sql server connection, by entering the .exe file When I edited the rule property to specify the port number, text zones for ports are greyed and no way to write in them. Is there a new feature in Windows Server 2012 that by default disables port numbers editing ? Any advices please ?
2012/11/02
[ "https://serverfault.com/questions/444871", "https://serverfault.com", "https://serverfault.com/users/140342/" ]
I actually found something that so far does what I asked for, sharing here so anyone who runs into this issue can try out this solution: ``` sudo setfacl -Rdm g:groupnamehere:rwx /base/path/members/ sudo setfacl -Rm g:groupnamehere:rwx /base/path/members/ ``` **R** is recursive, which means everything under that directory will have the rule applied to it. **d** is default, which means for all future items created under that directory, have these rules apply by default. **m** is needed to add/modify rules. The first command, is for new items (hence the d), the second command, is for old/existing items under the folder. Hope this helps someone out as this stuff is a bit complicated and not very intuitive.
setfacl on linux has the `-d` and `-k` options for manipulating default permissions which are probably what you are looking for (see man for more info).
444,871
Using a stand alone Windows Server 2012 Standard edition (no Active Directory), I succeded to add a new rule to allow sql server connection, by entering the .exe file When I edited the rule property to specify the port number, text zones for ports are greyed and no way to write in them. Is there a new feature in Windows Server 2012 that by default disables port numbers editing ? Any advices please ?
2012/11/02
[ "https://serverfault.com/questions/444871", "https://serverfault.com", "https://serverfault.com/users/140342/" ]
To go with your accepted answer ... You can combine those commands together as: ``` sudo setfacl -Rm d:g:groupnamehere:rwx,g:groupnamehere:rwx /base/path/members/ ```
setfacl on linux has the `-d` and `-k` options for manipulating default permissions which are probably what you are looking for (see man for more info).
444,871
Using a stand alone Windows Server 2012 Standard edition (no Active Directory), I succeded to add a new rule to allow sql server connection, by entering the .exe file When I edited the rule property to specify the port number, text zones for ports are greyed and no way to write in them. Is there a new feature in Windows Server 2012 that by default disables port numbers editing ? Any advices please ?
2012/11/02
[ "https://serverfault.com/questions/444871", "https://serverfault.com", "https://serverfault.com/users/140342/" ]
I actually found something that so far does what I asked for, sharing here so anyone who runs into this issue can try out this solution: ``` sudo setfacl -Rdm g:groupnamehere:rwx /base/path/members/ sudo setfacl -Rm g:groupnamehere:rwx /base/path/members/ ``` **R** is recursive, which means everything under that directory will have the rule applied to it. **d** is default, which means for all future items created under that directory, have these rules apply by default. **m** is needed to add/modify rules. The first command, is for new items (hence the d), the second command, is for old/existing items under the folder. Hope this helps someone out as this stuff is a bit complicated and not very intuitive.
To go with your accepted answer ... You can combine those commands together as: ``` sudo setfacl -Rm d:g:groupnamehere:rwx,g:groupnamehere:rwx /base/path/members/ ```
20,749,660
Using a Perl regex, I need to match a series of eight digits, for example, 12345678, but only if they are not all the same. 00000000 and 99999999 are typical patterns that should not match. I'm trying to weed out obviously invalid values from existing database records. I've got this: ``` my ($match) = /(\d{8})/; ``` But I can't quite get the backref arranged right.
2013/12/23
[ "https://Stackoverflow.com/questions/20749660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2321898/" ]
How about: ``` ^(\d)(?!\1{7})\d{7}$ ``` This will match 8 digit number that haven't 8 same digit. **Sample code:** ``` my $re = qr/^(\d)(?!\1{7})\d{7}$/; while(<DATA>) { chomp; say (/$re/ ? "OK : $_" : "KO : $_"); } __DATA__ 12345678 12345123 123456 11111111 ``` **Output:** ``` OK : 12345678 OK : 12345123 KO : 123456 KO : 11111111 ``` **Explanation:** ``` The regular expression: (?-imsx:^(\d)(?!\1{7})\d{7}$) matches as follows: NODE EXPLANATION ---------------------------------------------------------------------- (?-imsx: group, but do not capture (case-sensitive) (with ^ and $ matching normally) (with . not matching \n) (matching whitespace and # normally): ---------------------------------------------------------------------- ^ the beginning of the string ---------------------------------------------------------------------- ( group and capture to \1: ---------------------------------------------------------------------- \d digits (0-9) ---------------------------------------------------------------------- ) end of \1 ---------------------------------------------------------------------- (?! look ahead to see if there is not: ---------------------------------------------------------------------- \1{7} what was matched by capture \1 (7 times) ---------------------------------------------------------------------- ) end of look-ahead ---------------------------------------------------------------------- \d{7} digits (0-9) (7 times) ---------------------------------------------------------------------- $ before an optional \n, and the end of the string ---------------------------------------------------------------------- ) end of grouping ---------------------------------------------------------------------- ```
> > This answer is **based** on the title of the question: *match **n** digits, but only if they are not all the same*. > > > --- So I've come with the following expression: ``` (\d)\1+\b(*SKIP)(*FAIL)|\d+ ``` What does this mean ? ``` (\d) # Match a digit and put it in group 1 \1+ # Match what was matched in group 1 and repeat it one or more times \b # Word boundary, we could use (?!\d) to be more specific (*SKIP)(*FAIL) # Skip & fail, we use this to exclude what we just have matched | # Or \d+ # Match a digit one or more times ``` The advantage of this regex is that you don't need to edit it each time you want to change `n`. Of course, if you want to match only `n` digits, you could just replace the last alternation `\d+` with `\d{n}\b`. `[**Online demo**](http://regex101.com/r/jZ7wF8)` `[**SKIP/FAIL reference**](http://perldoc.perl.org/perlre.html#Special-Backtracking-Control-Verbs)`
20,749,660
Using a Perl regex, I need to match a series of eight digits, for example, 12345678, but only if they are not all the same. 00000000 and 99999999 are typical patterns that should not match. I'm trying to weed out obviously invalid values from existing database records. I've got this: ``` my ($match) = /(\d{8})/; ``` But I can't quite get the backref arranged right.
2013/12/23
[ "https://Stackoverflow.com/questions/20749660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2321898/" ]
How about: ``` ^(\d)(?!\1{7})\d{7}$ ``` This will match 8 digit number that haven't 8 same digit. **Sample code:** ``` my $re = qr/^(\d)(?!\1{7})\d{7}$/; while(<DATA>) { chomp; say (/$re/ ? "OK : $_" : "KO : $_"); } __DATA__ 12345678 12345123 123456 11111111 ``` **Output:** ``` OK : 12345678 OK : 12345123 KO : 123456 KO : 11111111 ``` **Explanation:** ``` The regular expression: (?-imsx:^(\d)(?!\1{7})\d{7}$) matches as follows: NODE EXPLANATION ---------------------------------------------------------------------- (?-imsx: group, but do not capture (case-sensitive) (with ^ and $ matching normally) (with . not matching \n) (matching whitespace and # normally): ---------------------------------------------------------------------- ^ the beginning of the string ---------------------------------------------------------------------- ( group and capture to \1: ---------------------------------------------------------------------- \d digits (0-9) ---------------------------------------------------------------------- ) end of \1 ---------------------------------------------------------------------- (?! look ahead to see if there is not: ---------------------------------------------------------------------- \1{7} what was matched by capture \1 (7 times) ---------------------------------------------------------------------- ) end of look-ahead ---------------------------------------------------------------------- \d{7} digits (0-9) (7 times) ---------------------------------------------------------------------- $ before an optional \n, and the end of the string ---------------------------------------------------------------------- ) end of grouping ---------------------------------------------------------------------- ```
``` my $number = "99999999"; # look for first digit, capture, print "ok\n" if $number =~ /(\d)\1{7}/; # use \1{7} to determine 7 matches of captured digit ```
20,749,660
Using a Perl regex, I need to match a series of eight digits, for example, 12345678, but only if they are not all the same. 00000000 and 99999999 are typical patterns that should not match. I'm trying to weed out obviously invalid values from existing database records. I've got this: ``` my ($match) = /(\d{8})/; ``` But I can't quite get the backref arranged right.
2013/12/23
[ "https://Stackoverflow.com/questions/20749660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2321898/" ]
How about: ``` ^(\d)(?!\1{7})\d{7}$ ``` This will match 8 digit number that haven't 8 same digit. **Sample code:** ``` my $re = qr/^(\d)(?!\1{7})\d{7}$/; while(<DATA>) { chomp; say (/$re/ ? "OK : $_" : "KO : $_"); } __DATA__ 12345678 12345123 123456 11111111 ``` **Output:** ``` OK : 12345678 OK : 12345123 KO : 123456 KO : 11111111 ``` **Explanation:** ``` The regular expression: (?-imsx:^(\d)(?!\1{7})\d{7}$) matches as follows: NODE EXPLANATION ---------------------------------------------------------------------- (?-imsx: group, but do not capture (case-sensitive) (with ^ and $ matching normally) (with . not matching \n) (matching whitespace and # normally): ---------------------------------------------------------------------- ^ the beginning of the string ---------------------------------------------------------------------- ( group and capture to \1: ---------------------------------------------------------------------- \d digits (0-9) ---------------------------------------------------------------------- ) end of \1 ---------------------------------------------------------------------- (?! look ahead to see if there is not: ---------------------------------------------------------------------- \1{7} what was matched by capture \1 (7 times) ---------------------------------------------------------------------- ) end of look-ahead ---------------------------------------------------------------------- \d{7} digits (0-9) (7 times) ---------------------------------------------------------------------- $ before an optional \n, and the end of the string ---------------------------------------------------------------------- ) end of grouping ---------------------------------------------------------------------- ```
I'd do this in two regular expressions. One to match what you are looking for, and one to filter what you're not. Inspired by HamZa's answer though, I've also provided a single regex solution. ``` use strict; use warnings; while (my $num = <DATA>) { chomp $num; # Single Regex Solution - Inspired by HamZa's code if ($num =~ /^.*(\d).*\1.*$(*SKIP)(*FAIL)|^\d{8}$/) { print "Yes - "; } else { print "No - "; } # Two Regex Solution if ($num =~ /^\d{8}$/ && $num !~ /(\d).*\1/) { print "Yes - "; } else { print "No - "; } print "$num\n"; } __DATA__ 12345678 12345674 00001111 00000000 99999999 87654321 87654351 123456789 ``` And the results? ``` Yes - Yes - 12345678 No - No - 12345674 No - No - 00001111 No - No - 00000000 No - No - 99999999 Yes - Yes - 87654321 No - No - 87654351 No - No - 123456789 ```
20,749,660
Using a Perl regex, I need to match a series of eight digits, for example, 12345678, but only if they are not all the same. 00000000 and 99999999 are typical patterns that should not match. I'm trying to weed out obviously invalid values from existing database records. I've got this: ``` my ($match) = /(\d{8})/; ``` But I can't quite get the backref arranged right.
2013/12/23
[ "https://Stackoverflow.com/questions/20749660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2321898/" ]
> > This answer is **based** on the title of the question: *match **n** digits, but only if they are not all the same*. > > > --- So I've come with the following expression: ``` (\d)\1+\b(*SKIP)(*FAIL)|\d+ ``` What does this mean ? ``` (\d) # Match a digit and put it in group 1 \1+ # Match what was matched in group 1 and repeat it one or more times \b # Word boundary, we could use (?!\d) to be more specific (*SKIP)(*FAIL) # Skip & fail, we use this to exclude what we just have matched | # Or \d+ # Match a digit one or more times ``` The advantage of this regex is that you don't need to edit it each time you want to change `n`. Of course, if you want to match only `n` digits, you could just replace the last alternation `\d+` with `\d{n}\b`. `[**Online demo**](http://regex101.com/r/jZ7wF8)` `[**SKIP/FAIL reference**](http://perldoc.perl.org/perlre.html#Special-Backtracking-Control-Verbs)`
``` my $number = "99999999"; # look for first digit, capture, print "ok\n" if $number =~ /(\d)\1{7}/; # use \1{7} to determine 7 matches of captured digit ```
20,749,660
Using a Perl regex, I need to match a series of eight digits, for example, 12345678, but only if they are not all the same. 00000000 and 99999999 are typical patterns that should not match. I'm trying to weed out obviously invalid values from existing database records. I've got this: ``` my ($match) = /(\d{8})/; ``` But I can't quite get the backref arranged right.
2013/12/23
[ "https://Stackoverflow.com/questions/20749660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2321898/" ]
I'd do this in two regular expressions. One to match what you are looking for, and one to filter what you're not. Inspired by HamZa's answer though, I've also provided a single regex solution. ``` use strict; use warnings; while (my $num = <DATA>) { chomp $num; # Single Regex Solution - Inspired by HamZa's code if ($num =~ /^.*(\d).*\1.*$(*SKIP)(*FAIL)|^\d{8}$/) { print "Yes - "; } else { print "No - "; } # Two Regex Solution if ($num =~ /^\d{8}$/ && $num !~ /(\d).*\1/) { print "Yes - "; } else { print "No - "; } print "$num\n"; } __DATA__ 12345678 12345674 00001111 00000000 99999999 87654321 87654351 123456789 ``` And the results? ``` Yes - Yes - 12345678 No - No - 12345674 No - No - 00001111 No - No - 00000000 No - No - 99999999 Yes - Yes - 87654321 No - No - 87654351 No - No - 123456789 ```
> > This answer is **based** on the title of the question: *match **n** digits, but only if they are not all the same*. > > > --- So I've come with the following expression: ``` (\d)\1+\b(*SKIP)(*FAIL)|\d+ ``` What does this mean ? ``` (\d) # Match a digit and put it in group 1 \1+ # Match what was matched in group 1 and repeat it one or more times \b # Word boundary, we could use (?!\d) to be more specific (*SKIP)(*FAIL) # Skip & fail, we use this to exclude what we just have matched | # Or \d+ # Match a digit one or more times ``` The advantage of this regex is that you don't need to edit it each time you want to change `n`. Of course, if you want to match only `n` digits, you could just replace the last alternation `\d+` with `\d{n}\b`. `[**Online demo**](http://regex101.com/r/jZ7wF8)` `[**SKIP/FAIL reference**](http://perldoc.perl.org/perlre.html#Special-Backtracking-Control-Verbs)`
20,749,660
Using a Perl regex, I need to match a series of eight digits, for example, 12345678, but only if they are not all the same. 00000000 and 99999999 are typical patterns that should not match. I'm trying to weed out obviously invalid values from existing database records. I've got this: ``` my ($match) = /(\d{8})/; ``` But I can't quite get the backref arranged right.
2013/12/23
[ "https://Stackoverflow.com/questions/20749660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2321898/" ]
I'd do this in two regular expressions. One to match what you are looking for, and one to filter what you're not. Inspired by HamZa's answer though, I've also provided a single regex solution. ``` use strict; use warnings; while (my $num = <DATA>) { chomp $num; # Single Regex Solution - Inspired by HamZa's code if ($num =~ /^.*(\d).*\1.*$(*SKIP)(*FAIL)|^\d{8}$/) { print "Yes - "; } else { print "No - "; } # Two Regex Solution if ($num =~ /^\d{8}$/ && $num !~ /(\d).*\1/) { print "Yes - "; } else { print "No - "; } print "$num\n"; } __DATA__ 12345678 12345674 00001111 00000000 99999999 87654321 87654351 123456789 ``` And the results? ``` Yes - Yes - 12345678 No - No - 12345674 No - No - 00001111 No - No - 00000000 No - No - 99999999 Yes - Yes - 87654321 No - No - 87654351 No - No - 123456789 ```
``` my $number = "99999999"; # look for first digit, capture, print "ok\n" if $number =~ /(\d)\1{7}/; # use \1{7} to determine 7 matches of captured digit ```
731,220
So I have this big file of fix length lines. I want to do a find and replace on a character line position. Example: ``` xxxxxxx 010109 xxxxxx xxxxx xxxxxxx 010309 xxxxxx xxxxx xxxxxxx 021506 xxxxxx xxxxx xxxxxxx 041187 xxxxxx xxxxx ``` So in this case I would want to find any value starting on position 13 through position 18 and replace it with 010107. Can anyone give help me out on how to formulate the regex for this? Much appreciated.
2009/04/08
[ "https://Stackoverflow.com/questions/731220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/88737/" ]
**Edited: after testing, Notepad++ doesn't support the {n} method of defining an exact number of chars** This works, tested on your data: Find: ``` ^(............)...... ``` Replace: ``` \1010107 ```
Try this search pattern: ``` ^(.{12})\d{6} ``` And this as replacement expression: ``` \1010107 ```
731,220
So I have this big file of fix length lines. I want to do a find and replace on a character line position. Example: ``` xxxxxxx 010109 xxxxxx xxxxx xxxxxxx 010309 xxxxxx xxxxx xxxxxxx 021506 xxxxxx xxxxx xxxxxxx 041187 xxxxxx xxxxx ``` So in this case I would want to find any value starting on position 13 through position 18 and replace it with 010107. Can anyone give help me out on how to formulate the regex for this? Much appreciated.
2009/04/08
[ "https://Stackoverflow.com/questions/731220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/88737/" ]
**Edited: after testing, Notepad++ doesn't support the {n} method of defining an exact number of chars** This works, tested on your data: Find: ``` ^(............)...... ``` Replace: ``` \1010107 ```
s/^(?:.{12})(.{6})(?:.\*)$/NNNNNN/ replacing NNNNNN by the desired number
731,220
So I have this big file of fix length lines. I want to do a find and replace on a character line position. Example: ``` xxxxxxx 010109 xxxxxx xxxxx xxxxxxx 010309 xxxxxx xxxxx xxxxxxx 021506 xxxxxx xxxxx xxxxxxx 041187 xxxxxx xxxxx ``` So in this case I would want to find any value starting on position 13 through position 18 and replace it with 010107. Can anyone give help me out on how to formulate the regex for this? Much appreciated.
2009/04/08
[ "https://Stackoverflow.com/questions/731220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/88737/" ]
**Edited: after testing, Notepad++ doesn't support the {n} method of defining an exact number of chars** This works, tested on your data: Find: ``` ^(............)...... ``` Replace: ``` \1010107 ```
Something like this: ``` sed 's/^\(.\{12\}\).\{6\}\(.*\)$/\1010107\2/' ``` should do the trick (escaped for command line use)
731,220
So I have this big file of fix length lines. I want to do a find and replace on a character line position. Example: ``` xxxxxxx 010109 xxxxxx xxxxx xxxxxxx 010309 xxxxxx xxxxx xxxxxxx 021506 xxxxxx xxxxx xxxxxxx 041187 xxxxxx xxxxx ``` So in this case I would want to find any value starting on position 13 through position 18 and replace it with 010107. Can anyone give help me out on how to formulate the regex for this? Much appreciated.
2009/04/08
[ "https://Stackoverflow.com/questions/731220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/88737/" ]
**Edited: after testing, Notepad++ doesn't support the {n} method of defining an exact number of chars** This works, tested on your data: Find: ``` ^(............)...... ``` Replace: ``` \1010107 ```
Just for the record, you don't need a regular expression for something like this. A simple split, or some kind of unpack function, would be just fine.
3,115,810
I would like to use the libical library in my project, but I have never used an external library before. I have downloaded the libical files, but I am pretty much stuck there. I do not how how, or even if, I need to build/extract them and then how to get them into Xcode. Any help would be greatly appreciated. Thank you.
2010/06/25
[ "https://Stackoverflow.com/questions/3115810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172131/" ]
If this a pre-built library then you can just drag it into your Xcode project (or use `Project` => `Add to Project…`) in the same way that you would for source/header files. If it's not pre-built then you'll need to build it for whatever environments and architecture you want to target. If it comes with an Xcode project then this is easy. If it's just the usual open source type of distribution then you usually do something like this: ``` $ ./configure $ ./make $ sudo ./make install ``` That will typically put the built library(ies) and header(s) into somewhere like `/usr/local/lib` and `/usr/local/include`. In your main Xcode project you can then just add these header(s) and library(ies) to your project. Note that if you're cross-compiling, e.g. for iPhone, then you'll need to add some flags to the `./configure` command so that you target the correct architecture, e.g. `./configure -build=arm-apple-darwin9.0.0d1`. Note also that it's usually a good idea to check [MacPorts](http://www.macports.org/) to see if they have already fixed up a given open source project for Mac OS X - this can save you a lot of work. See also [this blog about building and using libical on iPhone](http://ingvar.blog.linpro.no/2008/08/18/how-i-made-the-iphone-sync-my-calendar-over-air/).
Getting libical to configure and build for arm is more tricky then ./configure -build=arm-apple-darwin. See this question and answer for more details: [Compiling libical](https://stackoverflow.com/questions/7197955/compiling-libical)
41,522,744
Trying to bundle the following file with Webpack fails with > > ERROR in ./~/pg/lib/native/index.js Module not found: Error: Cannot > resolve module 'pg-native' in > .../node\_modules/pg/lib/native > @ ./~/pg/lib/native/index.js 9:13-33 > > > I tried several `ignore` statements in the *.babelrc* but didnt get it running... The test-file i want to bundle: *handler.js* ``` const Client = require('pg').Client; console.log("done"); ``` *webpack.config.js* ``` module.exports = { entry: './handler.js', target: 'node', module: { loaders: [{ test: /\.js$/, loaders: ['babel'], include: __dirname, exclude: /node_modules/, }] } }; ``` *.babelrc* ``` { "plugins": ["transform-runtime"], "presets": ["es2015", "stage-1"] } ``` *package.json* ``` "dependencies": { "postgraphql": "^2.4.0", "babel-runtime": "6.11.6" }, "devDependencies": { "babel-core": "^6.13.2", "babel-loader": "^6.2.4", "babel-plugin-transform-runtime": "^6.12.0", "babel-preset-es2015": "^6.13.2", "babel-preset-stage-0": "^6.5.0", "babel-polyfill": "6.13.0", "serverless-webpack": "^1.0.0-rc.3", "webpack": "^1.13.1" } ``` Somewhat related github-issues: * <https://github.com/brianc/node-postgres/issues/1187> * <https://github.com/serverless/serverless-runtime-babel/issues/8>
2017/01/07
[ "https://Stackoverflow.com/questions/41522744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3301344/" ]
This is an old thread but the problem still exists, so for anyone experiencing it, there is a workaround. The problem is an interaction between the way that `node-postgres` is written and how `babel` rewrites the code, which forces `pg-native` to be loaded even when you don't explicitly import/require it. The simplest workaround is to add a couple of aliases to your `webpack.config.js` to cause it to link in a dummy do-nothing file instead: ``` { ... resolve: { alias: { ... 'pg-native': path-to-dummy-js-file, 'dns': path-to-dummy-js-file } } ... } ``` where the dummy file contains a single line: ``` export default null ``` See <https://github.com/brianc/node-postgres/issues/838> for further discussion and alternative workarounds.
You may have pg-native globally installed locally. Hence the packet manager does not include the pg-native in the lock file. That was a issue i experienced where it did run fine locally but every time i build in the cloud webpack complained about pg-native missing. I solved it by removing the lockfile in the files pushed to the cloud (In this case seed.run).
41,522,744
Trying to bundle the following file with Webpack fails with > > ERROR in ./~/pg/lib/native/index.js Module not found: Error: Cannot > resolve module 'pg-native' in > .../node\_modules/pg/lib/native > @ ./~/pg/lib/native/index.js 9:13-33 > > > I tried several `ignore` statements in the *.babelrc* but didnt get it running... The test-file i want to bundle: *handler.js* ``` const Client = require('pg').Client; console.log("done"); ``` *webpack.config.js* ``` module.exports = { entry: './handler.js', target: 'node', module: { loaders: [{ test: /\.js$/, loaders: ['babel'], include: __dirname, exclude: /node_modules/, }] } }; ``` *.babelrc* ``` { "plugins": ["transform-runtime"], "presets": ["es2015", "stage-1"] } ``` *package.json* ``` "dependencies": { "postgraphql": "^2.4.0", "babel-runtime": "6.11.6" }, "devDependencies": { "babel-core": "^6.13.2", "babel-loader": "^6.2.4", "babel-plugin-transform-runtime": "^6.12.0", "babel-preset-es2015": "^6.13.2", "babel-preset-stage-0": "^6.5.0", "babel-polyfill": "6.13.0", "serverless-webpack": "^1.0.0-rc.3", "webpack": "^1.13.1" } ``` Somewhat related github-issues: * <https://github.com/brianc/node-postgres/issues/1187> * <https://github.com/serverless/serverless-runtime-babel/issues/8>
2017/01/07
[ "https://Stackoverflow.com/questions/41522744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3301344/" ]
This is indeed an old thread, but one that helped me nonetheless. The solution provided by Steve Schafer [1](https://stackoverflow.com/a/59652739/2822888) is good, but not the simplest. Instead, the one provided by Marco Lüthy [2](https://github.com/brianc/node-postgres/issues/838#issuecomment-405646013) in the linked issue is probably the easiest to set up because it is pure configuration, without even the need for a dummy file to be created. It consists of modifying your Webpack config `plugins` array as follows: ```js const webpack = require('webpack'); const webpackConfig = { ... resolve: { ... }, plugins: [ new webpack.IgnorePlugin(/^pg-native$/) // Or, for WebPack 4+: new webpack.IgnorePlugin({ resourceRegExp: /^pg-native$/ }) ], output: { ... }, ... } ``` Updated to include a change suggested in the comments.
You may have pg-native globally installed locally. Hence the packet manager does not include the pg-native in the lock file. That was a issue i experienced where it did run fine locally but every time i build in the cloud webpack complained about pg-native missing. I solved it by removing the lockfile in the files pushed to the cloud (In this case seed.run).
41,522,744
Trying to bundle the following file with Webpack fails with > > ERROR in ./~/pg/lib/native/index.js Module not found: Error: Cannot > resolve module 'pg-native' in > .../node\_modules/pg/lib/native > @ ./~/pg/lib/native/index.js 9:13-33 > > > I tried several `ignore` statements in the *.babelrc* but didnt get it running... The test-file i want to bundle: *handler.js* ``` const Client = require('pg').Client; console.log("done"); ``` *webpack.config.js* ``` module.exports = { entry: './handler.js', target: 'node', module: { loaders: [{ test: /\.js$/, loaders: ['babel'], include: __dirname, exclude: /node_modules/, }] } }; ``` *.babelrc* ``` { "plugins": ["transform-runtime"], "presets": ["es2015", "stage-1"] } ``` *package.json* ``` "dependencies": { "postgraphql": "^2.4.0", "babel-runtime": "6.11.6" }, "devDependencies": { "babel-core": "^6.13.2", "babel-loader": "^6.2.4", "babel-plugin-transform-runtime": "^6.12.0", "babel-preset-es2015": "^6.13.2", "babel-preset-stage-0": "^6.5.0", "babel-polyfill": "6.13.0", "serverless-webpack": "^1.0.0-rc.3", "webpack": "^1.13.1" } ``` Somewhat related github-issues: * <https://github.com/brianc/node-postgres/issues/1187> * <https://github.com/serverless/serverless-runtime-babel/issues/8>
2017/01/07
[ "https://Stackoverflow.com/questions/41522744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3301344/" ]
I know that this is an old topic but I'm compelled to share how I solved it. It was maddening to deal with. So, here is the readers digest version as based on the recollection from the last brain cell that I have. --------------------------------------------------------------------------------------------------------- Error: > > Webpack Compilation Error ./node\_modules/pg/lib/native/client.js Module not found: Error: Can't resolve 'pg-native' > > > The error above was thrown when attempting to run a Cypress test that required the npm package 'pg'. Attempting to install the `pg-native package` was not successful and resulted in another error; namely -> > > Call to 'pg\_config --libdir' returned exit status 1 while in binding.gyp. while trying to load binding.gyp > > > I found that executing `pg_config --libdir` in the VSCode cmd prompt resulted in that command failing. However, I knew that it should work since running that command from the system command prompt resulted in this -> `C:/PROGRA~1/POSTGR~1/9.3/lib` That is the path that contains a required dll. So, instead of running `npm install` from the VSCode command prompt, I ran it from the command prompt as launched from windows. The result...success!!! `pg-native` was installed successfully. After, the Cypress test was able to run as well. Errors in now way helped me to arrive at this solution. It was more just checking that things were installed that were required, etc.
You may have pg-native globally installed locally. Hence the packet manager does not include the pg-native in the lock file. That was a issue i experienced where it did run fine locally but every time i build in the cloud webpack complained about pg-native missing. I solved it by removing the lockfile in the files pushed to the cloud (In this case seed.run).
41,522,744
Trying to bundle the following file with Webpack fails with > > ERROR in ./~/pg/lib/native/index.js Module not found: Error: Cannot > resolve module 'pg-native' in > .../node\_modules/pg/lib/native > @ ./~/pg/lib/native/index.js 9:13-33 > > > I tried several `ignore` statements in the *.babelrc* but didnt get it running... The test-file i want to bundle: *handler.js* ``` const Client = require('pg').Client; console.log("done"); ``` *webpack.config.js* ``` module.exports = { entry: './handler.js', target: 'node', module: { loaders: [{ test: /\.js$/, loaders: ['babel'], include: __dirname, exclude: /node_modules/, }] } }; ``` *.babelrc* ``` { "plugins": ["transform-runtime"], "presets": ["es2015", "stage-1"] } ``` *package.json* ``` "dependencies": { "postgraphql": "^2.4.0", "babel-runtime": "6.11.6" }, "devDependencies": { "babel-core": "^6.13.2", "babel-loader": "^6.2.4", "babel-plugin-transform-runtime": "^6.12.0", "babel-preset-es2015": "^6.13.2", "babel-preset-stage-0": "^6.5.0", "babel-polyfill": "6.13.0", "serverless-webpack": "^1.0.0-rc.3", "webpack": "^1.13.1" } ``` Somewhat related github-issues: * <https://github.com/brianc/node-postgres/issues/1187> * <https://github.com/serverless/serverless-runtime-babel/issues/8>
2017/01/07
[ "https://Stackoverflow.com/questions/41522744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3301344/" ]
This is indeed an old thread, but one that helped me nonetheless. The solution provided by Steve Schafer [1](https://stackoverflow.com/a/59652739/2822888) is good, but not the simplest. Instead, the one provided by Marco Lüthy [2](https://github.com/brianc/node-postgres/issues/838#issuecomment-405646013) in the linked issue is probably the easiest to set up because it is pure configuration, without even the need for a dummy file to be created. It consists of modifying your Webpack config `plugins` array as follows: ```js const webpack = require('webpack'); const webpackConfig = { ... resolve: { ... }, plugins: [ new webpack.IgnorePlugin(/^pg-native$/) // Or, for WebPack 4+: new webpack.IgnorePlugin({ resourceRegExp: /^pg-native$/ }) ], output: { ... }, ... } ``` Updated to include a change suggested in the comments.
This is an old thread but the problem still exists, so for anyone experiencing it, there is a workaround. The problem is an interaction between the way that `node-postgres` is written and how `babel` rewrites the code, which forces `pg-native` to be loaded even when you don't explicitly import/require it. The simplest workaround is to add a couple of aliases to your `webpack.config.js` to cause it to link in a dummy do-nothing file instead: ``` { ... resolve: { alias: { ... 'pg-native': path-to-dummy-js-file, 'dns': path-to-dummy-js-file } } ... } ``` where the dummy file contains a single line: ``` export default null ``` See <https://github.com/brianc/node-postgres/issues/838> for further discussion and alternative workarounds.
41,522,744
Trying to bundle the following file with Webpack fails with > > ERROR in ./~/pg/lib/native/index.js Module not found: Error: Cannot > resolve module 'pg-native' in > .../node\_modules/pg/lib/native > @ ./~/pg/lib/native/index.js 9:13-33 > > > I tried several `ignore` statements in the *.babelrc* but didnt get it running... The test-file i want to bundle: *handler.js* ``` const Client = require('pg').Client; console.log("done"); ``` *webpack.config.js* ``` module.exports = { entry: './handler.js', target: 'node', module: { loaders: [{ test: /\.js$/, loaders: ['babel'], include: __dirname, exclude: /node_modules/, }] } }; ``` *.babelrc* ``` { "plugins": ["transform-runtime"], "presets": ["es2015", "stage-1"] } ``` *package.json* ``` "dependencies": { "postgraphql": "^2.4.0", "babel-runtime": "6.11.6" }, "devDependencies": { "babel-core": "^6.13.2", "babel-loader": "^6.2.4", "babel-plugin-transform-runtime": "^6.12.0", "babel-preset-es2015": "^6.13.2", "babel-preset-stage-0": "^6.5.0", "babel-polyfill": "6.13.0", "serverless-webpack": "^1.0.0-rc.3", "webpack": "^1.13.1" } ``` Somewhat related github-issues: * <https://github.com/brianc/node-postgres/issues/1187> * <https://github.com/serverless/serverless-runtime-babel/issues/8>
2017/01/07
[ "https://Stackoverflow.com/questions/41522744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3301344/" ]
This is an old thread but the problem still exists, so for anyone experiencing it, there is a workaround. The problem is an interaction between the way that `node-postgres` is written and how `babel` rewrites the code, which forces `pg-native` to be loaded even when you don't explicitly import/require it. The simplest workaround is to add a couple of aliases to your `webpack.config.js` to cause it to link in a dummy do-nothing file instead: ``` { ... resolve: { alias: { ... 'pg-native': path-to-dummy-js-file, 'dns': path-to-dummy-js-file } } ... } ``` where the dummy file contains a single line: ``` export default null ``` See <https://github.com/brianc/node-postgres/issues/838> for further discussion and alternative workarounds.
I know that this is an old topic but I'm compelled to share how I solved it. It was maddening to deal with. So, here is the readers digest version as based on the recollection from the last brain cell that I have. --------------------------------------------------------------------------------------------------------- Error: > > Webpack Compilation Error ./node\_modules/pg/lib/native/client.js Module not found: Error: Can't resolve 'pg-native' > > > The error above was thrown when attempting to run a Cypress test that required the npm package 'pg'. Attempting to install the `pg-native package` was not successful and resulted in another error; namely -> > > Call to 'pg\_config --libdir' returned exit status 1 while in binding.gyp. while trying to load binding.gyp > > > I found that executing `pg_config --libdir` in the VSCode cmd prompt resulted in that command failing. However, I knew that it should work since running that command from the system command prompt resulted in this -> `C:/PROGRA~1/POSTGR~1/9.3/lib` That is the path that contains a required dll. So, instead of running `npm install` from the VSCode command prompt, I ran it from the command prompt as launched from windows. The result...success!!! `pg-native` was installed successfully. After, the Cypress test was able to run as well. Errors in now way helped me to arrive at this solution. It was more just checking that things were installed that were required, etc.
41,522,744
Trying to bundle the following file with Webpack fails with > > ERROR in ./~/pg/lib/native/index.js Module not found: Error: Cannot > resolve module 'pg-native' in > .../node\_modules/pg/lib/native > @ ./~/pg/lib/native/index.js 9:13-33 > > > I tried several `ignore` statements in the *.babelrc* but didnt get it running... The test-file i want to bundle: *handler.js* ``` const Client = require('pg').Client; console.log("done"); ``` *webpack.config.js* ``` module.exports = { entry: './handler.js', target: 'node', module: { loaders: [{ test: /\.js$/, loaders: ['babel'], include: __dirname, exclude: /node_modules/, }] } }; ``` *.babelrc* ``` { "plugins": ["transform-runtime"], "presets": ["es2015", "stage-1"] } ``` *package.json* ``` "dependencies": { "postgraphql": "^2.4.0", "babel-runtime": "6.11.6" }, "devDependencies": { "babel-core": "^6.13.2", "babel-loader": "^6.2.4", "babel-plugin-transform-runtime": "^6.12.0", "babel-preset-es2015": "^6.13.2", "babel-preset-stage-0": "^6.5.0", "babel-polyfill": "6.13.0", "serverless-webpack": "^1.0.0-rc.3", "webpack": "^1.13.1" } ``` Somewhat related github-issues: * <https://github.com/brianc/node-postgres/issues/1187> * <https://github.com/serverless/serverless-runtime-babel/issues/8>
2017/01/07
[ "https://Stackoverflow.com/questions/41522744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3301344/" ]
This is indeed an old thread, but one that helped me nonetheless. The solution provided by Steve Schafer [1](https://stackoverflow.com/a/59652739/2822888) is good, but not the simplest. Instead, the one provided by Marco Lüthy [2](https://github.com/brianc/node-postgres/issues/838#issuecomment-405646013) in the linked issue is probably the easiest to set up because it is pure configuration, without even the need for a dummy file to be created. It consists of modifying your Webpack config `plugins` array as follows: ```js const webpack = require('webpack'); const webpackConfig = { ... resolve: { ... }, plugins: [ new webpack.IgnorePlugin(/^pg-native$/) // Or, for WebPack 4+: new webpack.IgnorePlugin({ resourceRegExp: /^pg-native$/ }) ], output: { ... }, ... } ``` Updated to include a change suggested in the comments.
I know that this is an old topic but I'm compelled to share how I solved it. It was maddening to deal with. So, here is the readers digest version as based on the recollection from the last brain cell that I have. --------------------------------------------------------------------------------------------------------- Error: > > Webpack Compilation Error ./node\_modules/pg/lib/native/client.js Module not found: Error: Can't resolve 'pg-native' > > > The error above was thrown when attempting to run a Cypress test that required the npm package 'pg'. Attempting to install the `pg-native package` was not successful and resulted in another error; namely -> > > Call to 'pg\_config --libdir' returned exit status 1 while in binding.gyp. while trying to load binding.gyp > > > I found that executing `pg_config --libdir` in the VSCode cmd prompt resulted in that command failing. However, I knew that it should work since running that command from the system command prompt resulted in this -> `C:/PROGRA~1/POSTGR~1/9.3/lib` That is the path that contains a required dll. So, instead of running `npm install` from the VSCode command prompt, I ran it from the command prompt as launched from windows. The result...success!!! `pg-native` was installed successfully. After, the Cypress test was able to run as well. Errors in now way helped me to arrive at this solution. It was more just checking that things were installed that were required, etc.
14,977,697
I want to read data from one column of datagridview. My datagridview contains many columns but I want to read all cells but only from one column. I read all columns using this code: ``` foreach (DataGridViewColumn col in dataGridView1.Columns) col.Name.ToString(); ``` But I want to read all cell from particular column.
2013/02/20
[ "https://Stackoverflow.com/questions/14977697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1865258/" ]
Try this ``` string data = string.Empty; int indexOfYourColumn = 0; foreach (DataGridViewRow row in dataGridView1.Rows) data = row.Cells[indexOfYourColumn].Value; ```
try this ``` foreach (DataGridViewRow row in dataGridView1.Rows) { foreach (DataGridViewCell cell in row.Cells) { if (cell.ColumnIndex == 0) //Set your Column Index { //DO your Stuff here.. } } } ``` or the other way ``` foreach (DataGridViewColumn col in dataGridView1.Columns) { if (col.Name == "MyColName") { //DO your Stuff here.. } } ```
14,977,697
I want to read data from one column of datagridview. My datagridview contains many columns but I want to read all cells but only from one column. I read all columns using this code: ``` foreach (DataGridViewColumn col in dataGridView1.Columns) col.Name.ToString(); ``` But I want to read all cell from particular column.
2013/02/20
[ "https://Stackoverflow.com/questions/14977697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1865258/" ]
Try this ``` string data = string.Empty; int indexOfYourColumn = 0; foreach (DataGridViewRow row in dataGridView1.Rows) data = row.Cells[indexOfYourColumn].Value; ```
To get the value of the clicked cell: ``` private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { textBox1.Text = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString(); } ```
14,977,697
I want to read data from one column of datagridview. My datagridview contains many columns but I want to read all cells but only from one column. I read all columns using this code: ``` foreach (DataGridViewColumn col in dataGridView1.Columns) col.Name.ToString(); ``` But I want to read all cell from particular column.
2013/02/20
[ "https://Stackoverflow.com/questions/14977697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1865258/" ]
Try this ``` string data = string.Empty; int indexOfYourColumn = 0; foreach (DataGridViewRow row in dataGridView1.Rows) data = row.Cells[indexOfYourColumn].Value; ```
**FOREACH LOOP** ``` string data = string.Empty; string data = string.Empty; int indexOfYourColumn = 0; int indexOfYourColumn = 0; foreach (DataGridViewRow row in dataGridView1.Rows) foreach (DataGridViewRow row in dataGridView1.Rows) data = row.Cells[indexOfYourColumn].Value; ``` **FOR LOOP** ``` using System.Collections; string data = string.Empty; int indexOfYourColumn = 0; IList list = dataGridView1.Rows; for (int i = 0; i < list.Count; i++) { DataGridViewRow row = (DataGridViewRow)list[i]; data = row.Cells[indexOfYourColumn].Value; data = Convert.ToDecimal(row.Cells[indexOfYourColumn].Value); } ```
14,977,697
I want to read data from one column of datagridview. My datagridview contains many columns but I want to read all cells but only from one column. I read all columns using this code: ``` foreach (DataGridViewColumn col in dataGridView1.Columns) col.Name.ToString(); ``` But I want to read all cell from particular column.
2013/02/20
[ "https://Stackoverflow.com/questions/14977697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1865258/" ]
Maybe this helps too. To get one cell: ``` string data = (string)DataGridView1[iCol, iRow].Value; ``` Then you can simply loop rows and columns. [Documentation](http://msdn.microsoft.com/ru-ru/library/ms158656.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2).
try this ``` foreach (DataGridViewRow row in dataGridView1.Rows) { foreach (DataGridViewCell cell in row.Cells) { if (cell.ColumnIndex == 0) //Set your Column Index { //DO your Stuff here.. } } } ``` or the other way ``` foreach (DataGridViewColumn col in dataGridView1.Columns) { if (col.Name == "MyColName") { //DO your Stuff here.. } } ```
14,977,697
I want to read data from one column of datagridview. My datagridview contains many columns but I want to read all cells but only from one column. I read all columns using this code: ``` foreach (DataGridViewColumn col in dataGridView1.Columns) col.Name.ToString(); ``` But I want to read all cell from particular column.
2013/02/20
[ "https://Stackoverflow.com/questions/14977697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1865258/" ]
Maybe this helps too. To get one cell: ``` string data = (string)DataGridView1[iCol, iRow].Value; ``` Then you can simply loop rows and columns. [Documentation](http://msdn.microsoft.com/ru-ru/library/ms158656.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2).
To get the value of the clicked cell: ``` private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { textBox1.Text = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString(); } ```
14,977,697
I want to read data from one column of datagridview. My datagridview contains many columns but I want to read all cells but only from one column. I read all columns using this code: ``` foreach (DataGridViewColumn col in dataGridView1.Columns) col.Name.ToString(); ``` But I want to read all cell from particular column.
2013/02/20
[ "https://Stackoverflow.com/questions/14977697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1865258/" ]
Maybe this helps too. To get one cell: ``` string data = (string)DataGridView1[iCol, iRow].Value; ``` Then you can simply loop rows and columns. [Documentation](http://msdn.microsoft.com/ru-ru/library/ms158656.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2).
**FOREACH LOOP** ``` string data = string.Empty; string data = string.Empty; int indexOfYourColumn = 0; int indexOfYourColumn = 0; foreach (DataGridViewRow row in dataGridView1.Rows) foreach (DataGridViewRow row in dataGridView1.Rows) data = row.Cells[indexOfYourColumn].Value; ``` **FOR LOOP** ``` using System.Collections; string data = string.Empty; int indexOfYourColumn = 0; IList list = dataGridView1.Rows; for (int i = 0; i < list.Count; i++) { DataGridViewRow row = (DataGridViewRow)list[i]; data = row.Cells[indexOfYourColumn].Value; data = Convert.ToDecimal(row.Cells[indexOfYourColumn].Value); } ```
14,977,697
I want to read data from one column of datagridview. My datagridview contains many columns but I want to read all cells but only from one column. I read all columns using this code: ``` foreach (DataGridViewColumn col in dataGridView1.Columns) col.Name.ToString(); ``` But I want to read all cell from particular column.
2013/02/20
[ "https://Stackoverflow.com/questions/14977697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1865258/" ]
try this ``` foreach (DataGridViewRow row in dataGridView1.Rows) { foreach (DataGridViewCell cell in row.Cells) { if (cell.ColumnIndex == 0) //Set your Column Index { //DO your Stuff here.. } } } ``` or the other way ``` foreach (DataGridViewColumn col in dataGridView1.Columns) { if (col.Name == "MyColName") { //DO your Stuff here.. } } ```
To get the value of the clicked cell: ``` private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { textBox1.Text = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString(); } ```
14,977,697
I want to read data from one column of datagridview. My datagridview contains many columns but I want to read all cells but only from one column. I read all columns using this code: ``` foreach (DataGridViewColumn col in dataGridView1.Columns) col.Name.ToString(); ``` But I want to read all cell from particular column.
2013/02/20
[ "https://Stackoverflow.com/questions/14977697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1865258/" ]
try this ``` foreach (DataGridViewRow row in dataGridView1.Rows) { foreach (DataGridViewCell cell in row.Cells) { if (cell.ColumnIndex == 0) //Set your Column Index { //DO your Stuff here.. } } } ``` or the other way ``` foreach (DataGridViewColumn col in dataGridView1.Columns) { if (col.Name == "MyColName") { //DO your Stuff here.. } } ```
**FOREACH LOOP** ``` string data = string.Empty; string data = string.Empty; int indexOfYourColumn = 0; int indexOfYourColumn = 0; foreach (DataGridViewRow row in dataGridView1.Rows) foreach (DataGridViewRow row in dataGridView1.Rows) data = row.Cells[indexOfYourColumn].Value; ``` **FOR LOOP** ``` using System.Collections; string data = string.Empty; int indexOfYourColumn = 0; IList list = dataGridView1.Rows; for (int i = 0; i < list.Count; i++) { DataGridViewRow row = (DataGridViewRow)list[i]; data = row.Cells[indexOfYourColumn].Value; data = Convert.ToDecimal(row.Cells[indexOfYourColumn].Value); } ```
54,187,563
Any suggestions on how to convert the [ISO 8601 duration](https://en.wikipedia.org/wiki/ISO_8601#Durations) format `PnYnMnDTnHnMnS` (ex: P1W, P5D, P3D) to number of days? I'm trying to set the text of a button in a way that the days of free trial are displayed to the user. Google provides the billing information in the ISO 8601 duration format through the key "freeTrialPeriod", but I need it in numbers the user can actually read. The current minimum API level of the app is 18, so the Duration and Period classes from Java 8 won't help, since they are meant for APIs equal or greater than 26. I have set the following method as a workaround, but it doesn't look like the best solution: ``` private String getTrialPeriodMessage() { String period = ""; try { period = subsInfoObjects.get(SUBS_PRODUCT_ID).getString("freeTrialPeriod"); } catch (Exception e) { e.printStackTrace(); } switch (period) { case "P1W": period = "7"; break; case "P2W": period = "14"; break; case "P3W": period = "21"; break; case "P4W": period = "28"; break; case "P7D": period = "7"; break; case "P6D": period = "6"; break; case "P5D": period = "5"; break; case "P4D": period = "4"; break; case "P3D": period = "3"; break; case "P2D": period = "2"; break; case "P1D": period = "1"; } return getString(R.string.continue_with_free_trial, period); } ``` Any suggestions on how to improve it? Thanks!
2019/01/14
[ "https://Stackoverflow.com/questions/54187563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10567570/" ]
java.time and ThreeTenABP ------------------------- This exists. Consider not reinventing the wheel. ``` import org.threeten.bp.Period; public class FormatPeriod { public static void main(String[] args) { String freeTrialString = "P3W"; Period freeTrial = Period.parse(freeTrialString); String formattedPeriod = "" + freeTrial.getDays() + " days"; System.out.println(formattedPeriod); } } ``` This program outputs > > 21 days > > > You will want to add a check that the years and months are 0, or print them out too if they aren’t. Use the `getYears` and `getMonths` methods of the `Period` class. As you can see, weeks are automatically converted to days. The `Period` class doesn’t represent weeks internally, only years, months and days. All of your example strings are supported. You can parse `P1Y` (1 year), `P1Y6M`(1 year 6 months), `P1Y2M14D` (1 year 2 months 14 days), even `P1Y5D`, `P2M`, `P1M15D`, `P35D` and of course `P3W`, etc. Question: Can I use java.time on Android? ----------------------------------------- Yes, java.time works nicely on older and newer Android devices. It just requires at least **Java 6**. * In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in. In this case import from `java.time` rather than `org.threeten.bp`. * In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom). * On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from `org.threeten.bp` with subpackages. Links ----- * [Oracle tutorial: Date Time](https://docs.oracle.com/javase/tutorial/datetime/) explaining how to use `java.time`. [Section *Period and Duration*](https://docs.oracle.com/javase/tutorial/datetime/iso/period.html). * [Java Specification Request (JSR) 310](https://jcp.org/en/jsr/detail?id=310), where `java.time` was first described. * [ThreeTen Backport project](http://www.threeten.org/threetenbp/), the backport of `java.time` to Java 6 and 7 (ThreeTen for JSR-310). * [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP), Android edition of ThreeTen Backport * [Question: How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project), with a very thorough explanation. * [Wikipedia article: ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)
If you do want to re-invent the wheel here is a simple solution to parse ISO 8601 durations, it only supports year/week/day and not the time part but it can of course be added. Another limitation of this solution is that it expects the different types, if present, comes in the order Year->Week->Day ``` private static final String REGEX = "^P((\\d)*Y)?((\\d)*W)?((\\d)*D)?"; public static int parseDuration(String duration) { int days = 0; Pattern pattern = Pattern.compile(REGEX); Matcher matcher = pattern.matcher(duration); while (matcher.find()) { if (matcher.group(1) != null ) { days += 365 * Integer.valueOf(matcher.group(2)); } if (matcher.group(3) != null ) { days += 7 * Integer.valueOf(matcher.group(4)); } if (matcher.group(5) != null ) { days += Integer.valueOf(matcher.group(6)); } } return days; } ```
54,187,563
Any suggestions on how to convert the [ISO 8601 duration](https://en.wikipedia.org/wiki/ISO_8601#Durations) format `PnYnMnDTnHnMnS` (ex: P1W, P5D, P3D) to number of days? I'm trying to set the text of a button in a way that the days of free trial are displayed to the user. Google provides the billing information in the ISO 8601 duration format through the key "freeTrialPeriod", but I need it in numbers the user can actually read. The current minimum API level of the app is 18, so the Duration and Period classes from Java 8 won't help, since they are meant for APIs equal or greater than 26. I have set the following method as a workaround, but it doesn't look like the best solution: ``` private String getTrialPeriodMessage() { String period = ""; try { period = subsInfoObjects.get(SUBS_PRODUCT_ID).getString("freeTrialPeriod"); } catch (Exception e) { e.printStackTrace(); } switch (period) { case "P1W": period = "7"; break; case "P2W": period = "14"; break; case "P3W": period = "21"; break; case "P4W": period = "28"; break; case "P7D": period = "7"; break; case "P6D": period = "6"; break; case "P5D": period = "5"; break; case "P4D": period = "4"; break; case "P3D": period = "3"; break; case "P2D": period = "2"; break; case "P1D": period = "1"; } return getString(R.string.continue_with_free_trial, period); } ``` Any suggestions on how to improve it? Thanks!
2019/01/14
[ "https://Stackoverflow.com/questions/54187563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10567570/" ]
java.time and ThreeTenABP ------------------------- This exists. Consider not reinventing the wheel. ``` import org.threeten.bp.Period; public class FormatPeriod { public static void main(String[] args) { String freeTrialString = "P3W"; Period freeTrial = Period.parse(freeTrialString); String formattedPeriod = "" + freeTrial.getDays() + " days"; System.out.println(formattedPeriod); } } ``` This program outputs > > 21 days > > > You will want to add a check that the years and months are 0, or print them out too if they aren’t. Use the `getYears` and `getMonths` methods of the `Period` class. As you can see, weeks are automatically converted to days. The `Period` class doesn’t represent weeks internally, only years, months and days. All of your example strings are supported. You can parse `P1Y` (1 year), `P1Y6M`(1 year 6 months), `P1Y2M14D` (1 year 2 months 14 days), even `P1Y5D`, `P2M`, `P1M15D`, `P35D` and of course `P3W`, etc. Question: Can I use java.time on Android? ----------------------------------------- Yes, java.time works nicely on older and newer Android devices. It just requires at least **Java 6**. * In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in. In this case import from `java.time` rather than `org.threeten.bp`. * In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom). * On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from `org.threeten.bp` with subpackages. Links ----- * [Oracle tutorial: Date Time](https://docs.oracle.com/javase/tutorial/datetime/) explaining how to use `java.time`. [Section *Period and Duration*](https://docs.oracle.com/javase/tutorial/datetime/iso/period.html). * [Java Specification Request (JSR) 310](https://jcp.org/en/jsr/detail?id=310), where `java.time` was first described. * [ThreeTen Backport project](http://www.threeten.org/threetenbp/), the backport of `java.time` to Java 6 and 7 (ThreeTen for JSR-310). * [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP), Android edition of ThreeTen Backport * [Question: How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project), with a very thorough explanation. * [Wikipedia article: ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)
**I needed to convert to seconds,** so, I am Looking at > > @Joakim Danielson's > > > answer, I improved the regular expression slightly. Please refer to those who need it. ``` private int changeIso8601TimeIntervalsToSecond(String duration) throws Exception { //P#DT#H#M#S String REGEX = "^P((\\d*)D)?T((\\d*)H)?((\\d*)M)?((\\d*)S)?$"; Pattern pattern = Pattern.compile(REGEX); Matcher matcher = pattern.matcher(duration); int seconds = 0; boolean didFind = false; while(matcher.find()){ didFind = true; //D if(matcher.group(1) != null){ seconds += 60 * 60 * 24 * Integer.parseInt(Objects.requireNonNull(matcher.group(2))); } //H if(matcher.group(3) != null){ seconds += 60 * 60 * Integer.parseInt(Objects.requireNonNull(matcher.group(4))); } //M if(matcher.group(5) != null){ seconds += 60 * Integer.parseInt(Objects.requireNonNull(matcher.group(6))); } //S if(matcher.group(7) != null){ seconds += Integer.parseInt(Objects.requireNonNull(matcher.group(8))); } } if(didFind){ return seconds; }else{ throw new Exception("NoRegularExpressionFoundException"); } } ```
54,187,563
Any suggestions on how to convert the [ISO 8601 duration](https://en.wikipedia.org/wiki/ISO_8601#Durations) format `PnYnMnDTnHnMnS` (ex: P1W, P5D, P3D) to number of days? I'm trying to set the text of a button in a way that the days of free trial are displayed to the user. Google provides the billing information in the ISO 8601 duration format through the key "freeTrialPeriod", but I need it in numbers the user can actually read. The current minimum API level of the app is 18, so the Duration and Period classes from Java 8 won't help, since they are meant for APIs equal or greater than 26. I have set the following method as a workaround, but it doesn't look like the best solution: ``` private String getTrialPeriodMessage() { String period = ""; try { period = subsInfoObjects.get(SUBS_PRODUCT_ID).getString("freeTrialPeriod"); } catch (Exception e) { e.printStackTrace(); } switch (period) { case "P1W": period = "7"; break; case "P2W": period = "14"; break; case "P3W": period = "21"; break; case "P4W": period = "28"; break; case "P7D": period = "7"; break; case "P6D": period = "6"; break; case "P5D": period = "5"; break; case "P4D": period = "4"; break; case "P3D": period = "3"; break; case "P2D": period = "2"; break; case "P1D": period = "1"; } return getString(R.string.continue_with_free_trial, period); } ``` Any suggestions on how to improve it? Thanks!
2019/01/14
[ "https://Stackoverflow.com/questions/54187563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10567570/" ]
If you do want to re-invent the wheel here is a simple solution to parse ISO 8601 durations, it only supports year/week/day and not the time part but it can of course be added. Another limitation of this solution is that it expects the different types, if present, comes in the order Year->Week->Day ``` private static final String REGEX = "^P((\\d)*Y)?((\\d)*W)?((\\d)*D)?"; public static int parseDuration(String duration) { int days = 0; Pattern pattern = Pattern.compile(REGEX); Matcher matcher = pattern.matcher(duration); while (matcher.find()) { if (matcher.group(1) != null ) { days += 365 * Integer.valueOf(matcher.group(2)); } if (matcher.group(3) != null ) { days += 7 * Integer.valueOf(matcher.group(4)); } if (matcher.group(5) != null ) { days += Integer.valueOf(matcher.group(6)); } } return days; } ```
**I needed to convert to seconds,** so, I am Looking at > > @Joakim Danielson's > > > answer, I improved the regular expression slightly. Please refer to those who need it. ``` private int changeIso8601TimeIntervalsToSecond(String duration) throws Exception { //P#DT#H#M#S String REGEX = "^P((\\d*)D)?T((\\d*)H)?((\\d*)M)?((\\d*)S)?$"; Pattern pattern = Pattern.compile(REGEX); Matcher matcher = pattern.matcher(duration); int seconds = 0; boolean didFind = false; while(matcher.find()){ didFind = true; //D if(matcher.group(1) != null){ seconds += 60 * 60 * 24 * Integer.parseInt(Objects.requireNonNull(matcher.group(2))); } //H if(matcher.group(3) != null){ seconds += 60 * 60 * Integer.parseInt(Objects.requireNonNull(matcher.group(4))); } //M if(matcher.group(5) != null){ seconds += 60 * Integer.parseInt(Objects.requireNonNull(matcher.group(6))); } //S if(matcher.group(7) != null){ seconds += Integer.parseInt(Objects.requireNonNull(matcher.group(8))); } } if(didFind){ return seconds; }else{ throw new Exception("NoRegularExpressionFoundException"); } } ```
18,819,048
I have a static double variable in a static class. When I create a specific class, I use the double variable as one of the args of the constructor. What would be the easiest way of manipulating field of the object by changing the variable in static class. Code for clarity: ``` public static class Vars { public static double Double1 = 5.0; } public class ClassFoo { public double Field1; public ClassFoo(double number) { Field1 = number; } } class Program { static void Main(string[] args) { ClassFoo Foo = new ClassFoo(Vars.Double1); Console.WriteLine(Foo.Field1 + " " + Vars.Double1); //5 5 Vars.Double1 = 0.0; Console.WriteLine(Foo.Field1 + " " + Vars.Double1); //5 0 //Foo.Field1 need to be a reference to Vars.Double1 } } ``` EDIT that goes beyond the question (no more answers needed, other solution found): I change some values (fields) very often (at runtime, or at least i would like to change them at runtime) to look for one that is right for me. Implementing: ``` if(KeyDown) variable++; if(OtherKeyDown) variable--; ``` Wasn't convenient enough. I just checked Visual Studio Debugger. It's not good (fast) enough. Have to pause, change and run code code again. Method i presented would be good if changed static variable would change field of the object.
2013/09/16
[ "https://Stackoverflow.com/questions/18819048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2679437/" ]
In short: no, you can't do this... at least, not seamlessly. As noted, this is generally considered to be A Bad Idea™. There is no reference encapsulation for value types, and no simple way to implement a seamless wrapper class to do it because you can't overload the assignment operators. You can use the techniques from the `Nullable<T>` type to get part-way there, but no further. The big stumbling block is the assignment operator. For the `Nullable` type this is fine. Since it is non-referencing (new values are distinct), an implicit conversion operator is sufficient. For a referencing type you need to be able to overload the assignment operator to ensure that assignment changes the contained data instead of replacing the wrapper instance. About the closest you can get to full reference is something like this: ``` public class Refable<T> where T : struct { public T Value { get; set; } public Refable(T initial = default(T)) { Value = initial; } public static implicit operator T(Refable<T> self) { return self.Value; } } ``` This will hold a value of the specific type, will automatically convert to that type where applicable (`Refable<double>` will implicitly convert to `double` when required for instance), but all assignments must be done by referencing the `Value` property. Example usage: ``` Refable<double> rd1 = new Refable<double>(1.5); Refable<double> rd2 = d1; // get initial value double d1 = rd1; // set value to 2.5 via second reference rd2.Value = 2.5; // get current value double d2 = rd1; // Output should be: 1.5, 2.5 Console.WriteLine("{0}, {1}", d1, d2); ```
What you really want to do is have `Vars` be a regular class, not a static class. For all methods and classes that need to deal with the variables contained in `Vars`, you can pass in a reference to that `Vars` instance. Here is a very simple example program that illustrates the above. Note that you could probably do a lot to improve the design of your program, but this will at least get you going in the right direction, and away from trying to bend the language to do things it can't or shouldn't do. ``` public class SharedVars { public static double Foo = 0.0; } public class ClassFoo { private SharedVars mySharedVars; public ClassFoo(SharedVars sharedVars) { // save a reference to the shared variables container class for future use mySharedVars = sharedVars; } // here's an example use public void ProcessKeyDown() { mySharedVars.foo++; } } class Program { static void Main(string[] args) { SharedVars sharedVars = new SharedVars(); ClassFoo foo = new ClassFoo(sharedVars); // ... some stuff happens ... if(KeyDown) foo.ProcessKeyDown(); } } ```
13,433,844
I've been doing C# with XNA for a year or so now, and I'm pretty comfortable with 2D games. But after some reading, I'm worried about XNA's future since it isn't supported in Windows 8 and stuff like that. So I've been considering switching to Unity 3D? What are the benefits of Unity over XNA/C# and it is worth the move? if not, why? I'm also open to suggestions of other languages and engines. I'm currently going through school and considering game development as a career, so I would like something which won't die in a year or so (as far as we can tell) and will give me skills I need. Also consider that I have previous programming knowledge with C#. Thanks, David.
2012/11/17
[ "https://Stackoverflow.com/questions/13433844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1739071/" ]
**XNA** XNA still works on Windows 8. The issue is that they are not supporting XNA based games in Windows 8 Modern UI. XNA still works for Windows 8 desktop games. The terminology is extremely confusing. XNA will either get a serious overhaul when the new XBox console is released or something brand new will be designed. **Language** If you want to create games for Windows 8 Modern UI, such as Cut The Rope, etc, you'll need to use C++. The last time I saw C++ was the only supported language that could interop with DirectX and Windows 8 mode. All the other features of Windows 8 are available with C#. **Unity3d** If you want to make video games you should pick Unity3d, or an equivalent gaming engine and framework. The problem a lot of video games creators get into is trying to design yet another game engine. This has been done to the point of them becoming commodities. Focus on the game, not the engine. Unity3d knowledge will be far more value than creating simple games with XNA. You should still understand 3D theory though.
**[MonoGame](http://monogame.codeplex.com/)** is a free XNA-compatible library that allows you to make games in C# for WinRT, Windows Store apps and Windows Phone 8, and on top of the [Xamarin](http://www.xamarin.com) tools also for iOS and Android. This works on top of SharpDX, the optimized managed wrapper for DirectX, so your game runs pretty much at the same speed as with XNA. Since MonoGame is open source, actively developed and targets all the current platforms, you probably need not worry about it being obsolete soon. It gives you a great way to keep your C#, XNA-based codebase to target Windows RT and the Windows Store now, and potentially extend to the other mobile platforms if you buy the Xamarin tools. So no reason to move your C# stuff to C++. Unity3D on the other hand is a totally different game framework, and would not be an easy port. But you can then target many more platforms (particularly consoles, and now Flash too), and still script most of the game in C#. But it's quite a different tool to learn.
11,000,975
I'm stumbled upon understanding java serialization. I have read in many documents and books that static and transient variables cannot be serialized in Java. We declare a serialVersionUid as follows. ``` private static final long serialVersionUID = 1L; ``` If a static variable was not serialized then, we often face an exception during the de-serialization process. ``` java.io.InvalidClassException ``` in which the serialVersionUID from the deserialized object is extracted and compared with the serialVersionUID of the loaded class. To my knowledge i think that if static variables cannot be serialized. There is no point of that exception. I may be wrong because I'm still learning. Is it a myth that "Static and transient variables in java cannot be serialized". Please correct me, I'm in a mess about this concept.
2012/06/12
[ "https://Stackoverflow.com/questions/11000975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/792580/" ]
The `serialVersionUID` is also serialized in this case. *Any static variable that is provided a value during class initialization is serialized*. However in normal cases, where you would provide the value to a static variable at the main class / run-time would not be serialized. You can try to access the `serialVersionUID` by making it public and try to access it after deserialization. You can refer "<http://javabeginnerstutorial.com/core-java-tutorial/transient-vs-static-variable-java/>" for more information. Hope that helps. Cheers !!
Any static variable which has been initialised at the time of declaration will be serialized.
11,000,975
I'm stumbled upon understanding java serialization. I have read in many documents and books that static and transient variables cannot be serialized in Java. We declare a serialVersionUid as follows. ``` private static final long serialVersionUID = 1L; ``` If a static variable was not serialized then, we often face an exception during the de-serialization process. ``` java.io.InvalidClassException ``` in which the serialVersionUID from the deserialized object is extracted and compared with the serialVersionUID of the loaded class. To my knowledge i think that if static variables cannot be serialized. There is no point of that exception. I may be wrong because I'm still learning. Is it a myth that "Static and transient variables in java cannot be serialized". Please correct me, I'm in a mess about this concept.
2012/06/12
[ "https://Stackoverflow.com/questions/11000975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/792580/" ]
The `serialVersionUID` is also serialized in this case. *Any static variable that is provided a value during class initialization is serialized*. However in normal cases, where you would provide the value to a static variable at the main class / run-time would not be serialized. You can try to access the `serialVersionUID` by making it public and try to access it after deserialization. You can refer "<http://javabeginnerstutorial.com/core-java-tutorial/transient-vs-static-variable-java/>" for more information. Hope that helps. Cheers !!
No, if a class have static variable then at the time of serialization that variable will be skipped . because static variable is unique for all object and serialization is used for only save the object properties ( state of object ). static variable is a property of class
11,000,975
I'm stumbled upon understanding java serialization. I have read in many documents and books that static and transient variables cannot be serialized in Java. We declare a serialVersionUid as follows. ``` private static final long serialVersionUID = 1L; ``` If a static variable was not serialized then, we often face an exception during the de-serialization process. ``` java.io.InvalidClassException ``` in which the serialVersionUID from the deserialized object is extracted and compared with the serialVersionUID of the loaded class. To my knowledge i think that if static variables cannot be serialized. There is no point of that exception. I may be wrong because I'm still learning. Is it a myth that "Static and transient variables in java cannot be serialized". Please correct me, I'm in a mess about this concept.
2012/06/12
[ "https://Stackoverflow.com/questions/11000975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/792580/" ]
serialVersionUID is a **special** static variable used by the serialization and deserialization process, to verify that a local class is compatible with the class used to serialize an object. It's not just a static variable as others, which are definitely not serialized. When an object of a class is first serialized, a class descriptor containing among other things the class name and serial version UID is written to the stream. When this is deserialized, the JVM checks if the serial version UID read from the stream is the same as the one of the local class. If they're not, it doesn't even try to deserialize the object, because it knows the classes are incompatible.
You can test this for yourself - here's some example code that should answer your question: ``` import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; class TestJava implements Serializable{ public static int k = 10; public int j = 5; public static void main(String[] args) { TestJava tj1= new TestJava(); TestJava tj2; try{ //serialization FileOutputStream fos = new FileOutputStream("myclass.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(tj1); oos.close(); fos.close(); System.out.println("object serielized 1..."+tj1.j); System.out.println("object serielized 2..."+tj1.k); System.out.println("object serielized 3..."+k); k=++k; // 'k' value incrementd after serialization } catch(FileNotFoundException fnfe){ fnfe.printStackTrace(); } catch(IOException ioex){ ioex.printStackTrace(); } try{ //deserialization FileInputStream fis = new FileInputStream("myclass.ser"); ObjectInputStream ois = new ObjectInputStream(fis); tj2 = (TestJava) ois.readObject(); ois.close(); fis.close(); System.out.println("object DEEEEserielized 1..."+tj2.j); System.out.println("object DEEEEserielized 2..."+tj2.k); System.out.println("object DEEEEserielized 3..."+k); // in deserialization 'k' value is shown as incremented. // That means Static varialbe 'K' is not serialized. // if 'K' value is serialized then, it has to show old value before incrementd the 'K' value. } catch(FileNotFoundException fnfe){ fnfe.printStackTrace(); } catch(IOException ioex){ ioex.printStackTrace(); } catch(ClassNotFoundException CNFE){ CNFE.printStackTrace(); } } } ``` This will output the following: ``` object serielized 1...5 object serielized 2...10 object serielized 3...10 object DEEEEserielized 1...5 object DEEEEserielized 2...11 object DEEEEserielized 3...11 ``` So we create an object of class `TestJava` with one static integer field and one non-static field. We serialize the object, then - after serialization - increment the static integer. When we later deserialize the object, we see that it has the incremented value, implying that it was not serialized.
11,000,975
I'm stumbled upon understanding java serialization. I have read in many documents and books that static and transient variables cannot be serialized in Java. We declare a serialVersionUid as follows. ``` private static final long serialVersionUID = 1L; ``` If a static variable was not serialized then, we often face an exception during the de-serialization process. ``` java.io.InvalidClassException ``` in which the serialVersionUID from the deserialized object is extracted and compared with the serialVersionUID of the loaded class. To my knowledge i think that if static variables cannot be serialized. There is no point of that exception. I may be wrong because I'm still learning. Is it a myth that "Static and transient variables in java cannot be serialized". Please correct me, I'm in a mess about this concept.
2012/06/12
[ "https://Stackoverflow.com/questions/11000975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/792580/" ]
serialVersionUID is a **special** static variable used by the serialization and deserialization process, to verify that a local class is compatible with the class used to serialize an object. It's not just a static variable as others, which are definitely not serialized. When an object of a class is first serialized, a class descriptor containing among other things the class name and serial version UID is written to the stream. When this is deserialized, the JVM checks if the serial version UID read from the stream is the same as the one of the local class. If they're not, it doesn't even try to deserialize the object, because it knows the classes are incompatible.
Any static variable which has been initialised at the time of declaration will be serialized.
11,000,975
I'm stumbled upon understanding java serialization. I have read in many documents and books that static and transient variables cannot be serialized in Java. We declare a serialVersionUid as follows. ``` private static final long serialVersionUID = 1L; ``` If a static variable was not serialized then, we often face an exception during the de-serialization process. ``` java.io.InvalidClassException ``` in which the serialVersionUID from the deserialized object is extracted and compared with the serialVersionUID of the loaded class. To my knowledge i think that if static variables cannot be serialized. There is no point of that exception. I may be wrong because I'm still learning. Is it a myth that "Static and transient variables in java cannot be serialized". Please correct me, I'm in a mess about this concept.
2012/06/12
[ "https://Stackoverflow.com/questions/11000975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/792580/" ]
1. **Instance Variables:** These variables are serialized, so during deserialization we will get back the serialized state. 2. **Static Variables:** These variables are not serialized, So during deserialization static variable value will loaded from the class.(Current value will be loaded.) 3. **transient Variables:** `transient` variables are not serialized, so during deserialization those variables will be initialized with corresponding default values (ex: for objects `null`, `int` `0`). 4. **Super class variables:** If super class also implemented Serializable interface then those variables will be serialized, otherwise it won't serialize the super class variables. and while deserializing, JVM will run default constructor in super class and populates the default values. Same thing will happen for all superclasses.
`serialVersionUID` is special and is not subject to these rules. There is code within the serialization machinery that specifically handles this field to perform the automatic version checks.
11,000,975
I'm stumbled upon understanding java serialization. I have read in many documents and books that static and transient variables cannot be serialized in Java. We declare a serialVersionUid as follows. ``` private static final long serialVersionUID = 1L; ``` If a static variable was not serialized then, we often face an exception during the de-serialization process. ``` java.io.InvalidClassException ``` in which the serialVersionUID from the deserialized object is extracted and compared with the serialVersionUID of the loaded class. To my knowledge i think that if static variables cannot be serialized. There is no point of that exception. I may be wrong because I'm still learning. Is it a myth that "Static and transient variables in java cannot be serialized". Please correct me, I'm in a mess about this concept.
2012/06/12
[ "https://Stackoverflow.com/questions/11000975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/792580/" ]
`serialVersionUID` is special and is not subject to these rules. There is code within the serialization machinery that specifically handles this field to perform the automatic version checks.
No, if a class have static variable then at the time of serialization that variable will be skipped . because static variable is unique for all object and serialization is used for only save the object properties ( state of object ). static variable is a property of class
11,000,975
I'm stumbled upon understanding java serialization. I have read in many documents and books that static and transient variables cannot be serialized in Java. We declare a serialVersionUid as follows. ``` private static final long serialVersionUID = 1L; ``` If a static variable was not serialized then, we often face an exception during the de-serialization process. ``` java.io.InvalidClassException ``` in which the serialVersionUID from the deserialized object is extracted and compared with the serialVersionUID of the loaded class. To my knowledge i think that if static variables cannot be serialized. There is no point of that exception. I may be wrong because I'm still learning. Is it a myth that "Static and transient variables in java cannot be serialized". Please correct me, I'm in a mess about this concept.
2012/06/12
[ "https://Stackoverflow.com/questions/11000975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/792580/" ]
1. **Instance Variables:** These variables are serialized, so during deserialization we will get back the serialized state. 2. **Static Variables:** These variables are not serialized, So during deserialization static variable value will loaded from the class.(Current value will be loaded.) 3. **transient Variables:** `transient` variables are not serialized, so during deserialization those variables will be initialized with corresponding default values (ex: for objects `null`, `int` `0`). 4. **Super class variables:** If super class also implemented Serializable interface then those variables will be serialized, otherwise it won't serialize the super class variables. and while deserializing, JVM will run default constructor in super class and populates the default values. Same thing will happen for all superclasses.
**Yes**, static variable will be serialized if it is initialized at the time of declaration. For example, **case 1 :** without initialization at the time of declaration ``` class Person implements Serializable{ public String firstName; static String lastName; } public class Employee { public static void main(String[] args) { Person p = new Person(); p.firstName="abc"; p.lastName="xyz"; //to do serialization } } ``` output : ``` //after deserialization firstName= abc lastName= null ``` **case 2 :** with initialization at the time of declaration ``` class Person implements Serializable{ public String firstName=="abc"; static String lastName="pqr"; } public class Employee { public static void main(String[] args) { Person p = new Person(); p.firstName="abc"; p.lastName="xyz"; //to do serialization } } ``` output : //after deserialization ``` firstName= abc lastName= pqr ```
11,000,975
I'm stumbled upon understanding java serialization. I have read in many documents and books that static and transient variables cannot be serialized in Java. We declare a serialVersionUid as follows. ``` private static final long serialVersionUID = 1L; ``` If a static variable was not serialized then, we often face an exception during the de-serialization process. ``` java.io.InvalidClassException ``` in which the serialVersionUID from the deserialized object is extracted and compared with the serialVersionUID of the loaded class. To my knowledge i think that if static variables cannot be serialized. There is no point of that exception. I may be wrong because I'm still learning. Is it a myth that "Static and transient variables in java cannot be serialized". Please correct me, I'm in a mess about this concept.
2012/06/12
[ "https://Stackoverflow.com/questions/11000975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/792580/" ]
You can test this for yourself - here's some example code that should answer your question: ``` import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; class TestJava implements Serializable{ public static int k = 10; public int j = 5; public static void main(String[] args) { TestJava tj1= new TestJava(); TestJava tj2; try{ //serialization FileOutputStream fos = new FileOutputStream("myclass.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(tj1); oos.close(); fos.close(); System.out.println("object serielized 1..."+tj1.j); System.out.println("object serielized 2..."+tj1.k); System.out.println("object serielized 3..."+k); k=++k; // 'k' value incrementd after serialization } catch(FileNotFoundException fnfe){ fnfe.printStackTrace(); } catch(IOException ioex){ ioex.printStackTrace(); } try{ //deserialization FileInputStream fis = new FileInputStream("myclass.ser"); ObjectInputStream ois = new ObjectInputStream(fis); tj2 = (TestJava) ois.readObject(); ois.close(); fis.close(); System.out.println("object DEEEEserielized 1..."+tj2.j); System.out.println("object DEEEEserielized 2..."+tj2.k); System.out.println("object DEEEEserielized 3..."+k); // in deserialization 'k' value is shown as incremented. // That means Static varialbe 'K' is not serialized. // if 'K' value is serialized then, it has to show old value before incrementd the 'K' value. } catch(FileNotFoundException fnfe){ fnfe.printStackTrace(); } catch(IOException ioex){ ioex.printStackTrace(); } catch(ClassNotFoundException CNFE){ CNFE.printStackTrace(); } } } ``` This will output the following: ``` object serielized 1...5 object serielized 2...10 object serielized 3...10 object DEEEEserielized 1...5 object DEEEEserielized 2...11 object DEEEEserielized 3...11 ``` So we create an object of class `TestJava` with one static integer field and one non-static field. We serialize the object, then - after serialization - increment the static integer. When we later deserialize the object, we see that it has the incremented value, implying that it was not serialized.
**Yes**, static variable will be serialized if it is initialized at the time of declaration. For example, **case 1 :** without initialization at the time of declaration ``` class Person implements Serializable{ public String firstName; static String lastName; } public class Employee { public static void main(String[] args) { Person p = new Person(); p.firstName="abc"; p.lastName="xyz"; //to do serialization } } ``` output : ``` //after deserialization firstName= abc lastName= null ``` **case 2 :** with initialization at the time of declaration ``` class Person implements Serializable{ public String firstName=="abc"; static String lastName="pqr"; } public class Employee { public static void main(String[] args) { Person p = new Person(); p.firstName="abc"; p.lastName="xyz"; //to do serialization } } ``` output : //after deserialization ``` firstName= abc lastName= pqr ```
11,000,975
I'm stumbled upon understanding java serialization. I have read in many documents and books that static and transient variables cannot be serialized in Java. We declare a serialVersionUid as follows. ``` private static final long serialVersionUID = 1L; ``` If a static variable was not serialized then, we often face an exception during the de-serialization process. ``` java.io.InvalidClassException ``` in which the serialVersionUID from the deserialized object is extracted and compared with the serialVersionUID of the loaded class. To my knowledge i think that if static variables cannot be serialized. There is no point of that exception. I may be wrong because I'm still learning. Is it a myth that "Static and transient variables in java cannot be serialized". Please correct me, I'm in a mess about this concept.
2012/06/12
[ "https://Stackoverflow.com/questions/11000975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/792580/" ]
serialVersionUID is a **special** static variable used by the serialization and deserialization process, to verify that a local class is compatible with the class used to serialize an object. It's not just a static variable as others, which are definitely not serialized. When an object of a class is first serialized, a class descriptor containing among other things the class name and serial version UID is written to the stream. When this is deserialized, the JVM checks if the serial version UID read from the stream is the same as the one of the local class. If they're not, it doesn't even try to deserialize the object, because it knows the classes are incompatible.
1. **Instance Variables:** These variables are serialized, so during deserialization we will get back the serialized state. 2. **Static Variables:** These variables are not serialized, So during deserialization static variable value will loaded from the class.(Current value will be loaded.) 3. **transient Variables:** `transient` variables are not serialized, so during deserialization those variables will be initialized with corresponding default values (ex: for objects `null`, `int` `0`). 4. **Super class variables:** If super class also implemented Serializable interface then those variables will be serialized, otherwise it won't serialize the super class variables. and while deserializing, JVM will run default constructor in super class and populates the default values. Same thing will happen for all superclasses.
11,000,975
I'm stumbled upon understanding java serialization. I have read in many documents and books that static and transient variables cannot be serialized in Java. We declare a serialVersionUid as follows. ``` private static final long serialVersionUID = 1L; ``` If a static variable was not serialized then, we often face an exception during the de-serialization process. ``` java.io.InvalidClassException ``` in which the serialVersionUID from the deserialized object is extracted and compared with the serialVersionUID of the loaded class. To my knowledge i think that if static variables cannot be serialized. There is no point of that exception. I may be wrong because I'm still learning. Is it a myth that "Static and transient variables in java cannot be serialized". Please correct me, I'm in a mess about this concept.
2012/06/12
[ "https://Stackoverflow.com/questions/11000975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/792580/" ]
serialVersionUID is a **special** static variable used by the serialization and deserialization process, to verify that a local class is compatible with the class used to serialize an object. It's not just a static variable as others, which are definitely not serialized. When an object of a class is first serialized, a class descriptor containing among other things the class name and serial version UID is written to the stream. When this is deserialized, the JVM checks if the serial version UID read from the stream is the same as the one of the local class. If they're not, it doesn't even try to deserialize the object, because it knows the classes are incompatible.
No, if a class have static variable then at the time of serialization that variable will be skipped . because static variable is unique for all object and serialization is used for only save the object properties ( state of object ). static variable is a property of class
68,317
I am trying to figure out head-internal relative clauses. A paper I looked at presented two versions of the same sentence, one with the head word (りんご) outside the relative clause: > > [皿の上にあった]**りんご**をくすねた。 > > > And one version where it is inside the relative clause: > > [**りんご**が皿の上にあった]のをくすねた。 > > > Do these two sentences mean exactly the same thing, or are there differences in nuance? When are head-internal relative clauses usually used in Japanese?
2019/05/17
[ "https://japanese.stackexchange.com/questions/68317", "https://japanese.stackexchange.com", "https://japanese.stackexchange.com/users/33409/" ]
They are slightly different, if not much. The former sounds saying a fact relatively objectively. On the other hand, the latter rather means "although an apple was on the plate, s/he stole it" and it sounds somehow accusive in the sense that it should have been there. In grammar for old Japanese, a similar form is considered a conjunction. > > When are head-internal relative clauses usually used in Japanese? > > > I forgot to answer to this part. Speaking of this usage of を, not specifically to "head-internal relative clause", I personally use it like a weaker version of のに in the point of paradoxical sense, mostly in the form of "…、それをさぁ~、…。". So, I think I've been using it to some degree. I personally am used to the form of HIRC with を too. But I'm not sure other native speakers share that sense.
I could have the wrong end of the stick here, but your second example doesn't make sense to me. ### Part 1: regular relative clause Let's look at your first example first. > > [皿の上にあった]**りんご**をくすねた。 > > > At its core (haha, pun not intended), we have: > > **りんご**をくすねた。 > > I pilfered the **apple**. > > > The relative clause portion tells us more about the apple: > > [皿の上にあった] > > [(it) was on the plate] > > > Looking at the whole utterance, we get: > > [皿の上にあった]**りんご**をくすねた。 > > I pilfered the **apple** [(that) was on the plate]. > > > ### Part 2: nominalized clause Now let's look at your second example. > > [**りんご**が皿の上にあった]のをくすねた。 > > > The core here is more complicated, because we don't have a simple concrete noun as the object of our verb くすねた. Instead, we have the の, which here is used to nominalize (make a noun out of) the entire preceding clause. So let's look at the embedded clause. > > [**りんご**が皿の上にあった] > > [The **apple** was on the plate] > > > Okay, simple enough. After this, though, we have that の, turning our entire embedded clause into a nominalized phrase. This can be a bit messy to translate into English; it comes through somewhat similar to "the fact that", or "the act of", or sometimes by turning a verb into the "-ing" form. Some examples: > > ラーメンを食べるのが好きです。 > > I like (the act of) eating ramen. > > > Note that this is different from just *"I like ramen"*. We're not talking about "ramen" as the main noun, but rather about the whole clause that contains "ramen" -- in this case, about "eating" it. > > 道子さんが東京に行ったのは知らなかった。 > > I didn't know (the fact) that Michiko went to Tokyo. > > > Again, this is different from *"I didn't know Michiko"*. We're not talking about "Michiko" as the main noun, but rather about the whole clause that contains "Michiko" -- in this case, that she "went to Tokyo". Looking again at the whole second example sentence then: > > [**りんご**が皿の上にあった]のをくすねた。 > > > The key is that it turns the *whole* embedded clause into a kind of noun: we're not talking about "the apple" anymore, but rather the fact that "the apple was on the plate". Because of the verb here, くすねた / "pilfered", nothing quite makes sense -- just due to the meaning of the words, this doesn't fit together. The best translation I can come up with would be something like: > > I pilfered (the fact that) [the **apple** was on the plate]. > > > ...??? That doesn't make sense in English. Nor does the Japanese make sense. (At least, as I understand it.) If you change the verb from くすねた to 見た, that would work: > > [**りんご**が皿の上にあった]のを**見た**。 > > I **saw** (the fact) that [the **apple** was on the plate]. > > > --- The paper in question appears to be this one: * [**日本語主要部内在型関係節の時制解釈**](http://www.ls-japan.org/modules/documents/LSJpapers/journals/143_nomura.pdf), by 野村 益寛 of 北海道大学, published in 2013 in volume 143 of **言語研究**. This seems to have been written by a native speaker of Japanese, which makes that second sample sentence a bit of a head-scratcher for me. For the verb くすねる, I'm only aware of the sense *"pilfer, filch, sneak, pinch, swipe"*, with the core underlying meaning of *"to steal something sneakily"*. There might be a sense of くすねる that I'm missing, which could make the second sample sentence work better.
44,877,715
why do we need self referential object in javascript. example ``` let a = {}; a.self = a; ``` now a property self is referring to itself and become circular object. in nodejs when we use routing library like hapi. the request object which we receive is circular
2017/07/03
[ "https://Stackoverflow.com/questions/44877715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5949299/" ]
The problem came from ***malloc(total\_courses + sizeof(course\_collection))*** You only allocate array of pointer of course\_collection. You need allocate memory for whole the *struct Course* It should be **malloc(total\_courses \* sizeof(struct Course))**
User this malloc(total\_courses + sizeof(struct Course)) instead of malloc(total\_courses + sizeof(course\_collection)) segmentation fault due to memory allocation mostly for arrays arr[n] we use it till '0' to 'n-1' { carefully observe not 'n'}
38,796,482
Does it simply mean that I have a parameter in my 'model\_params' variable that is not in this line? ``` params.require(...).permit(...) ``` I can't find offending parameter. Is there a way to accept all parameters?
2016/08/05
[ "https://Stackoverflow.com/questions/38796482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1344643/" ]
A space is a [descendant combinator](https://www.w3.org/TR/css3-selectors/#descendant-combinators). It targets descendants, but the div is not a descendant of the button, it is a sibling. You need to use the [adjacent sibling combinator](https://www.w3.org/TR/css3-selectors/#adjacent-sibling-combinators) instead: a plus sign. You also need to target the links (which are descendants of `.dropcontent` so you should use a descendant combinator there) since it is those which you have set `display: none` on and not the div. ``` .dropbutton:hover + .dropcontent a { ```
I'd move the `display: none;` to the `.dropcontent` itself - as it now pertains to its anchors, that is, links, and as such, neither current answer would work -, then use ``` .dropbutton:hover + .dropcontent { display: block; } ``` But you must not add anything between dropbutton and dropcontent afterwards, or it will not work any more.
38,796,482
Does it simply mean that I have a parameter in my 'model\_params' variable that is not in this line? ``` params.require(...).permit(...) ``` I can't find offending parameter. Is there a way to accept all parameters?
2016/08/05
[ "https://Stackoverflow.com/questions/38796482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1344643/" ]
A space is a [descendant combinator](https://www.w3.org/TR/css3-selectors/#descendant-combinators). It targets descendants, but the div is not a descendant of the button, it is a sibling. You need to use the [adjacent sibling combinator](https://www.w3.org/TR/css3-selectors/#adjacent-sibling-combinators) instead: a plus sign. You also need to target the links (which are descendants of `.dropcontent` so you should use a descendant combinator there) since it is those which you have set `display: none` on and not the div. ``` .dropbutton:hover + .dropcontent a { ```
Are you using Javascript to do this? ``` var button = document.getElementsByClassName('.dropbutton')[0], menuContent = docuemnt.getElementsByClassName('.dropcontent')[0]; button.onmouseover = function(event) { menuContent.style.display['block']; } button.onmouseout = function(event) { menuContent.style.display['none']; } ``` With a slight change to your CSS: `.dropbutton` should have `display: none`, and you should remove the `display: none` from `.dropcontent a`
44,105,977
This is what I have: ``` class encoded { public static void main(String[] args) { String s1 = "hello"; char[] ch = s1.toCharArray(); for(int i=0;i<ch.length;i++) { char c = (char) (((i - 'a' + 1) % 26) + 'a'); System.out.print(c); } } } ``` So far I've converted the string to an array, and I've worked out how to shift, but now I'm stuck. What I want is for the code to start at `ch[0]`, read the character, shift it one to the right (`h` to `i`) and then do the same for each character in the array until it reaches the end. Right now, my code outputs `opqrs`. I want it to output `ifmmp`. If I replace the `int i = 0` in the `for` loop with `int i = ch[0]`, it does start at `i`, but then it just inputs `ijklmno...` I want it to read `h`, output as `i`, read `e`, output as `f`, and so on until it reaches the end of the array.
2017/05/22
[ "https://Stackoverflow.com/questions/44105977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8046403/" ]
You are using the loop index `i` instead of the `i`th character in your loop, which means the output of your code does not depend the input `String` (well, except for the length of the output, which is the same as the length of the input). Change ``` char c = (char) (((i - 'a' + 1) % 26) + 'a'); ``` to ``` char c = (char) (((ch[i] - 'a' + 1) % 26) + 'a'); ```
Replace `i - 'a' + 1` with `ch[i] - 'a' + 1` ``` class encoded { public static void main(String[] args) { String s1 = "hello"; char[] ch = s1.toCharArray(); for(int i=0;i<ch.length;i++) { char c = (char) (((ch[i] - 'a' + 1) % 26) + 'a'); System.out.print(c); } } } ```
40,428,510
I have a directory "FolderName" with 10,000 new files every day. Almost a half of those files are named as follows: ``` filename_yyyy-mm-dd_hh:mm ``` while the other half are named: ``` filename_yyyy-mm-dd hh:mm ``` (with space instead of underscore) The script I'd like to set up should do the following: Rename only the files containing a space in their name, skipping files that need no processing. I cannot find a way to make the script efficient, I need to really skip the good half, my script tries to mv any file, and it's quite long and inefficient. Any good idea for a better design? Thanks everybody
2016/11/04
[ "https://Stackoverflow.com/questions/40428510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5233499/" ]
`for f in "$(find . -name '* *')"; do mv $f $(echo $f | sed 's/\ /_/'); done` will do it. There should be a better way using find's `-exec` option as well. EDIT: If the function is put in a script, then find can be used directly: ``` cat <<EOF > space_to_underscore #!/usr/bin/env bash mv "$1" "$(sed 's/\ /_/' <(echo "$1"))" EOF chmod +x space_to_underscore find . -name '* *' -exec ./space_to_underscore {} \; ``` This will be faster than using a for loop.
Rename only the files containing a space in their name, skipping files that need no processing: ``` for file in *\ * ; do mv "$file" "${file// /_}" ; done ``` Move all the files older than one week to a "NewFolderName" folder: ``` find -mtime 7 -exec mv {} NewFolderName/ \; ```
40,428,510
I have a directory "FolderName" with 10,000 new files every day. Almost a half of those files are named as follows: ``` filename_yyyy-mm-dd_hh:mm ``` while the other half are named: ``` filename_yyyy-mm-dd hh:mm ``` (with space instead of underscore) The script I'd like to set up should do the following: Rename only the files containing a space in their name, skipping files that need no processing. I cannot find a way to make the script efficient, I need to really skip the good half, my script tries to mv any file, and it's quite long and inefficient. Any good idea for a better design? Thanks everybody
2016/11/04
[ "https://Stackoverflow.com/questions/40428510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5233499/" ]
Check out the [`rename`](http://search.cpan.org/~rmbarker/File-Rename-0.06/rename.PL) utility, a Perl script designed just for this, it's powerful and fast. ``` rename -n ' ' _ *\ * ``` Or: ``` find /path/to/dir -type f -name '* *' -exec rename -n ' ' _ {} \; ``` The `-n` flag is for dry run, to print what works happen without actually renaming anything. If the output looks good, remove the flag and rerun.
`for f in "$(find . -name '* *')"; do mv $f $(echo $f | sed 's/\ /_/'); done` will do it. There should be a better way using find's `-exec` option as well. EDIT: If the function is put in a script, then find can be used directly: ``` cat <<EOF > space_to_underscore #!/usr/bin/env bash mv "$1" "$(sed 's/\ /_/' <(echo "$1"))" EOF chmod +x space_to_underscore find . -name '* *' -exec ./space_to_underscore {} \; ``` This will be faster than using a for loop.
40,428,510
I have a directory "FolderName" with 10,000 new files every day. Almost a half of those files are named as follows: ``` filename_yyyy-mm-dd_hh:mm ``` while the other half are named: ``` filename_yyyy-mm-dd hh:mm ``` (with space instead of underscore) The script I'd like to set up should do the following: Rename only the files containing a space in their name, skipping files that need no processing. I cannot find a way to make the script efficient, I need to really skip the good half, my script tries to mv any file, and it's quite long and inefficient. Any good idea for a better design? Thanks everybody
2016/11/04
[ "https://Stackoverflow.com/questions/40428510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5233499/" ]
Check out the [`rename`](http://search.cpan.org/~rmbarker/File-Rename-0.06/rename.PL) utility, a Perl script designed just for this, it's powerful and fast. ``` rename -n ' ' _ *\ * ``` Or: ``` find /path/to/dir -type f -name '* *' -exec rename -n ' ' _ {} \; ``` The `-n` flag is for dry run, to print what works happen without actually renaming anything. If the output looks good, remove the flag and rerun.
Rename only the files containing a space in their name, skipping files that need no processing: ``` for file in *\ * ; do mv "$file" "${file// /_}" ; done ``` Move all the files older than one week to a "NewFolderName" folder: ``` find -mtime 7 -exec mv {} NewFolderName/ \; ```
40,428,510
I have a directory "FolderName" with 10,000 new files every day. Almost a half of those files are named as follows: ``` filename_yyyy-mm-dd_hh:mm ``` while the other half are named: ``` filename_yyyy-mm-dd hh:mm ``` (with space instead of underscore) The script I'd like to set up should do the following: Rename only the files containing a space in their name, skipping files that need no processing. I cannot find a way to make the script efficient, I need to really skip the good half, my script tries to mv any file, and it's quite long and inefficient. Any good idea for a better design? Thanks everybody
2016/11/04
[ "https://Stackoverflow.com/questions/40428510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5233499/" ]
with the legacy `rename` you can easily convert single space to underlines ``` $ rename ' ' '_' files ```
Rename only the files containing a space in their name, skipping files that need no processing: ``` for file in *\ * ; do mv "$file" "${file// /_}" ; done ``` Move all the files older than one week to a "NewFolderName" folder: ``` find -mtime 7 -exec mv {} NewFolderName/ \; ```
40,428,510
I have a directory "FolderName" with 10,000 new files every day. Almost a half of those files are named as follows: ``` filename_yyyy-mm-dd_hh:mm ``` while the other half are named: ``` filename_yyyy-mm-dd hh:mm ``` (with space instead of underscore) The script I'd like to set up should do the following: Rename only the files containing a space in their name, skipping files that need no processing. I cannot find a way to make the script efficient, I need to really skip the good half, my script tries to mv any file, and it's quite long and inefficient. Any good idea for a better design? Thanks everybody
2016/11/04
[ "https://Stackoverflow.com/questions/40428510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5233499/" ]
Check out the [`rename`](http://search.cpan.org/~rmbarker/File-Rename-0.06/rename.PL) utility, a Perl script designed just for this, it's powerful and fast. ``` rename -n ' ' _ *\ * ``` Or: ``` find /path/to/dir -type f -name '* *' -exec rename -n ' ' _ {} \; ``` The `-n` flag is for dry run, to print what works happen without actually renaming anything. If the output looks good, remove the flag and rerun.
with the legacy `rename` you can easily convert single space to underlines ``` $ rename ' ' '_' files ```
25,440,573
i have created Lead Management System. i have created to type of user category as given below 1. user - Normal user of System who can see only his/her data while logged in system 2. admin - treating as manager login in which manager can see all data of user which has been register under his/her name Function:- i have created on function in which im checking weather logged in user is 'logged\_in\_as' as admin or user. Coder give below ``` function logged_in_as() { return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `user` WHERE `user_type` = 'admin'"), 0) == 1) ? true : false; } ``` Query :- Now by using this function i am trying to pull out the data according to query given below. ``` if(logged_in_as() === false) { $sql = mysql_query("SELECT * FROM `lead_table` WHERE `created_by` = $session_user_id"); } else { $sql = mysql_query("SELECT * FROM `lead_table`"); } $hotelcount = mysql_num_rows($sql); if($hotelcount > 0) { while($row = mysql_fetch_array($sql)) { $id = $row['customer_id']; $pic = $row['client_name']; $country = $row['city']; $destination = $row['contact_person']; $price = $row['email_id']; $mobile = $row['mobile']; $lead_id = $row['lead_id']; $dynamiclist .= '<tbody> <tr class="yahoo"> <td>' . $id . '</td> <td>' . $pic . '</td> <td class="hidden-phone">' . $country . '</td> <td class="hidden-phone">' . $destination . '</td> <td class="hidden-phone">'. $price . '</td> <td>'. $mobile .'</td> <td>Trident</td> <td><a href="edit.php?mode=update&lead_id='. $lead_id .'">Edit</a> / <a href="updatelead.php?lead_id='. $lead_id .'">Update</a></td> </tr> </tbody>'; } } else { $dynamiclist = 'We Do Not Have Any Hotel Listed in This City'; } ``` Error:- When i am logged in as 'user' query is returning only the data which has been entered by the user but when i am logged in as admin query is not returning any data which has been entered by register user under that admin. Please Help !!!
2014/08/22
[ "https://Stackoverflow.com/questions/25440573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3270076/" ]
Check whether logged\_in\_as() returns the proper bool value. Maybe u have a bug in that function and it always returns false. Since it is false, it will return all the leads entered by that user (i.e. admin), and since admin has not entered any data, it shows blank. This is only a guess. It should work otherwise, your code is apparently OK. Let me know what returns by the logged\_in\_as() function for further support.
Just on a side note, why not save the usergroup (admin or normal user) to a session instead of running that function all the time when checking who is and isn't a system admin? Potentially you would run that sql routine many times on a page just to check the usergroup which seems a bit much. At that juncture it would check like so: ``` if(isset($_SESSION['usergroup']) && $_SESSION['usergroup'] == 'admin') { // Do your code thang... } ``` You would only run an sql userid check at login. Maybe your system doesn't have heavy traffic and it doesn't bog you down, but that just seems like a lot of sql just to keep checking usergroup. Also the comment about the deprecated `mysql_query` is true, you should switch over to `PDO or mysqli` calls.
25,440,573
i have created Lead Management System. i have created to type of user category as given below 1. user - Normal user of System who can see only his/her data while logged in system 2. admin - treating as manager login in which manager can see all data of user which has been register under his/her name Function:- i have created on function in which im checking weather logged in user is 'logged\_in\_as' as admin or user. Coder give below ``` function logged_in_as() { return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `user` WHERE `user_type` = 'admin'"), 0) == 1) ? true : false; } ``` Query :- Now by using this function i am trying to pull out the data according to query given below. ``` if(logged_in_as() === false) { $sql = mysql_query("SELECT * FROM `lead_table` WHERE `created_by` = $session_user_id"); } else { $sql = mysql_query("SELECT * FROM `lead_table`"); } $hotelcount = mysql_num_rows($sql); if($hotelcount > 0) { while($row = mysql_fetch_array($sql)) { $id = $row['customer_id']; $pic = $row['client_name']; $country = $row['city']; $destination = $row['contact_person']; $price = $row['email_id']; $mobile = $row['mobile']; $lead_id = $row['lead_id']; $dynamiclist .= '<tbody> <tr class="yahoo"> <td>' . $id . '</td> <td>' . $pic . '</td> <td class="hidden-phone">' . $country . '</td> <td class="hidden-phone">' . $destination . '</td> <td class="hidden-phone">'. $price . '</td> <td>'. $mobile .'</td> <td>Trident</td> <td><a href="edit.php?mode=update&lead_id='. $lead_id .'">Edit</a> / <a href="updatelead.php?lead_id='. $lead_id .'">Update</a></td> </tr> </tbody>'; } } else { $dynamiclist = 'We Do Not Have Any Hotel Listed in This City'; } ``` Error:- When i am logged in as 'user' query is returning only the data which has been entered by the user but when i am logged in as admin query is not returning any data which has been entered by register user under that admin. Please Help !!!
2014/08/22
[ "https://Stackoverflow.com/questions/25440573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3270076/" ]
Check whether logged\_in\_as() returns the proper bool value. Maybe u have a bug in that function and it always returns false. Since it is false, it will return all the leads entered by that user (i.e. admin), and since admin has not entered any data, it shows blank. This is only a guess. It should work otherwise, your code is apparently OK. Let me know what returns by the logged\_in\_as() function for further support.
I hope I am mistaken but does your `logged_in_as()` method even works? It doesn't even seems to have an input. As long as your `user` table contains at least 1 admin it'll always return true. try this and see if it helps ``` function logged_in_as() { return (mysql_result(mysql_query("SELECT if(user_type='admin',1,0) FROM `user` WHERE `user_id` = $session_user_id"), 0) == 1) ? true : false; } ```
25,440,573
i have created Lead Management System. i have created to type of user category as given below 1. user - Normal user of System who can see only his/her data while logged in system 2. admin - treating as manager login in which manager can see all data of user which has been register under his/her name Function:- i have created on function in which im checking weather logged in user is 'logged\_in\_as' as admin or user. Coder give below ``` function logged_in_as() { return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `user` WHERE `user_type` = 'admin'"), 0) == 1) ? true : false; } ``` Query :- Now by using this function i am trying to pull out the data according to query given below. ``` if(logged_in_as() === false) { $sql = mysql_query("SELECT * FROM `lead_table` WHERE `created_by` = $session_user_id"); } else { $sql = mysql_query("SELECT * FROM `lead_table`"); } $hotelcount = mysql_num_rows($sql); if($hotelcount > 0) { while($row = mysql_fetch_array($sql)) { $id = $row['customer_id']; $pic = $row['client_name']; $country = $row['city']; $destination = $row['contact_person']; $price = $row['email_id']; $mobile = $row['mobile']; $lead_id = $row['lead_id']; $dynamiclist .= '<tbody> <tr class="yahoo"> <td>' . $id . '</td> <td>' . $pic . '</td> <td class="hidden-phone">' . $country . '</td> <td class="hidden-phone">' . $destination . '</td> <td class="hidden-phone">'. $price . '</td> <td>'. $mobile .'</td> <td>Trident</td> <td><a href="edit.php?mode=update&lead_id='. $lead_id .'">Edit</a> / <a href="updatelead.php?lead_id='. $lead_id .'">Update</a></td> </tr> </tbody>'; } } else { $dynamiclist = 'We Do Not Have Any Hotel Listed in This City'; } ``` Error:- When i am logged in as 'user' query is returning only the data which has been entered by the user but when i am logged in as admin query is not returning any data which has been entered by register user under that admin. Please Help !!!
2014/08/22
[ "https://Stackoverflow.com/questions/25440573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3270076/" ]
Just on a side note, why not save the usergroup (admin or normal user) to a session instead of running that function all the time when checking who is and isn't a system admin? Potentially you would run that sql routine many times on a page just to check the usergroup which seems a bit much. At that juncture it would check like so: ``` if(isset($_SESSION['usergroup']) && $_SESSION['usergroup'] == 'admin') { // Do your code thang... } ``` You would only run an sql userid check at login. Maybe your system doesn't have heavy traffic and it doesn't bog you down, but that just seems like a lot of sql just to keep checking usergroup. Also the comment about the deprecated `mysql_query` is true, you should switch over to `PDO or mysqli` calls.
I hope I am mistaken but does your `logged_in_as()` method even works? It doesn't even seems to have an input. As long as your `user` table contains at least 1 admin it'll always return true. try this and see if it helps ``` function logged_in_as() { return (mysql_result(mysql_query("SELECT if(user_type='admin',1,0) FROM `user` WHERE `user_id` = $session_user_id"), 0) == 1) ? true : false; } ```
42,014,274
Haven't seen a solution similar enough to this yet... I have two files each containing a list of file names. There are overlap in the contents of the files but file A contain some file names that are not in file B. Also, the file extensions are different in files A and B. That is: ``` A B ------------ -------------- file-1-2.txt file-1-2.png file-2-3.txt file-3-4.png file-3-4.txt ... ``` How do I combine the two files, comma-delimited, into one ignoring lines that don't match? That is: ``` C ------------ file-1-2.txt,file-1-2.png file-3-4.txt,file-3-4.png ``` I believe some usage of `awk` similar to the following will work: ``` awk 'FNR==NR{NOT SURE} {print $1,$2}' fileA fileB ``` Thanks in advance!
2017/02/02
[ "https://Stackoverflow.com/questions/42014274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3741624/" ]
You could do: ``` $ awk 'function base(fn) {sub("[.][^.]*$", "", fn); return fn} NR==FNR { fn[$1]; next} {for (e in fn){ if (base(e)==base($1)){ printf "%s,%s\n", e, $1 }}} ' f1 f2 file-1-2.txt,file-1-2.png file-3-4.txt,file-3-4.png ``` Since `awk` associative arrays are unordered, the order of the printout is determined by the order of the second file -- not the first. --- Explanation: 1. `function base(fn) {sub("[.][^.]*$", "", fn); return fn}` is a function that strips the extension from the filename (assuming that the extension is the non `.` characters to the right of the last `.` found. The entire name is returned if no `.` is found.) 2. `NR==FNR { fn[$1]; next}` read each line (each file name in this case) into an associative array. The `NR==FNR` is an `awk` idiom that is true only for the first file and `next` means the only this part is executed on the first file of file names. `$1` is used since the leading and trailing spaces are stripped. Since Unix filenames *can* have leading or trailing spaces, this is a rare ambiguity you need to resolve. If you don't want the lines stripped, you would use `$0` instead. 3. `{for (e in fn){ if (base(e)==base($1)){ printf "%s,%s\n", e, $1 }}}` now for any line other than from the first file (where `NR==FNR` is true since `next` skipped this part) loop through the saved file names. Print if the base name is the same.
The unix join command should do what you want. Set the field separator -t '.' to be a dot and join by the first column in both files. You may need to sort the files ahead of time. The sort can be done on the same command line as the join with the proper syntax. <(sort -k 2 file1.txt) <(sort file2.txt)
42,014,274
Haven't seen a solution similar enough to this yet... I have two files each containing a list of file names. There are overlap in the contents of the files but file A contain some file names that are not in file B. Also, the file extensions are different in files A and B. That is: ``` A B ------------ -------------- file-1-2.txt file-1-2.png file-2-3.txt file-3-4.png file-3-4.txt ... ``` How do I combine the two files, comma-delimited, into one ignoring lines that don't match? That is: ``` C ------------ file-1-2.txt,file-1-2.png file-3-4.txt,file-3-4.png ``` I believe some usage of `awk` similar to the following will work: ``` awk 'FNR==NR{NOT SURE} {print $1,$2}' fileA fileB ``` Thanks in advance!
2017/02/02
[ "https://Stackoverflow.com/questions/42014274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3741624/" ]
This pure bash solution should work and handle dots, backslashes, dashes, and other special characters in either file. ``` mapfile -t arr_a < A mapfile -t arr_b < B for a in "${arr_a[@]}"; do for b in "${arr_b[@]}"; do [[ ${a%.*} == "${b%.*}" ]] && printf '%s,%s\n' "$a" "$b" && break done; done ``` First, we read the contents of the files into arrays, one line per item, using `mapfile`. 1 Then, for each line in `A`, we compare to each line in `B`. To compare only the portion before the extension, we use the shell parameter expansion `${var%pattern}`, which removes the shortest match of the glob `.*`2 from the end of the filenames. 1The -t option strips the trailing newline from the array items. 2The `.` here is literal, removing a period and everything after.
The unix join command should do what you want. Set the field separator -t '.' to be a dot and join by the first column in both files. You may need to sort the files ahead of time. The sort can be done on the same command line as the join with the proper syntax. <(sort -k 2 file1.txt) <(sort file2.txt)
42,014,274
Haven't seen a solution similar enough to this yet... I have two files each containing a list of file names. There are overlap in the contents of the files but file A contain some file names that are not in file B. Also, the file extensions are different in files A and B. That is: ``` A B ------------ -------------- file-1-2.txt file-1-2.png file-2-3.txt file-3-4.png file-3-4.txt ... ``` How do I combine the two files, comma-delimited, into one ignoring lines that don't match? That is: ``` C ------------ file-1-2.txt,file-1-2.png file-3-4.txt,file-3-4.png ``` I believe some usage of `awk` similar to the following will work: ``` awk 'FNR==NR{NOT SURE} {print $1,$2}' fileA fileB ``` Thanks in advance!
2017/02/02
[ "https://Stackoverflow.com/questions/42014274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3741624/" ]
You could do: ``` $ awk 'function base(fn) {sub("[.][^.]*$", "", fn); return fn} NR==FNR { fn[$1]; next} {for (e in fn){ if (base(e)==base($1)){ printf "%s,%s\n", e, $1 }}} ' f1 f2 file-1-2.txt,file-1-2.png file-3-4.txt,file-3-4.png ``` Since `awk` associative arrays are unordered, the order of the printout is determined by the order of the second file -- not the first. --- Explanation: 1. `function base(fn) {sub("[.][^.]*$", "", fn); return fn}` is a function that strips the extension from the filename (assuming that the extension is the non `.` characters to the right of the last `.` found. The entire name is returned if no `.` is found.) 2. `NR==FNR { fn[$1]; next}` read each line (each file name in this case) into an associative array. The `NR==FNR` is an `awk` idiom that is true only for the first file and `next` means the only this part is executed on the first file of file names. `$1` is used since the leading and trailing spaces are stripped. Since Unix filenames *can* have leading or trailing spaces, this is a rare ambiguity you need to resolve. If you don't want the lines stripped, you would use `$0` instead. 3. `{for (e in fn){ if (base(e)==base($1)){ printf "%s,%s\n", e, $1 }}}` now for any line other than from the first file (where `NR==FNR` is true since `next` skipped this part) loop through the saved file names. Print if the base name is the same.
Here's something fairly brute force: ``` file1="file1.txt" file2="file2.txt" out_file="out.txt" touch $out_file while read line ; do # read the first file line by line file1_name="$(echo "$line" | cut -d'.' -f1)" # get the filename without extension file2_name="$(grep "$file1_name\." $file2)" if [ -n "$file2_name" ]; then #did we find a match echo "$line,$file2_name" >> $out_file else echo "Did not find a match to ${line} in $file2" fi done < $file1 ``` We loop through file1 and look for matches in file 2. If found, we output to the output file. Other improvements: a better grep using regexp: ``` file2_name="$(grep -e "$file1_name\.[^.]*$" $file2)" ``` This looks for a line that starts with `$file1_name`, a dot `.` and then no more dots till the end which is the extension.
42,014,274
Haven't seen a solution similar enough to this yet... I have two files each containing a list of file names. There are overlap in the contents of the files but file A contain some file names that are not in file B. Also, the file extensions are different in files A and B. That is: ``` A B ------------ -------------- file-1-2.txt file-1-2.png file-2-3.txt file-3-4.png file-3-4.txt ... ``` How do I combine the two files, comma-delimited, into one ignoring lines that don't match? That is: ``` C ------------ file-1-2.txt,file-1-2.png file-3-4.txt,file-3-4.png ``` I believe some usage of `awk` similar to the following will work: ``` awk 'FNR==NR{NOT SURE} {print $1,$2}' fileA fileB ``` Thanks in advance!
2017/02/02
[ "https://Stackoverflow.com/questions/42014274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3741624/" ]
This pure bash solution should work and handle dots, backslashes, dashes, and other special characters in either file. ``` mapfile -t arr_a < A mapfile -t arr_b < B for a in "${arr_a[@]}"; do for b in "${arr_b[@]}"; do [[ ${a%.*} == "${b%.*}" ]] && printf '%s,%s\n' "$a" "$b" && break done; done ``` First, we read the contents of the files into arrays, one line per item, using `mapfile`. 1 Then, for each line in `A`, we compare to each line in `B`. To compare only the portion before the extension, we use the shell parameter expansion `${var%pattern}`, which removes the shortest match of the glob `.*`2 from the end of the filenames. 1The -t option strips the trailing newline from the array items. 2The `.` here is literal, removing a period and everything after.
You could do: ``` $ awk 'function base(fn) {sub("[.][^.]*$", "", fn); return fn} NR==FNR { fn[$1]; next} {for (e in fn){ if (base(e)==base($1)){ printf "%s,%s\n", e, $1 }}} ' f1 f2 file-1-2.txt,file-1-2.png file-3-4.txt,file-3-4.png ``` Since `awk` associative arrays are unordered, the order of the printout is determined by the order of the second file -- not the first. --- Explanation: 1. `function base(fn) {sub("[.][^.]*$", "", fn); return fn}` is a function that strips the extension from the filename (assuming that the extension is the non `.` characters to the right of the last `.` found. The entire name is returned if no `.` is found.) 2. `NR==FNR { fn[$1]; next}` read each line (each file name in this case) into an associative array. The `NR==FNR` is an `awk` idiom that is true only for the first file and `next` means the only this part is executed on the first file of file names. `$1` is used since the leading and trailing spaces are stripped. Since Unix filenames *can* have leading or trailing spaces, this is a rare ambiguity you need to resolve. If you don't want the lines stripped, you would use `$0` instead. 3. `{for (e in fn){ if (base(e)==base($1)){ printf "%s,%s\n", e, $1 }}}` now for any line other than from the first file (where `NR==FNR` is true since `next` skipped this part) loop through the saved file names. Print if the base name is the same.
42,014,274
Haven't seen a solution similar enough to this yet... I have two files each containing a list of file names. There are overlap in the contents of the files but file A contain some file names that are not in file B. Also, the file extensions are different in files A and B. That is: ``` A B ------------ -------------- file-1-2.txt file-1-2.png file-2-3.txt file-3-4.png file-3-4.txt ... ``` How do I combine the two files, comma-delimited, into one ignoring lines that don't match? That is: ``` C ------------ file-1-2.txt,file-1-2.png file-3-4.txt,file-3-4.png ``` I believe some usage of `awk` similar to the following will work: ``` awk 'FNR==NR{NOT SURE} {print $1,$2}' fileA fileB ``` Thanks in advance!
2017/02/02
[ "https://Stackoverflow.com/questions/42014274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3741624/" ]
This pure bash solution should work and handle dots, backslashes, dashes, and other special characters in either file. ``` mapfile -t arr_a < A mapfile -t arr_b < B for a in "${arr_a[@]}"; do for b in "${arr_b[@]}"; do [[ ${a%.*} == "${b%.*}" ]] && printf '%s,%s\n' "$a" "$b" && break done; done ``` First, we read the contents of the files into arrays, one line per item, using `mapfile`. 1 Then, for each line in `A`, we compare to each line in `B`. To compare only the portion before the extension, we use the shell parameter expansion `${var%pattern}`, which removes the shortest match of the glob `.*`2 from the end of the filenames. 1The -t option strips the trailing newline from the array items. 2The `.` here is literal, removing a period and everything after.
Here's something fairly brute force: ``` file1="file1.txt" file2="file2.txt" out_file="out.txt" touch $out_file while read line ; do # read the first file line by line file1_name="$(echo "$line" | cut -d'.' -f1)" # get the filename without extension file2_name="$(grep "$file1_name\." $file2)" if [ -n "$file2_name" ]; then #did we find a match echo "$line,$file2_name" >> $out_file else echo "Did not find a match to ${line} in $file2" fi done < $file1 ``` We loop through file1 and look for matches in file 2. If found, we output to the output file. Other improvements: a better grep using regexp: ``` file2_name="$(grep -e "$file1_name\.[^.]*$" $file2)" ``` This looks for a line that starts with `$file1_name`, a dot `.` and then no more dots till the end which is the extension.
8,797,791
I'm trying to run a simple `test\spec` but getting an error. Error is only happening when the tests fail. ``` begin require 'rubygems' require 'test/spec' rescue LoadError puts "==> you need test/spec to run tests. {sudo gem install test-spec}" end context "Foo" do specify "should bar" do "ttes".should.equal "tes" end end ``` > > 1) Error: test\_spec {Foo} 001 should bar: NoMethodError: > undefined method `ascii_compatible?' for #<Encoding:US-ASCII> > person.rb:11:in`block (2 levels) in ' > > >
2012/01/10
[ "https://Stackoverflow.com/questions/8797791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44286/" ]
I can only guess, but there is something very strange going on here. Are you mixing Ruby versions or something? Are you using a gem that's not compatible with your version of Ruby? Every encoding instance should respond to [`ascii_compatible?`](http://apidock.com/ruby/Encoding/ascii_compatible%3F) in Ruby 1.9, so maybe you are using 1.8 (as you seem to be on Windows, this seems likely). Also, a full stack trace will be of great help (you can catch the exception with `begin`/`rescue` and call [`backtrace`](http://apidock.com/ruby/Exception/backtrace) on it. That way you will find out which exact line of the `test-spec` module fails. Also, *test-spec* doesn't seem to be a very actively developed Gem. Maybe an option is to use [*RSpec*](https://www.relishapp.com/rspec) instead, a more widely used tool with the same purpose.
I was getting a similar problem running Ruby 1.9.1 on Windows. My environment had been previously set up to run Ruby for some scripting of automated tests for embedded development. I tried installing 1.9.3, but the problem was still there. Eventually uninstalled both 1.9.1 and 1.9.3, re-installed Ruby 1.9.3 and test-unit gem (2.4.5) and everything works OK now.
8,797,791
I'm trying to run a simple `test\spec` but getting an error. Error is only happening when the tests fail. ``` begin require 'rubygems' require 'test/spec' rescue LoadError puts "==> you need test/spec to run tests. {sudo gem install test-spec}" end context "Foo" do specify "should bar" do "ttes".should.equal "tes" end end ``` > > 1) Error: test\_spec {Foo} 001 should bar: NoMethodError: > undefined method `ascii_compatible?' for #<Encoding:US-ASCII> > person.rb:11:in`block (2 levels) in ' > > >
2012/01/10
[ "https://Stackoverflow.com/questions/8797791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44286/" ]
I can only guess, but there is something very strange going on here. Are you mixing Ruby versions or something? Are you using a gem that's not compatible with your version of Ruby? Every encoding instance should respond to [`ascii_compatible?`](http://apidock.com/ruby/Encoding/ascii_compatible%3F) in Ruby 1.9, so maybe you are using 1.8 (as you seem to be on Windows, this seems likely). Also, a full stack trace will be of great help (you can catch the exception with `begin`/`rescue` and call [`backtrace`](http://apidock.com/ruby/Exception/backtrace) on it. That way you will find out which exact line of the `test-spec` module fails. Also, *test-spec* doesn't seem to be a very actively developed Gem. Maybe an option is to use [*RSpec*](https://www.relishapp.com/rspec) instead, a more widely used tool with the same purpose.
My version of Ruby 1.9.1 had a gems that depended upon 'test-unit'. At least one of them forced the install of test-unit-2.4.7. For me, removing the 'test-unit-2.4.7' gem solved the problem. In test-unit-2.4.7 we have this code: ``` in /home/davei/.gem/ruby/1.9.1/gems/test-unit-2.4.7/lib/test/unit/assertions.rb 1483 1484 def ensure_diffable_string(string) 1485 if string.respond_to?(:encoding) and => 1486 !string.encoding.ascii_compatible? 1487 string = string.dup.force_encoding("ASCII-8BIT") 1488 end 1489 string 1490 end ``` Perhaps every instance of Encoding should support the 'ascii\_compatible?' method, but that is not the case in Ruby 1.9.1p378. See for yourself: ``` (rdb:1) p string.encoding #<Encoding:US-ASCII> (rdb:1) p string.encoding.public_methods [:to_s, :inspect, :name, :names, :dummy?, :_dump, :dbg, :pretty_print, :pretty_print_cycle, :pretty_print_instance_variables, :pretty_print_inspect, :nil?, :===, :=~, :!~, :eql?, :class, :clone, :dup, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :freeze, :frozen?, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :extend, :display, :method, :public_method, :define_singleton_method, :hash, :__id__, :object_id, :to_enum, :enum_for, :gem, :pretty_inspect, :==, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__] ``` I found 'ascii\_compatible?' missing for Encoding:UTF-8 as well.
48,073,506
I did a lot of research on the web, but did not find a documentation of the composer error log. In the discussions I found, nobody had an explanation that was consistent with the error log. For example: * [[Support] Need explanation for "Conclusion: don't install ..."](https://github.com/composer/composer/issues/2702) * [Why composer says "Conclusion: don't install" when (seemingly) no obstacles are present?](https://stackoverflow.com/q/45009772) I know, what composer does and can resolve issues on my own, but I often have to consult packagist.org for this. Despite being quite (and unnecessarily) verbose, the composer log only gives me some hints. It does not really point out the concrete problems. Does anyone know of a complete documentation or how to explain the reasoning behind the logs, maybe taking the above ones as an example?
2018/01/03
[ "https://Stackoverflow.com/questions/48073506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/486218/" ]
Documentation of Composer can be found at [getcomposer.org/doc](https://getcomposer.org/doc/), especially [Troubleshooting](https://getcomposer.org/doc/articles/troubleshooting.md) section. Usually the dependency problems comes from misconfiguration of your `composer.json` and understanding Composer logs comes with experience or learning on trial and error. Documenting every possible errors out of hundreds can become quickly outdated. If you believe some specific error isn't clear enough, you can always raise a [new suggestion](https://github.com/composer/composer/issues) at the [Composer's GitHub page](https://github.com/composer/composer). As suggested in linked [GitHub issue](https://github.com/composer/composer/issues/2702), "Conclusion: don't install" message it could be related to requirements defined in [`minimum-stability`](https://getcomposer.org/doc/04-schema.md#minimum-stability). Another [linked question](https://stackoverflow.com/q/45009772/55075) could be related to Composer's bug as reported at [GH-7215](https://github.com/composer/composer/issues/7215). ### Errors Here is a small guide explaining the common Composer's errors: * > > **Can only install one** of: org/package[x.y.z, X.Y.Z]. > > > If you see this messages, that could be the main cause of the dependency issue. It basically means that based on the Composer's dependency calculation both of these versions are required, but only one major version can be installed (you cannot have both x.y.z and X.Y.Z, unless you split your configuration for different folders). To see `why` these packages are required, use the `composer why`/`depends` command and adjust the dependencies accordingly. See: [How to resolve a "Can only install one of:" conflict?](https://stackoverflow.com/q/36611550/55075) & [How to solve two packages requirements conflicts when running composer install?](https://stackoverflow.com/q/21052831/55075) * > > Installation request for org/package2 (**locked at** vX.Y.Z) > > > This message means that there was an installation request for org/package, however, it is locked at X.Y.Z. If the requested version is not compatible with the locked version (like a different major version), you cannot install both. This message often comes along with already mentioned "Can only install one" one. So, whenever you see "locked at", that means Composer reads your installed package version from the `composer.lock` file. To troubleshoot, you can use `composer why`/`depends` command to find why the package was requested and adjust the compatibility, otherwise, you may try to remove `composer.lock` file and start from scratch (ideally from the empty folder). See: [Installation failed for laravel/lumen-installer: guzzlehttp/guzzle locked at 6.3.0](https://stackoverflow.com/q/48427886/55075) * > > org/package1 vx.y.z **conflicts** with org/package2[vX.Y.Z]. > > > It is a similar issue as above where two packages are conflicting and you need to solve the dependency manually. Reading the whole context of the message may give you some more clues. Checking the dependency tree may also help (`composer show -t`). * > > conflict with your requirements or **`minimum-stability`** > > > This message means as it reads, so you should check the required version and/or your `minimum-stability` settings. This can be caused by a package being marked as non-stable and your requirements being "stable only. See: [But these conflict with your requirements or minimum-stability](https://stackoverflow.com/q/40453388/55075) Or because of conflicts with other installed packages. See: [How to identify what is preventing Composer from installing latest version of a package?](https://stackoverflow.com/q/45386572/1426539). For any other errors, check out the official **[Composer's Troubleshooting page](https://getcomposer.org/doc/articles/troubleshooting.md)**. ### Troubleshooting Here are more suggestions how to troubleshoot the Composer dependency issues in general: * Add `-v`/`-vv`/`-vvv` parameter to your command for more verbose output. * Run `composer diagnose` to check for common errors to help debugging problems. * If you seeing "locked at x.y.z" messages, it relates to packages locked in your `composer.lock`. * Test your `composer.json` on the empty folder. * Keep your `composer.json` to minimum. * Run `composer show -t` to see your current dependency tree. * Run `composer show -a org/package x.y.z` to check the details about the package. * Feel free to ask a new question at *Stack Overflow*. To fully debug Composer's dependency problem, you can: * Analyse or modify the source code (e.g. [`DependencyResolver/Problem.php`](https://github.com/composer/composer/blob/master/src/Composer/DependencyResolver/Problem.php)). * Run Composer under [XDebug](https://xdebug.org/), either by the breakpoint or generating a full or partial trace file. --- Useful threads explaining common errors: * [How to resolve a "Can only install one of:" conflict?](https://stackoverflow.com/q/36611550/55075) * [composer.json fails to resolve installable set of package](https://stackoverflow.com/q/16672993/55075) * [Discover latest versions of Composer packages when dependencies are locked](https://stackoverflow.com/q/30277015/55075) * [When trying to install php-jwt facing trouble with auth0](https://stackoverflow.com/q/42532831/55075) * [Reference - Composer error "Your PHP version does not satisfy requirements" after upgrading PHP](https://stackoverflow.com/q/66368196/) * [How to identify what is preventing Composer from installing latest version of a package?](https://stackoverflow.com/q/45386572/1426539)
### Error: > > somevendor/somepackage[v1.0.0, ..., v1.9.1] require composer-plugin-api ~[X.X] > > > This means that that `somevendor/somepacakge` requires that a specific version range of Composer to be installed. Run `composer -v` and compare it to the version constraint in the error message (shown as `~X.X` in the example above, but that could be something like `^1.0`, or `^2.2`, etc). If your version does not match the constraint, see if you can either: * [upgrade or downgrade](https://stackoverflow.com/a/64598028/1426539) your composer version to match the composer constraint in the error message * upgrade `somevendor/somepackage` so that it can work with your Composer version.
35,661,088
I am new to bootstrap and I am attempting to learn the basics. However, I have put a color background for the div and it is only appears when I have resize the browser. Here is my code: ``` <html> <body> <div id="header"> <div class="col-md-8"><img src="images/logo.png"></div> <div class="col-md-4"> <br /> <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <p> <a href="#">HOME</a> &nbsp; &nbsp; &nbsp; <a href="#">SERVICES</a> &nbsp;&nbsp;&nbsp; <a href="#">NEWS</a> &nbsp;&nbsp;&nbsp; <a href="#">CAREERS</a> &nbsp;&nbsp;&nbsp; <a href="#">CONTACT</a> </p> </div> </div> </body> </html> .container { margin:0px; padding:0px; } #header{ background-color:#e4e4e4; } ``` Thank you in advance.
2016/02/26
[ "https://Stackoverflow.com/questions/35661088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5335546/" ]
You might want to try something like this. You will have to replace the hard coded elements... ```js var fruits = ["Apple", "Banana"]; var tempString = "Pie,Dumpling,Cider"; var tempArray = new Array(); tempArray.push(tempString); tempString = "Bread,Republic"; tempArray.push(tempString); var output = {}; for (var i = 0; i < fruits.length; i++) { var members = tempArray[i].split(","); var temp = {}; for(var k = 0; k < members.length; k++) { temp[("" + k)] = members[k]; } output[("" + fruits[i])] = temp; } console.log(output); //Different ways to access the objects console.log(output.Apple); console.log(output["Apple"]); console.log(output.Banana[0]); console.log(output["Banana"]["0"]); ``` [![enter image description here](https://i.stack.imgur.com/zS7gB.png)](https://i.stack.imgur.com/zS7gB.png)
try this: ``` var fruits = ["Apple", "Banana"], i, k, members, tmp, output = []; var final = []; for (i=0; i < fruits.length; ++i) { members = document.getElementById(fruits[i]).getAttribute("data-makes"); tmp = members.split(","); output[i] = new Object(); for (k=0; k < tmp.length; ++k) { output[i][k+1] = tmp[k]; } final.push(fruits[i]) final.push(output[i]) } console.log(final); ```
35,661,088
I am new to bootstrap and I am attempting to learn the basics. However, I have put a color background for the div and it is only appears when I have resize the browser. Here is my code: ``` <html> <body> <div id="header"> <div class="col-md-8"><img src="images/logo.png"></div> <div class="col-md-4"> <br /> <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <p> <a href="#">HOME</a> &nbsp; &nbsp; &nbsp; <a href="#">SERVICES</a> &nbsp;&nbsp;&nbsp; <a href="#">NEWS</a> &nbsp;&nbsp;&nbsp; <a href="#">CAREERS</a> &nbsp;&nbsp;&nbsp; <a href="#">CONTACT</a> </p> </div> </div> </body> </html> .container { margin:0px; padding:0px; } #header{ background-color:#e4e4e4; } ``` Thank you in advance.
2016/02/26
[ "https://Stackoverflow.com/questions/35661088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5335546/" ]
Here's an alternative method you might find useful in the future. ``` // loop over the fruits var arr = fruits.reduce(function (fp, fc) { // get the string (in your example the data-makes value) // and add each to a new object var temp = makes[fc].split(', ').reduce(function (p, c, i) { p[i + 1] = c; return p; }, {}); // then concatenate the fruit name and its object to // the output array return fp.concat.apply(fp, [fc, temp]); }, []); ``` OUTPUT ``` [ "Apple", { "1": "pie", "2": "dumpling", "3": "cider"}, "Banana", { "1": "bread", "2": "Republic" } ] ``` [DEMO](https://jsfiddle.net/ezzk4tmr/1/)
try this: ``` var fruits = ["Apple", "Banana"], i, k, members, tmp, output = []; var final = []; for (i=0; i < fruits.length; ++i) { members = document.getElementById(fruits[i]).getAttribute("data-makes"); tmp = members.split(","); output[i] = new Object(); for (k=0; k < tmp.length; ++k) { output[i][k+1] = tmp[k]; } final.push(fruits[i]) final.push(output[i]) } console.log(final); ```
35,661,088
I am new to bootstrap and I am attempting to learn the basics. However, I have put a color background for the div and it is only appears when I have resize the browser. Here is my code: ``` <html> <body> <div id="header"> <div class="col-md-8"><img src="images/logo.png"></div> <div class="col-md-4"> <br /> <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <p> <a href="#">HOME</a> &nbsp; &nbsp; &nbsp; <a href="#">SERVICES</a> &nbsp;&nbsp;&nbsp; <a href="#">NEWS</a> &nbsp;&nbsp;&nbsp; <a href="#">CAREERS</a> &nbsp;&nbsp;&nbsp; <a href="#">CONTACT</a> </p> </div> </div> </body> </html> .container { margin:0px; padding:0px; } #header{ background-color:#e4e4e4; } ``` Thank you in advance.
2016/02/26
[ "https://Stackoverflow.com/questions/35661088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5335546/" ]
You might want to try something like this. You will have to replace the hard coded elements... ```js var fruits = ["Apple", "Banana"]; var tempString = "Pie,Dumpling,Cider"; var tempArray = new Array(); tempArray.push(tempString); tempString = "Bread,Republic"; tempArray.push(tempString); var output = {}; for (var i = 0; i < fruits.length; i++) { var members = tempArray[i].split(","); var temp = {}; for(var k = 0; k < members.length; k++) { temp[("" + k)] = members[k]; } output[("" + fruits[i])] = temp; } console.log(output); //Different ways to access the objects console.log(output.Apple); console.log(output["Apple"]); console.log(output.Banana[0]); console.log(output["Banana"]["0"]); ``` [![enter image description here](https://i.stack.imgur.com/zS7gB.png)](https://i.stack.imgur.com/zS7gB.png)
First, remember that JSON keys are always Strings -- no integers. ``` ["Apple", "Banana"] // data-makes="Pie,Dumpling,Cider", data-makes="Bread,Republic" var output = []; var type; var fruits = ["Apple", "Banana"]; for (i=0; i < fruits.length; ++i) { members = document.getElementById(fruits[i]).getAttribute("data-makes"); tmp = members.split(","); for (k=0; k < tmp.length; ++k) { type = {} type[fruits[i]] = {} type[fruits[i]][k] = tmp[k] output.push(type); } } ``` This will output: ``` [ { "apple" : { "1" : "pie", "2" : "Dumpling", "3" : "Cider" } }, { "banana" : { "1" : "Bread", "2" : "Republic" } ] ``` Not exactly what you asked (I can't imagine the use of a 1-D array for this, but you can get the point)
35,661,088
I am new to bootstrap and I am attempting to learn the basics. However, I have put a color background for the div and it is only appears when I have resize the browser. Here is my code: ``` <html> <body> <div id="header"> <div class="col-md-8"><img src="images/logo.png"></div> <div class="col-md-4"> <br /> <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <p> <a href="#">HOME</a> &nbsp; &nbsp; &nbsp; <a href="#">SERVICES</a> &nbsp;&nbsp;&nbsp; <a href="#">NEWS</a> &nbsp;&nbsp;&nbsp; <a href="#">CAREERS</a> &nbsp;&nbsp;&nbsp; <a href="#">CONTACT</a> </p> </div> </div> </body> </html> .container { margin:0px; padding:0px; } #header{ background-color:#e4e4e4; } ``` Thank you in advance.
2016/02/26
[ "https://Stackoverflow.com/questions/35661088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5335546/" ]
You might want to try something like this. You will have to replace the hard coded elements... ```js var fruits = ["Apple", "Banana"]; var tempString = "Pie,Dumpling,Cider"; var tempArray = new Array(); tempArray.push(tempString); tempString = "Bread,Republic"; tempArray.push(tempString); var output = {}; for (var i = 0; i < fruits.length; i++) { var members = tempArray[i].split(","); var temp = {}; for(var k = 0; k < members.length; k++) { temp[("" + k)] = members[k]; } output[("" + fruits[i])] = temp; } console.log(output); //Different ways to access the objects console.log(output.Apple); console.log(output["Apple"]); console.log(output.Banana[0]); console.log(output["Banana"]["0"]); ``` [![enter image description here](https://i.stack.imgur.com/zS7gB.png)](https://i.stack.imgur.com/zS7gB.png)
You have two problems in your code: First, you're never putting `fruits[i]` in the `output` array. Second, you can't assign to `output[i][k+1]` until you first initialize `output[i]` to be an array or object. ``` for (i=0; i < fruits.length; ++i) { output.push(fruits[i]); var members = document.getElementById(fruits[i]).getAttribute("data-makes"); var tmp = members.split(","); var obj = {}; for (k=0; k < tmp.length; ++k) { obj[k+1] = tmp[k]; } output.push(obj); } ```
35,661,088
I am new to bootstrap and I am attempting to learn the basics. However, I have put a color background for the div and it is only appears when I have resize the browser. Here is my code: ``` <html> <body> <div id="header"> <div class="col-md-8"><img src="images/logo.png"></div> <div class="col-md-4"> <br /> <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <p> <a href="#">HOME</a> &nbsp; &nbsp; &nbsp; <a href="#">SERVICES</a> &nbsp;&nbsp;&nbsp; <a href="#">NEWS</a> &nbsp;&nbsp;&nbsp; <a href="#">CAREERS</a> &nbsp;&nbsp;&nbsp; <a href="#">CONTACT</a> </p> </div> </div> </body> </html> .container { margin:0px; padding:0px; } #header{ background-color:#e4e4e4; } ``` Thank you in advance.
2016/02/26
[ "https://Stackoverflow.com/questions/35661088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5335546/" ]
You might want to try something like this. You will have to replace the hard coded elements... ```js var fruits = ["Apple", "Banana"]; var tempString = "Pie,Dumpling,Cider"; var tempArray = new Array(); tempArray.push(tempString); tempString = "Bread,Republic"; tempArray.push(tempString); var output = {}; for (var i = 0; i < fruits.length; i++) { var members = tempArray[i].split(","); var temp = {}; for(var k = 0; k < members.length; k++) { temp[("" + k)] = members[k]; } output[("" + fruits[i])] = temp; } console.log(output); //Different ways to access the objects console.log(output.Apple); console.log(output["Apple"]); console.log(output.Banana[0]); console.log(output["Banana"]["0"]); ``` [![enter image description here](https://i.stack.imgur.com/zS7gB.png)](https://i.stack.imgur.com/zS7gB.png)
Here's an alternative method you might find useful in the future. ``` // loop over the fruits var arr = fruits.reduce(function (fp, fc) { // get the string (in your example the data-makes value) // and add each to a new object var temp = makes[fc].split(', ').reduce(function (p, c, i) { p[i + 1] = c; return p; }, {}); // then concatenate the fruit name and its object to // the output array return fp.concat.apply(fp, [fc, temp]); }, []); ``` OUTPUT ``` [ "Apple", { "1": "pie", "2": "dumpling", "3": "cider"}, "Banana", { "1": "bread", "2": "Republic" } ] ``` [DEMO](https://jsfiddle.net/ezzk4tmr/1/)
35,661,088
I am new to bootstrap and I am attempting to learn the basics. However, I have put a color background for the div and it is only appears when I have resize the browser. Here is my code: ``` <html> <body> <div id="header"> <div class="col-md-8"><img src="images/logo.png"></div> <div class="col-md-4"> <br /> <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <p> <a href="#">HOME</a> &nbsp; &nbsp; &nbsp; <a href="#">SERVICES</a> &nbsp;&nbsp;&nbsp; <a href="#">NEWS</a> &nbsp;&nbsp;&nbsp; <a href="#">CAREERS</a> &nbsp;&nbsp;&nbsp; <a href="#">CONTACT</a> </p> </div> </div> </body> </html> .container { margin:0px; padding:0px; } #header{ background-color:#e4e4e4; } ``` Thank you in advance.
2016/02/26
[ "https://Stackoverflow.com/questions/35661088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5335546/" ]
Here's an alternative method you might find useful in the future. ``` // loop over the fruits var arr = fruits.reduce(function (fp, fc) { // get the string (in your example the data-makes value) // and add each to a new object var temp = makes[fc].split(', ').reduce(function (p, c, i) { p[i + 1] = c; return p; }, {}); // then concatenate the fruit name and its object to // the output array return fp.concat.apply(fp, [fc, temp]); }, []); ``` OUTPUT ``` [ "Apple", { "1": "pie", "2": "dumpling", "3": "cider"}, "Banana", { "1": "bread", "2": "Republic" } ] ``` [DEMO](https://jsfiddle.net/ezzk4tmr/1/)
First, remember that JSON keys are always Strings -- no integers. ``` ["Apple", "Banana"] // data-makes="Pie,Dumpling,Cider", data-makes="Bread,Republic" var output = []; var type; var fruits = ["Apple", "Banana"]; for (i=0; i < fruits.length; ++i) { members = document.getElementById(fruits[i]).getAttribute("data-makes"); tmp = members.split(","); for (k=0; k < tmp.length; ++k) { type = {} type[fruits[i]] = {} type[fruits[i]][k] = tmp[k] output.push(type); } } ``` This will output: ``` [ { "apple" : { "1" : "pie", "2" : "Dumpling", "3" : "Cider" } }, { "banana" : { "1" : "Bread", "2" : "Republic" } ] ``` Not exactly what you asked (I can't imagine the use of a 1-D array for this, but you can get the point)
35,661,088
I am new to bootstrap and I am attempting to learn the basics. However, I have put a color background for the div and it is only appears when I have resize the browser. Here is my code: ``` <html> <body> <div id="header"> <div class="col-md-8"><img src="images/logo.png"></div> <div class="col-md-4"> <br /> <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <p> <a href="#">HOME</a> &nbsp; &nbsp; &nbsp; <a href="#">SERVICES</a> &nbsp;&nbsp;&nbsp; <a href="#">NEWS</a> &nbsp;&nbsp;&nbsp; <a href="#">CAREERS</a> &nbsp;&nbsp;&nbsp; <a href="#">CONTACT</a> </p> </div> </div> </body> </html> .container { margin:0px; padding:0px; } #header{ background-color:#e4e4e4; } ``` Thank you in advance.
2016/02/26
[ "https://Stackoverflow.com/questions/35661088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5335546/" ]
Here's an alternative method you might find useful in the future. ``` // loop over the fruits var arr = fruits.reduce(function (fp, fc) { // get the string (in your example the data-makes value) // and add each to a new object var temp = makes[fc].split(', ').reduce(function (p, c, i) { p[i + 1] = c; return p; }, {}); // then concatenate the fruit name and its object to // the output array return fp.concat.apply(fp, [fc, temp]); }, []); ``` OUTPUT ``` [ "Apple", { "1": "pie", "2": "dumpling", "3": "cider"}, "Banana", { "1": "bread", "2": "Republic" } ] ``` [DEMO](https://jsfiddle.net/ezzk4tmr/1/)
You have two problems in your code: First, you're never putting `fruits[i]` in the `output` array. Second, you can't assign to `output[i][k+1]` until you first initialize `output[i]` to be an array or object. ``` for (i=0; i < fruits.length; ++i) { output.push(fruits[i]); var members = document.getElementById(fruits[i]).getAttribute("data-makes"); var tmp = members.split(","); var obj = {}; for (k=0; k < tmp.length; ++k) { obj[k+1] = tmp[k]; } output.push(obj); } ```
40,378
I am performing 10-folds cross-validation to evaluate the performances of a series of models (variable selection + regression) with R. I created manually the folds with this [code](https://stats.stackexchange.com/questions/61090/how-to-split-a-data-set-to-do-10-fold-cross-validation). At the moment I'm performing first variable selection, then hyperparameters tuning through cv, and finally testing the performance with RMSE and MAE for all the models, but I have a doubt. Is it correct to "use" the same fold for all the models? Or should I do a separate cv for each model?
2018/10/29
[ "https://datascience.stackexchange.com/questions/40378", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/56923/" ]
I recommend trying both (more than once), and exploring any differences. In my experience, using the same set of folds for all models or using a new set of folds for each model doesn't make any material difference. Post if you find different! Regarding "I'm performing first variable selection, then hyperparameters tuning through cv", maybe watch <https://www.youtube.com/watch?reload=9&v=S06JpVoNaA0> to be sure you are not introducing any bias.
If you want to evaluate the performance of different models i.e. Model Benchmarking, it is necessary to keep the input environment same i.e. any external input like CV (number of folds). While you can tune the model-specific parameters to optimize the model.
40,378
I am performing 10-folds cross-validation to evaluate the performances of a series of models (variable selection + regression) with R. I created manually the folds with this [code](https://stats.stackexchange.com/questions/61090/how-to-split-a-data-set-to-do-10-fold-cross-validation). At the moment I'm performing first variable selection, then hyperparameters tuning through cv, and finally testing the performance with RMSE and MAE for all the models, but I have a doubt. Is it correct to "use" the same fold for all the models? Or should I do a separate cv for each model?
2018/10/29
[ "https://datascience.stackexchange.com/questions/40378", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/56923/" ]
I recommend trying both (more than once), and exploring any differences. In my experience, using the same set of folds for all models or using a new set of folds for each model doesn't make any material difference. Post if you find different! Regarding "I'm performing first variable selection, then hyperparameters tuning through cv", maybe watch <https://www.youtube.com/watch?reload=9&v=S06JpVoNaA0> to be sure you are not introducing any bias.
IMHO I would use the same fold for all models. First of all it can be reproducible and you are evaluating all models with the same data. So it's the same environment for benchmarking. Also you can use folds predictions for stacking. ps: You can try to use validation set for hyperparameters tuning.
26,231,939
I am learning Laravel as my first framework, I saw, they have own syntax for create forms eg: Laravel Inputs: ``` {{ Form::text('email', '', array('placeholder' => 'Email')) }} {{ Form::password('password', array('placeholder' => 'Password')) }} {{ Form::submit('Login', array('class' => 'btn btn-success')) }} ``` HTML Inputs: ``` <input type="text" name="email" placeholder="Email"/> <input type="password" name="password" placeholder="Password"/> <input type="submit" name="submit" value="Login" class="btn btn-success"/> ``` what are the advantages, I can get, if i use Laravel syntax for create forms? thank you
2014/10/07
[ "https://Stackoverflow.com/questions/26231939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3099298/" ]
There are many advantages of using the Laravel syntax. 1. The Laravel Form automatically adds CSRF protection . 2. You can autofill form easily using the Form::model() instead of the plain PHP. 3. Your code remains clean and consistent and is not filled with a mix of HTML and PHP 4. It gives extensibility i.e others can dynamically insert form elements. This is useful only if you are building a software for others to use.
* Cleaner syntax. Compare for example a traditional HTML select vs using [`Form::select('name', $array)`](http://laravel.com/docs/4.2/html#drop-down-lists). * Integrated [CSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) protection. * Integrated URLs to named routes, actions and RESTful controllers of your application. If use routes in your form URL and you cange a route URL all your models will still work. * [Form Model Binding](http://laravel.com/docs/4.2/html#form-model-binding) to populate form with data from your models. * Automatic form fields population with flash (old) input. * Extendable and customizable with macros. Think if all your fields need a class but that class may change on future. If you use a macro to set that class when it changes in the future you only have to update one line of code instead of all your views. * Possible integration with popular CSS frameworks to add their look and field + automatic error appending. [example](https://github.com/stevenmaguire/zurb-foundation-laravel)
26,231,939
I am learning Laravel as my first framework, I saw, they have own syntax for create forms eg: Laravel Inputs: ``` {{ Form::text('email', '', array('placeholder' => 'Email')) }} {{ Form::password('password', array('placeholder' => 'Password')) }} {{ Form::submit('Login', array('class' => 'btn btn-success')) }} ``` HTML Inputs: ``` <input type="text" name="email" placeholder="Email"/> <input type="password" name="password" placeholder="Password"/> <input type="submit" name="submit" value="Login" class="btn btn-success"/> ``` what are the advantages, I can get, if i use Laravel syntax for create forms? thank you
2014/10/07
[ "https://Stackoverflow.com/questions/26231939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3099298/" ]
There are many advantages of using the Laravel syntax. 1. The Laravel Form automatically adds CSRF protection . 2. You can autofill form easily using the Form::model() instead of the plain PHP. 3. Your code remains clean and consistent and is not filled with a mix of HTML and PHP 4. It gives extensibility i.e others can dynamically insert form elements. This is useful only if you are building a software for others to use.
Laravel's [Blade synta](http://laravel.com/docs/4.2/templates)x based on ASP.NET's Razor can be very useful because it allows for template inheritance and it has useful syntax sugar for control structures like `if` and `for` and it helps with CSRF by assigning a token to your forms and verifying it when they're posted. Also it allows you to bind your model to a form and have the framework itself worry about filling out all the form fields. You can also even extend it by defining your own custom control structures.
26,231,939
I am learning Laravel as my first framework, I saw, they have own syntax for create forms eg: Laravel Inputs: ``` {{ Form::text('email', '', array('placeholder' => 'Email')) }} {{ Form::password('password', array('placeholder' => 'Password')) }} {{ Form::submit('Login', array('class' => 'btn btn-success')) }} ``` HTML Inputs: ``` <input type="text" name="email" placeholder="Email"/> <input type="password" name="password" placeholder="Password"/> <input type="submit" name="submit" value="Login" class="btn btn-success"/> ``` what are the advantages, I can get, if i use Laravel syntax for create forms? thank you
2014/10/07
[ "https://Stackoverflow.com/questions/26231939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3099298/" ]
* Cleaner syntax. Compare for example a traditional HTML select vs using [`Form::select('name', $array)`](http://laravel.com/docs/4.2/html#drop-down-lists). * Integrated [CSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) protection. * Integrated URLs to named routes, actions and RESTful controllers of your application. If use routes in your form URL and you cange a route URL all your models will still work. * [Form Model Binding](http://laravel.com/docs/4.2/html#form-model-binding) to populate form with data from your models. * Automatic form fields population with flash (old) input. * Extendable and customizable with macros. Think if all your fields need a class but that class may change on future. If you use a macro to set that class when it changes in the future you only have to update one line of code instead of all your views. * Possible integration with popular CSS frameworks to add their look and field + automatic error appending. [example](https://github.com/stevenmaguire/zurb-foundation-laravel)
Laravel's [Blade synta](http://laravel.com/docs/4.2/templates)x based on ASP.NET's Razor can be very useful because it allows for template inheritance and it has useful syntax sugar for control structures like `if` and `for` and it helps with CSRF by assigning a token to your forms and verifying it when they're posted. Also it allows you to bind your model to a form and have the framework itself worry about filling out all the form fields. You can also even extend it by defining your own custom control structures.
908,077
I'm looking at the PayPal `IPN docs`, and it says the `datetime` stamps of their strings are formatted as: ``` HH:MM:SS DD Mmm YY, YYYY PST ``` So year is specified twice? Once in double digits, and another with 4 digits? This looks bizarre.
2009/05/25
[ "https://Stackoverflow.com/questions/908077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73398/" ]
This seems to be a bug in the documentation. The actual format should be "HH:MM:SS Mmm DD, YYYY PST" (e.g. "08:30:06 Apr 19, 2017 PDT")
Complete date plus hours, minutes, seconds and a decimal fraction of a second YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) Where TZD = time zone designator (Z or +hh:mm or -hh:mm) Example 1994-11-05T08:15:30-05:00 corresponds to November 5, 1994, 8:15:30 am, US Eastern Standard Time. 1994-11-05T13:15:30Z corresponds to the same instant. <https://www.w3.org/TR/NOTE-datetime>
908,077
I'm looking at the PayPal `IPN docs`, and it says the `datetime` stamps of their strings are formatted as: ``` HH:MM:SS DD Mmm YY, YYYY PST ``` So year is specified twice? Once in double digits, and another with 4 digits? This looks bizarre.
2009/05/25
[ "https://Stackoverflow.com/questions/908077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73398/" ]
Complete date plus hours, minutes, seconds and a decimal fraction of a second YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) Where TZD = time zone designator (Z or +hh:mm or -hh:mm) Example 1994-11-05T08:15:30-05:00 corresponds to November 5, 1994, 8:15:30 am, US Eastern Standard Time. 1994-11-05T13:15:30Z corresponds to the same instant. <https://www.w3.org/TR/NOTE-datetime>
Actually, I think the right format is: yyyy-MM-ddTHH:MM:ssZ The case is important.
908,077
I'm looking at the PayPal `IPN docs`, and it says the `datetime` stamps of their strings are formatted as: ``` HH:MM:SS DD Mmm YY, YYYY PST ``` So year is specified twice? Once in double digits, and another with 4 digits? This looks bizarre.
2009/05/25
[ "https://Stackoverflow.com/questions/908077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73398/" ]
this is the correct format according to their documentation - 2010-03-27T12:34:49Z so it is - YYYY-MM-DDTHH:MM:SSZ (I don't know what the T in the middle and Z is but it's constant for all the dates) I've created PayPal NVP library in Java, so if you want to check how it works, or use it, you are more than welcome. it's on sourceforge - payapal-nvp.sourceforge.net
Complete date plus hours, minutes, seconds and a decimal fraction of a second YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) Where TZD = time zone designator (Z or +hh:mm or -hh:mm) Example 1994-11-05T08:15:30-05:00 corresponds to November 5, 1994, 8:15:30 am, US Eastern Standard Time. 1994-11-05T13:15:30Z corresponds to the same instant. <https://www.w3.org/TR/NOTE-datetime>