qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
11,226,026
I got confused with async nature of node.js. I'm writing a small project in it and my previous (sync) programming experience gets in the way. How should I decide if/where to write async code? For example I've got a model with fields, where each has some validation rules: ``` model = { title: text_validation, subtitle: text_validation } text_validation = { max_len: 10, required: true, url: true } ``` When I validate the model, I iterate through all fields checking if rules pass - these are really quick functions. ``` Model.validate = function() { validator = {}; fields = Object.keys(Model); fields.forEach(function(field) { validator[field_name] = field.validate(); }); } Field.validate = function() { validator = []; rules.forEach(function(rule) { if (rule is not valid) validator.push(rule) }); return validator; } ``` Should I use callbacks with such short and quick iterations? Where is the limit here? Should node.js be always async or can I allow sync loops or w/e if it's quick enough? Please, if possible refer to examples when and where to use sync/async.
2012/06/27
[ "https://Stackoverflow.com/questions/11226026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/467736/" ]
You probably shouldn't. In most cases, you need async logic only when you're waiting for something from outside your application (mostly file, database and network operations). Delaying in-application code asynchronously will give you no performance advantage, as your code will still need to run *at some point*.
I already said that in comment, but I think it is a good idea to give examples as well. The concepts of *callback* and *asynchrounous operations* are different, although related. The `forEach` loop you are using **is not** asynchronous at all. Here's how more or less the definition of `forEach` looks: ``` Array.prototype.forEach = function(callback) { var l = this.length; for (var i = 0; i < l; i++) callback(this[i], i); }; ``` As you can see there is nothing asynchronous in this. The `callback` is executed in a loop step after step, synchronously. So how to make the loop asynchronous? Well, you could try this: ``` Array.prototype.asyncForEach = function(applier, finished) { var self = this; var l = self.length; var call = function(i) { process.nextTick(function() { applier(self[i], i); if (i == l-1) finished(); else call(i+1); }); } call(0); }; ``` And you can use it like this: ``` var x = [1,2,3,4,5,6,7,8,9,10]; x.asyncForEach(function(el, index) { /* apply function to each el and index */ console.log(el); }, function() { /* This will be called when the loop finishes! */ console.log('Finished!'); }); /* Let us check whether the loop is really asynchronous. The following code should fire BEFORE loop! */ console.log('Is it asynchronous?'); ``` As you can see, it is not see as easy and simple as `forEach`. But this allows other code to be running between iterations of the loop (magic of the [`process.nextTick`](http://nodejs.org/api/process.html#process_process_nexttick_callback) method). So you gain [High Availability](http://en.wikipedia.org/wiki/High_availability), but the cost is that it will take even more time for the loop to finish. Note that modifying the array between iterations is possible and it will likely result in crashing your app. :D As I said in comment: I've never ever seen a loop working so long that it actually needed to be turned to asynchronous one. And I've worked with some market data which I processed alot (although with Python, not JavaScript - this might be a reason). And as lanzz commented, if the loop takes too much time, forking it may be a good idea. Or creating a WebService (or [Node.JS addon](http://nodejs.org/api/addons.html)) written in some efficient language (C?).
39,084,824
Here's my code: HTML ---- ``` <div class="screen screen1"></div> <div class="screen screen2"></div> ``` CSS --- ``` .screen{ width: 100%; height: 50%; position: absolute; background-color:#001; background-image: radial-gradient(white 15%, transparent 16%), radial-gradient(white 15%, transparent 16%); background-size:60px 60px; background-position: 0 0, 30px 30px; } .screen2{ left: 100%; } ``` JavaScript ---------- ``` $(document).ready(function(){ screen1 = $('.screen1'); screen2 = $('.screen2'); move(screen1, screen2); }); function move(first, second){ first.animate({left: '-100%'}, 3000, function(){ first.css('left', '100%'); move(second, first); }); second.animate({left: 0}, 3000); } ``` I want to animate two divs to make an infinite background repeating animation using jQuery. I came this far, and it works good for the most part except for the small pause that happens when I send `.screen1` to the right. Here's the fiddle: <https://jsfiddle.net/mavisme/a1275tuv/> How do I fix it to run smoothly?
2016/08/22
[ "https://Stackoverflow.com/questions/39084824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4768408/" ]
I assume you are unsatisfied with the "speeding up" and "slowing down" at the beginning and end of each cycle. Have a look at 'easing': ``` function move(first, second) { first.animate({ left: '-100%', }, 3000, 'linear', function() { first.css('left', '100%'); move(second, first); }); second.animate({ left: 0 }, 3000, 'linear'); } ``` > > easing (default: swing) > > > A string indicating which easing function to use for the transition. > > > <http://api.jquery.com/animate/>
Animating two divs to loop right to left indefinitely Here's my code: <https://jsfiddle.net/a1275tuv/5/> ``` $(function(){ var x = 0; setInterval(function(){ x-=1; $('.screen').css('background-position', x + 'px 0'); }, 10); }) ```
39,084,824
Here's my code: HTML ---- ``` <div class="screen screen1"></div> <div class="screen screen2"></div> ``` CSS --- ``` .screen{ width: 100%; height: 50%; position: absolute; background-color:#001; background-image: radial-gradient(white 15%, transparent 16%), radial-gradient(white 15%, transparent 16%); background-size:60px 60px; background-position: 0 0, 30px 30px; } .screen2{ left: 100%; } ``` JavaScript ---------- ``` $(document).ready(function(){ screen1 = $('.screen1'); screen2 = $('.screen2'); move(screen1, screen2); }); function move(first, second){ first.animate({left: '-100%'}, 3000, function(){ first.css('left', '100%'); move(second, first); }); second.animate({left: 0}, 3000); } ``` I want to animate two divs to make an infinite background repeating animation using jQuery. I came this far, and it works good for the most part except for the small pause that happens when I send `.screen1` to the right. Here's the fiddle: <https://jsfiddle.net/mavisme/a1275tuv/> How do I fix it to run smoothly?
2016/08/22
[ "https://Stackoverflow.com/questions/39084824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4768408/" ]
You should totally drop that and try ~~jQuery~~ CSS animations: ```css @keyframes animate { from { background-position: 0 0; } to { background-position: -60px 0; } } * { box-sizing: border-box; margin: 0; padding: 0; font-family: sans-serif; } html, body { height: 100%; min-height: 100%; overflow: hidden; } .screen { width: 100%; height: 100%; position: absolute; background-color: #001; background-image: radial-gradient(white 15%, transparent 16%), radial-gradient(white 15%, transparent 16%); background-size: 60px 60px; animation: animate 300ms linear infinite; } ``` ```html <div class="screen"></div> ```
Animating two divs to loop right to left indefinitely Here's my code: <https://jsfiddle.net/a1275tuv/5/> ``` $(function(){ var x = 0; setInterval(function(){ x-=1; $('.screen').css('background-position', x + 'px 0'); }, 10); }) ```
26,034,690
Having a string like: ``` "/some regex/gi" ``` How can I get an array with the search pattern (`"some regex"`) and flags (`"gi"`)? I tried to use `match` function: ``` > "/some regex/gi".match("/(.*)/([a-z]+)") [ '/some regex/gi', 'some regex', 'gi', index: 0, input: '/some regex/gi' ] ``` However, this fails for regular expressions without flags (returns `null`) and probably for other more complex regular expressions. Examples: ``` "without flags" // => ["without flags", "without flags", ...] "/with flags/gi" // => ["/with flags/gi", "with flags", "gi", ...] "/with\/slashes\//gi" // => ["/with\/slashes\//gi", "with\/slashes\/", "gi", ...] "/with \/some\/(.*)regex/gi" // => ["/with \/some\/(.*)regex/gi", "with \/some\/(.*)regex", "gi", ...] ``` The order in array is not important, however, the positions of search patter and flags should be the same. --- Actually, I want to take a string and parse it. After getting the search pattern and flags I want to pass them to `new RegExp(searchPattern, flags)` -- then I have a real regular expression. For my input I want to accept strings with and without slashes. No slashes (actually no slash at the begining -- first char) indicate that there are no flags. So, for `"/hi/gi"`, we will have `re = new RegExp("hi", "gi")`. Also see the following examples: ``` "/singlehash" => new RegExp("/singlehash", undefined) "single/hash" => new RegExp("single/hash", undefined) "/hi/" => new RegExp("hi", undefined) "hi" => new RegExp("hi", undefined) "/hi\/slash/" => new RegExp("hi\/slash", undefined) "/hi\/slash/gi" => new RegExp("hi\/slash", "gi") "/^dummy.*[a-z]$/flags" => new RegExp("^dummy.*[a-z]$", "flags") ``` I created the following little script that should not output any errors: ``` var obj = { "without flags": new RegExp("without flags"), "/something/gi": new RegExp("something", "gi"), "/with\/slashes\//gi": new RegExp("with\/slashes\/", "gi"), "/with \/some\/(.*)regex/gi": new RegExp("with \/some\/(.*)regex", "gi"), "/^dummy.*[a-z]$/gmi": new RegExp("^dummy.*[a-z]$", "gmi"), "raw input": new RegExp("raw input"), "/singlehash": new RegExp("/singlehash"), "single/hash": new RegExp("single/hash") }; var re = /^((?:\/(.*)\/(.*)|.*))$/; try { for (var s in obj) { var c = obj[s]; var m = s.match(re); if (m === null) { return console.error("null result for" + s); } console.log("> Input: " + s); console.log(" Pattern: " + m[1]); console.log(" Flags: " + m[2]); console.log(" Match array: ", m); var r = new RegExp(m[1], m[2]); if (r.toString() !== c.toString()) { console.error("Incorrect parsing for: " + s + ". Expected " + c.toString() + " but got " + r.toString()); } else { console.info("Correct parsing for: " + s); } } } catch (e) { console.error("!!!! Failed to parse: " + s + "\n" + e.stack); } ``` [**JSFIDDLE**](http://jsfiddle.net/fcrmkd6L/5/)
2014/09/25
[ "https://Stackoverflow.com/questions/26034690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1420197/" ]
This will work even if there're `\/` inside the regex: `/(\/?)(.+)\1([a-z]*)/i` With delimiters and flags: ``` var matches = "/some regex/gi".match(/(\/?)(.+)\1([a-z]*)/i); ``` **output:** ``` ["/some regex/gi", "/", "some regex", "gi"] ``` Without delimiters: ``` var matches = "without flags".match(/(\/?)(.+)\1([a-z]*)/i); ``` **output:** ``` ["without flags", "", "without flags", ""] ``` With all our test cases: ``` var matches = "/some regex/gi".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["/some regex/gi", "/", "some regex", "gi"] var matches = "some regex".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["some regex", "", "some regex", ""] var matches = "/with\/slashes\//gi".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["/with/slashes//gi", "/", "with/slashes/", "gi"] var matches = "/with \/some\/(.*)regex/gi".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["/with /some/(.*)regex/gi", "/", "with /some/(.*)regex", "gi"] var matches = "/^dummy.*[a-z]$/gmi".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["/^dummy.*[a-z]$/gmi", "/", "^dummy.*[a-z]$", "gmi"] var matches = "/singlehash".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["/singlehash", "", "/singlehash", ""] var matches = "single/hash".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["single/hash", "", "single/hash", ""] var matches = "raw input".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["raw input", "", "raw input", ""] ``` The regex is in `matches[2]` and flags in `matches[3]`
Remove quotes from your regex and use regex delimiters `/.../`: ``` var obj = { "/without flags/": new RegExp("without flags"), "/something/gi": new RegExp("something", "gi"), "/with\/slashes\//gi": new RegExp("with\/slashes\/", "gi"), "/with \/some\/(.*)regex/gi": new RegExp("with \/some\/(.*)regex", "gi"), "/^dummy.*[a-z]$/gmi": new RegExp("^dummy.*[a-z]$", "gmi"), "/singlehash": new RegExp("/singlehash"), "single/hash": new RegExp("single/hash"), "raw input": new RegExp("raw input") }; var re = /^(?:\/(.*?)\/([a-z]*)|(.+))$/i; try { for (var s in obj) { var c = obj[s]; var m = s.match(re); if (m === null || m[1]+m[3] === undefined) { console.error("null result for: " + s, m); continue; } var regex = (m[1]==undefined)?m[3]:m[1]; var r = (m[2]==undefined) ? new RegExp(regex) : new RegExp(regex, m[2]); if (r.toString() !== c.toString()) { console.error("Incorrect parsing for: " + s + ". Expected " + c.toString() + " but got " + r.toString()); } else { console.info("Correct parsing for: " + s); } } } catch (e) { console.error("!!!! Failed to parse: " + s + "\n" + e.stack); } ``` ### - [JSFiddle Demo](http://jsfiddle.net/fcrmkd6L/8/) ### - [RegEx Demo](http://regex101.com/r/oI2zQ1/3)
26,034,690
Having a string like: ``` "/some regex/gi" ``` How can I get an array with the search pattern (`"some regex"`) and flags (`"gi"`)? I tried to use `match` function: ``` > "/some regex/gi".match("/(.*)/([a-z]+)") [ '/some regex/gi', 'some regex', 'gi', index: 0, input: '/some regex/gi' ] ``` However, this fails for regular expressions without flags (returns `null`) and probably for other more complex regular expressions. Examples: ``` "without flags" // => ["without flags", "without flags", ...] "/with flags/gi" // => ["/with flags/gi", "with flags", "gi", ...] "/with\/slashes\//gi" // => ["/with\/slashes\//gi", "with\/slashes\/", "gi", ...] "/with \/some\/(.*)regex/gi" // => ["/with \/some\/(.*)regex/gi", "with \/some\/(.*)regex", "gi", ...] ``` The order in array is not important, however, the positions of search patter and flags should be the same. --- Actually, I want to take a string and parse it. After getting the search pattern and flags I want to pass them to `new RegExp(searchPattern, flags)` -- then I have a real regular expression. For my input I want to accept strings with and without slashes. No slashes (actually no slash at the begining -- first char) indicate that there are no flags. So, for `"/hi/gi"`, we will have `re = new RegExp("hi", "gi")`. Also see the following examples: ``` "/singlehash" => new RegExp("/singlehash", undefined) "single/hash" => new RegExp("single/hash", undefined) "/hi/" => new RegExp("hi", undefined) "hi" => new RegExp("hi", undefined) "/hi\/slash/" => new RegExp("hi\/slash", undefined) "/hi\/slash/gi" => new RegExp("hi\/slash", "gi") "/^dummy.*[a-z]$/flags" => new RegExp("^dummy.*[a-z]$", "flags") ``` I created the following little script that should not output any errors: ``` var obj = { "without flags": new RegExp("without flags"), "/something/gi": new RegExp("something", "gi"), "/with\/slashes\//gi": new RegExp("with\/slashes\/", "gi"), "/with \/some\/(.*)regex/gi": new RegExp("with \/some\/(.*)regex", "gi"), "/^dummy.*[a-z]$/gmi": new RegExp("^dummy.*[a-z]$", "gmi"), "raw input": new RegExp("raw input"), "/singlehash": new RegExp("/singlehash"), "single/hash": new RegExp("single/hash") }; var re = /^((?:\/(.*)\/(.*)|.*))$/; try { for (var s in obj) { var c = obj[s]; var m = s.match(re); if (m === null) { return console.error("null result for" + s); } console.log("> Input: " + s); console.log(" Pattern: " + m[1]); console.log(" Flags: " + m[2]); console.log(" Match array: ", m); var r = new RegExp(m[1], m[2]); if (r.toString() !== c.toString()) { console.error("Incorrect parsing for: " + s + ". Expected " + c.toString() + " but got " + r.toString()); } else { console.info("Correct parsing for: " + s); } } } catch (e) { console.error("!!!! Failed to parse: " + s + "\n" + e.stack); } ``` [**JSFIDDLE**](http://jsfiddle.net/fcrmkd6L/5/)
2014/09/25
[ "https://Stackoverflow.com/questions/26034690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1420197/" ]
Remove quotes from your regex and use regex delimiters `/.../`: ``` var obj = { "/without flags/": new RegExp("without flags"), "/something/gi": new RegExp("something", "gi"), "/with\/slashes\//gi": new RegExp("with\/slashes\/", "gi"), "/with \/some\/(.*)regex/gi": new RegExp("with \/some\/(.*)regex", "gi"), "/^dummy.*[a-z]$/gmi": new RegExp("^dummy.*[a-z]$", "gmi"), "/singlehash": new RegExp("/singlehash"), "single/hash": new RegExp("single/hash"), "raw input": new RegExp("raw input") }; var re = /^(?:\/(.*?)\/([a-z]*)|(.+))$/i; try { for (var s in obj) { var c = obj[s]; var m = s.match(re); if (m === null || m[1]+m[3] === undefined) { console.error("null result for: " + s, m); continue; } var regex = (m[1]==undefined)?m[3]:m[1]; var r = (m[2]==undefined) ? new RegExp(regex) : new RegExp(regex, m[2]); if (r.toString() !== c.toString()) { console.error("Incorrect parsing for: " + s + ". Expected " + c.toString() + " but got " + r.toString()); } else { console.info("Correct parsing for: " + s); } } } catch (e) { console.error("!!!! Failed to parse: " + s + "\n" + e.stack); } ``` ### - [JSFiddle Demo](http://jsfiddle.net/fcrmkd6L/8/) ### - [RegEx Demo](http://regex101.com/r/oI2zQ1/3)
Why not just ``` /\/(.*)\/(.*)|(.*)/ ``` In English ``` Look for either a slash, followed by a (greedy) sequence of characters, a closing slash, and an optional sequence of flags or any sequence of characters ``` See <http://regex101.com/r/aY1oS8/2>.
26,034,690
Having a string like: ``` "/some regex/gi" ``` How can I get an array with the search pattern (`"some regex"`) and flags (`"gi"`)? I tried to use `match` function: ``` > "/some regex/gi".match("/(.*)/([a-z]+)") [ '/some regex/gi', 'some regex', 'gi', index: 0, input: '/some regex/gi' ] ``` However, this fails for regular expressions without flags (returns `null`) and probably for other more complex regular expressions. Examples: ``` "without flags" // => ["without flags", "without flags", ...] "/with flags/gi" // => ["/with flags/gi", "with flags", "gi", ...] "/with\/slashes\//gi" // => ["/with\/slashes\//gi", "with\/slashes\/", "gi", ...] "/with \/some\/(.*)regex/gi" // => ["/with \/some\/(.*)regex/gi", "with \/some\/(.*)regex", "gi", ...] ``` The order in array is not important, however, the positions of search patter and flags should be the same. --- Actually, I want to take a string and parse it. After getting the search pattern and flags I want to pass them to `new RegExp(searchPattern, flags)` -- then I have a real regular expression. For my input I want to accept strings with and without slashes. No slashes (actually no slash at the begining -- first char) indicate that there are no flags. So, for `"/hi/gi"`, we will have `re = new RegExp("hi", "gi")`. Also see the following examples: ``` "/singlehash" => new RegExp("/singlehash", undefined) "single/hash" => new RegExp("single/hash", undefined) "/hi/" => new RegExp("hi", undefined) "hi" => new RegExp("hi", undefined) "/hi\/slash/" => new RegExp("hi\/slash", undefined) "/hi\/slash/gi" => new RegExp("hi\/slash", "gi") "/^dummy.*[a-z]$/flags" => new RegExp("^dummy.*[a-z]$", "flags") ``` I created the following little script that should not output any errors: ``` var obj = { "without flags": new RegExp("without flags"), "/something/gi": new RegExp("something", "gi"), "/with\/slashes\//gi": new RegExp("with\/slashes\/", "gi"), "/with \/some\/(.*)regex/gi": new RegExp("with \/some\/(.*)regex", "gi"), "/^dummy.*[a-z]$/gmi": new RegExp("^dummy.*[a-z]$", "gmi"), "raw input": new RegExp("raw input"), "/singlehash": new RegExp("/singlehash"), "single/hash": new RegExp("single/hash") }; var re = /^((?:\/(.*)\/(.*)|.*))$/; try { for (var s in obj) { var c = obj[s]; var m = s.match(re); if (m === null) { return console.error("null result for" + s); } console.log("> Input: " + s); console.log(" Pattern: " + m[1]); console.log(" Flags: " + m[2]); console.log(" Match array: ", m); var r = new RegExp(m[1], m[2]); if (r.toString() !== c.toString()) { console.error("Incorrect parsing for: " + s + ". Expected " + c.toString() + " but got " + r.toString()); } else { console.info("Correct parsing for: " + s); } } } catch (e) { console.error("!!!! Failed to parse: " + s + "\n" + e.stack); } ``` [**JSFIDDLE**](http://jsfiddle.net/fcrmkd6L/5/)
2014/09/25
[ "https://Stackoverflow.com/questions/26034690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1420197/" ]
This will work even if there're `\/` inside the regex: `/(\/?)(.+)\1([a-z]*)/i` With delimiters and flags: ``` var matches = "/some regex/gi".match(/(\/?)(.+)\1([a-z]*)/i); ``` **output:** ``` ["/some regex/gi", "/", "some regex", "gi"] ``` Without delimiters: ``` var matches = "without flags".match(/(\/?)(.+)\1([a-z]*)/i); ``` **output:** ``` ["without flags", "", "without flags", ""] ``` With all our test cases: ``` var matches = "/some regex/gi".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["/some regex/gi", "/", "some regex", "gi"] var matches = "some regex".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["some regex", "", "some regex", ""] var matches = "/with\/slashes\//gi".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["/with/slashes//gi", "/", "with/slashes/", "gi"] var matches = "/with \/some\/(.*)regex/gi".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["/with /some/(.*)regex/gi", "/", "with /some/(.*)regex", "gi"] var matches = "/^dummy.*[a-z]$/gmi".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["/^dummy.*[a-z]$/gmi", "/", "^dummy.*[a-z]$", "gmi"] var matches = "/singlehash".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["/singlehash", "", "/singlehash", ""] var matches = "single/hash".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["single/hash", "", "single/hash", ""] var matches = "raw input".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["raw input", "", "raw input", ""] ``` The regex is in `matches[2]` and flags in `matches[3]`
Why not just ``` /\/(.*)\/(.*)|(.*)/ ``` In English ``` Look for either a slash, followed by a (greedy) sequence of characters, a closing slash, and an optional sequence of flags or any sequence of characters ``` See <http://regex101.com/r/aY1oS8/2>.
26,034,690
Having a string like: ``` "/some regex/gi" ``` How can I get an array with the search pattern (`"some regex"`) and flags (`"gi"`)? I tried to use `match` function: ``` > "/some regex/gi".match("/(.*)/([a-z]+)") [ '/some regex/gi', 'some regex', 'gi', index: 0, input: '/some regex/gi' ] ``` However, this fails for regular expressions without flags (returns `null`) and probably for other more complex regular expressions. Examples: ``` "without flags" // => ["without flags", "without flags", ...] "/with flags/gi" // => ["/with flags/gi", "with flags", "gi", ...] "/with\/slashes\//gi" // => ["/with\/slashes\//gi", "with\/slashes\/", "gi", ...] "/with \/some\/(.*)regex/gi" // => ["/with \/some\/(.*)regex/gi", "with \/some\/(.*)regex", "gi", ...] ``` The order in array is not important, however, the positions of search patter and flags should be the same. --- Actually, I want to take a string and parse it. After getting the search pattern and flags I want to pass them to `new RegExp(searchPattern, flags)` -- then I have a real regular expression. For my input I want to accept strings with and without slashes. No slashes (actually no slash at the begining -- first char) indicate that there are no flags. So, for `"/hi/gi"`, we will have `re = new RegExp("hi", "gi")`. Also see the following examples: ``` "/singlehash" => new RegExp("/singlehash", undefined) "single/hash" => new RegExp("single/hash", undefined) "/hi/" => new RegExp("hi", undefined) "hi" => new RegExp("hi", undefined) "/hi\/slash/" => new RegExp("hi\/slash", undefined) "/hi\/slash/gi" => new RegExp("hi\/slash", "gi") "/^dummy.*[a-z]$/flags" => new RegExp("^dummy.*[a-z]$", "flags") ``` I created the following little script that should not output any errors: ``` var obj = { "without flags": new RegExp("without flags"), "/something/gi": new RegExp("something", "gi"), "/with\/slashes\//gi": new RegExp("with\/slashes\/", "gi"), "/with \/some\/(.*)regex/gi": new RegExp("with \/some\/(.*)regex", "gi"), "/^dummy.*[a-z]$/gmi": new RegExp("^dummy.*[a-z]$", "gmi"), "raw input": new RegExp("raw input"), "/singlehash": new RegExp("/singlehash"), "single/hash": new RegExp("single/hash") }; var re = /^((?:\/(.*)\/(.*)|.*))$/; try { for (var s in obj) { var c = obj[s]; var m = s.match(re); if (m === null) { return console.error("null result for" + s); } console.log("> Input: " + s); console.log(" Pattern: " + m[1]); console.log(" Flags: " + m[2]); console.log(" Match array: ", m); var r = new RegExp(m[1], m[2]); if (r.toString() !== c.toString()) { console.error("Incorrect parsing for: " + s + ". Expected " + c.toString() + " but got " + r.toString()); } else { console.info("Correct parsing for: " + s); } } } catch (e) { console.error("!!!! Failed to parse: " + s + "\n" + e.stack); } ``` [**JSFIDDLE**](http://jsfiddle.net/fcrmkd6L/5/)
2014/09/25
[ "https://Stackoverflow.com/questions/26034690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1420197/" ]
This will work even if there're `\/` inside the regex: `/(\/?)(.+)\1([a-z]*)/i` With delimiters and flags: ``` var matches = "/some regex/gi".match(/(\/?)(.+)\1([a-z]*)/i); ``` **output:** ``` ["/some regex/gi", "/", "some regex", "gi"] ``` Without delimiters: ``` var matches = "without flags".match(/(\/?)(.+)\1([a-z]*)/i); ``` **output:** ``` ["without flags", "", "without flags", ""] ``` With all our test cases: ``` var matches = "/some regex/gi".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["/some regex/gi", "/", "some regex", "gi"] var matches = "some regex".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["some regex", "", "some regex", ""] var matches = "/with\/slashes\//gi".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["/with/slashes//gi", "/", "with/slashes/", "gi"] var matches = "/with \/some\/(.*)regex/gi".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["/with /some/(.*)regex/gi", "/", "with /some/(.*)regex", "gi"] var matches = "/^dummy.*[a-z]$/gmi".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["/^dummy.*[a-z]$/gmi", "/", "^dummy.*[a-z]$", "gmi"] var matches = "/singlehash".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["/singlehash", "", "/singlehash", ""] var matches = "single/hash".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["single/hash", "", "single/hash", ""] var matches = "raw input".match(/(\/?)(.+)\1([a-z]*)/i); ==> ["raw input", "", "raw input", ""] ``` The regex is in `matches[2]` and flags in `matches[3]`
Use **backtracking**. See this regex: ``` /^(?:\/(.*)\/([a-z]*)|(.*))$/ ``` Here is an [online code demo](https://eval.in/private/ca83867b165da2). Works now.
26,034,690
Having a string like: ``` "/some regex/gi" ``` How can I get an array with the search pattern (`"some regex"`) and flags (`"gi"`)? I tried to use `match` function: ``` > "/some regex/gi".match("/(.*)/([a-z]+)") [ '/some regex/gi', 'some regex', 'gi', index: 0, input: '/some regex/gi' ] ``` However, this fails for regular expressions without flags (returns `null`) and probably for other more complex regular expressions. Examples: ``` "without flags" // => ["without flags", "without flags", ...] "/with flags/gi" // => ["/with flags/gi", "with flags", "gi", ...] "/with\/slashes\//gi" // => ["/with\/slashes\//gi", "with\/slashes\/", "gi", ...] "/with \/some\/(.*)regex/gi" // => ["/with \/some\/(.*)regex/gi", "with \/some\/(.*)regex", "gi", ...] ``` The order in array is not important, however, the positions of search patter and flags should be the same. --- Actually, I want to take a string and parse it. After getting the search pattern and flags I want to pass them to `new RegExp(searchPattern, flags)` -- then I have a real regular expression. For my input I want to accept strings with and without slashes. No slashes (actually no slash at the begining -- first char) indicate that there are no flags. So, for `"/hi/gi"`, we will have `re = new RegExp("hi", "gi")`. Also see the following examples: ``` "/singlehash" => new RegExp("/singlehash", undefined) "single/hash" => new RegExp("single/hash", undefined) "/hi/" => new RegExp("hi", undefined) "hi" => new RegExp("hi", undefined) "/hi\/slash/" => new RegExp("hi\/slash", undefined) "/hi\/slash/gi" => new RegExp("hi\/slash", "gi") "/^dummy.*[a-z]$/flags" => new RegExp("^dummy.*[a-z]$", "flags") ``` I created the following little script that should not output any errors: ``` var obj = { "without flags": new RegExp("without flags"), "/something/gi": new RegExp("something", "gi"), "/with\/slashes\//gi": new RegExp("with\/slashes\/", "gi"), "/with \/some\/(.*)regex/gi": new RegExp("with \/some\/(.*)regex", "gi"), "/^dummy.*[a-z]$/gmi": new RegExp("^dummy.*[a-z]$", "gmi"), "raw input": new RegExp("raw input"), "/singlehash": new RegExp("/singlehash"), "single/hash": new RegExp("single/hash") }; var re = /^((?:\/(.*)\/(.*)|.*))$/; try { for (var s in obj) { var c = obj[s]; var m = s.match(re); if (m === null) { return console.error("null result for" + s); } console.log("> Input: " + s); console.log(" Pattern: " + m[1]); console.log(" Flags: " + m[2]); console.log(" Match array: ", m); var r = new RegExp(m[1], m[2]); if (r.toString() !== c.toString()) { console.error("Incorrect parsing for: " + s + ". Expected " + c.toString() + " but got " + r.toString()); } else { console.info("Correct parsing for: " + s); } } } catch (e) { console.error("!!!! Failed to parse: " + s + "\n" + e.stack); } ``` [**JSFIDDLE**](http://jsfiddle.net/fcrmkd6L/5/)
2014/09/25
[ "https://Stackoverflow.com/questions/26034690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1420197/" ]
Use **backtracking**. See this regex: ``` /^(?:\/(.*)\/([a-z]*)|(.*))$/ ``` Here is an [online code demo](https://eval.in/private/ca83867b165da2). Works now.
Why not just ``` /\/(.*)\/(.*)|(.*)/ ``` In English ``` Look for either a slash, followed by a (greedy) sequence of characters, a closing slash, and an optional sequence of flags or any sequence of characters ``` See <http://regex101.com/r/aY1oS8/2>.
7,275
I found this plot on Wikipedia: ![domain-colored plot of sine function](https://i.stack.imgur.com/GjMe4.jpg) > > [Domain coloring](http://en.wikipedia.org/wiki/Domain_coloring) of $\sin(z)$ over $(-\pi,\pi)$ on $x$ and $y$ axes. Brightness indicates absolute magnitude, saturation represents imaginary and real magnitude. > > > Despite following the link and reading the page nothing I have tried is giving me the result shown. How should this be done?
2012/06/23
[ "https://mathematica.stackexchange.com/questions/7275", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/121/" ]
Building on Heike's `ColorFunction`, I came up with this: [![enter image description here](https://i.stack.imgur.com/ZU9kk.png)](https://i.stack.imgur.com/ZU9kk.png) The white bits are the trickiest - you need to make sure the brightness is high where the saturation is low, otherwise the black lines appear on top of the white ones. The code is below. The functions defined are: * `complexGrid[max,n]` simply generates an $n\times n$ grid of complex numbers ranging from $-max$ to $+max$ in both axes. * `complexHSB[Z]` takes an array $Z$ of complex numbers and returns an array of $\{h,s,b\}$ values. I've tweaked the colour functions slightly. The initial $\{h,s,b\}$ values are calculated using Heike's formulas, except I don't square $s$. The brightness is then adjusted so that it is high when the saturation is low. The formula is almost the same as $b2=\max (1-s,b)$ but written in a way that makes it `Listable`. * `domainImage[func,max,n]` calls the previous two functions to create an image. `func` is the function to be plotted. The image is generated at twice the desired size and then resized back down to provide a degree of antialiasing. * `domainPlot[func,max,n]` is the end user function which embeds the image in a graphics frame. --- ``` complexGrid = Compile[{{max, _Real}, {n, _Integer}}, Block[{r}, r = Range[-max, max, 2 max/(n - 1)]; Outer[Plus, -I r, r]]]; complexHSB = Compile[{{Z, _Complex, 2}}, Block[{h, s, b, b2}, h = Arg[Z]/(2 Pi); s = Abs[Sin[2 Pi Abs[Z]]]; b = Sqrt[Sqrt[Abs[Sin[2 Pi Im[Z]] Sin[2 Pi Re[Z]]]]]; b2 = 0.5 ((1 - s) + b + Sqrt[(1 - s - b)^2 + 0.01]); Transpose[{h, Sqrt[s], b2}, {3, 1, 2}]]]; domainImage[func_, max_, n_] := ImageResize[ColorConvert[ Image[complexHSB@func@complexGrid[max, 2 n], ColorSpace -> "HSB"], "RGB"], n, Resampling -> "Gaussian"]; domainPlot[func_: Identity, max_: Pi, n_: 500] := Graphics[{}, Frame -> True, PlotRange -> max, RotateLabel -> False, FrameLabel -> {"Re[z]", "Im[z]", "Domain Colouring of " <> ToString@StandardForm@func@"z"}, BaseStyle -> {FontFamily -> "Calibri", 12}, Prolog -> Inset[domainImage[func, max, n], {0, 0}, {Center, Center}, 2` max]]; domainPlot[Sin, Pi] ``` Other examples follow: It's informative to plot the untransformed complex plane to understand what the colours indicate: ``` domainPlot[] ``` [![enter image description here](https://i.stack.imgur.com/akXDv.png)](https://i.stack.imgur.com/akXDv.png) A simple example: ``` domainPlot[Sqrt] ``` [![enter image description here](https://i.stack.imgur.com/UsLQ9.png)](https://i.stack.imgur.com/UsLQ9.png) Plotting a pure function: ``` domainPlot[(# + 2 I)/(# - 1) &] ``` [![enter image description here](https://i.stack.imgur.com/0p0CP.png)](https://i.stack.imgur.com/0p0CP.png) I think this one is very pretty: ``` domainPlot[Log] ``` [![enter image description here](https://i.stack.imgur.com/66Ukq.png)](https://i.stack.imgur.com/66Ukq.png)
This is a good way : ``` DensityPlot[ Rescale[ Arg[Sin[-x - I y]], {-Pi, Pi}], {x, -Pi, Pi}, {y, -Pi, Pi}, MeshFunctions -> Function @@@ {{{x, y, z}, Re[Sin[x + I y]]}, {{x, y, z}, Im[Sin[x + I y]]}, {{x, y, z}, Abs[Sin[x + I y]]}}, MeshStyle -> {Directive[Opacity[0.8], Thickness[0.001]], Directive[Opacity[0.7], Thickness[0.001]], Directive[White, Opacity[0.3], Thickness[0.006]]}, ColorFunction -> Hue, Mesh -> 50, Exclusions -> None, PlotPoints -> 100] ``` ![enter image description here](https://i.stack.imgur.com/8Hjf9.gif) Another ways to tackle the problem, which apprears promising. ``` ContourPlot[ Evaluate @ {Table[Re @ Sin[x + I y] == 1/2 k, {k, -25, 25}], Table[Im @ Sin[x + I y] == 1/2 k, {k, -25, 25}]}, {x, -Pi, Pi}, {y, -Pi, Pi}, PlotPoints -> 100, MaxRecursion -> 5] ``` ![enter image description here](https://i.stack.imgur.com/NLv8X.gif) and ``` RegionPlot[ Evaluate @ {Table[1/2 (k + 1) > Re @ Sin[x + I y] > 1/2 k, {k, -25, 25}], Table[1/2 (k + 1) > Im @ Sin[x + I y] > 1/2 k, {k, -25, 25}]}, {x, -Pi, Pi}, {y, -Pi, Pi}, PlotPoints -> 50, MaxRecursion -> 4, ColorFunction -> Function[{x, y}, Hue[Re@Sin[x + I y]]]] ``` ![enter image description here](https://i.stack.imgur.com/YwSCR.gif) These plots seem to be good points for further playing around to get better solutions.
7,275
I found this plot on Wikipedia: ![domain-colored plot of sine function](https://i.stack.imgur.com/GjMe4.jpg) > > [Domain coloring](http://en.wikipedia.org/wiki/Domain_coloring) of $\sin(z)$ over $(-\pi,\pi)$ on $x$ and $y$ axes. Brightness indicates absolute magnitude, saturation represents imaginary and real magnitude. > > > Despite following the link and reading the page nothing I have tried is giving me the result shown. How should this be done?
2012/06/23
[ "https://mathematica.stackexchange.com/questions/7275", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/121/" ]
This is a good way : ``` DensityPlot[ Rescale[ Arg[Sin[-x - I y]], {-Pi, Pi}], {x, -Pi, Pi}, {y, -Pi, Pi}, MeshFunctions -> Function @@@ {{{x, y, z}, Re[Sin[x + I y]]}, {{x, y, z}, Im[Sin[x + I y]]}, {{x, y, z}, Abs[Sin[x + I y]]}}, MeshStyle -> {Directive[Opacity[0.8], Thickness[0.001]], Directive[Opacity[0.7], Thickness[0.001]], Directive[White, Opacity[0.3], Thickness[0.006]]}, ColorFunction -> Hue, Mesh -> 50, Exclusions -> None, PlotPoints -> 100] ``` ![enter image description here](https://i.stack.imgur.com/8Hjf9.gif) Another ways to tackle the problem, which apprears promising. ``` ContourPlot[ Evaluate @ {Table[Re @ Sin[x + I y] == 1/2 k, {k, -25, 25}], Table[Im @ Sin[x + I y] == 1/2 k, {k, -25, 25}]}, {x, -Pi, Pi}, {y, -Pi, Pi}, PlotPoints -> 100, MaxRecursion -> 5] ``` ![enter image description here](https://i.stack.imgur.com/NLv8X.gif) and ``` RegionPlot[ Evaluate @ {Table[1/2 (k + 1) > Re @ Sin[x + I y] > 1/2 k, {k, -25, 25}], Table[1/2 (k + 1) > Im @ Sin[x + I y] > 1/2 k, {k, -25, 25}]}, {x, -Pi, Pi}, {y, -Pi, Pi}, PlotPoints -> 50, MaxRecursion -> 4, ColorFunction -> Function[{x, y}, Hue[Re@Sin[x + I y]]]] ``` ![enter image description here](https://i.stack.imgur.com/YwSCR.gif) These plots seem to be good points for further playing around to get better solutions.
With Mathematica 12.0, there's now a [`ComplexPlot`](https://reference.wolfram.com/language/ref/ComplexPlot.html) function that replaces user made solutions. As with other `Plot` functions, it allows us to specify a [`ColorFunction`](https://reference.wolfram.com/language/ref/ColorFunction.html) option to manipulate how to color the plot. This particular coloring is implemented natively in the `"CyclicReImLogAbs"` option. So the modern equivalent is ``` ComplexPlot[Sin[z], {z, -Pi - Pi I, Pi + Pi I}, ColorFunction -> "CyclicReImLogAbs", Frame -> False] ``` [![Plot Result](https://i.stack.imgur.com/W0FEc.png)](https://i.stack.imgur.com/W0FEc.png)
7,275
I found this plot on Wikipedia: ![domain-colored plot of sine function](https://i.stack.imgur.com/GjMe4.jpg) > > [Domain coloring](http://en.wikipedia.org/wiki/Domain_coloring) of $\sin(z)$ over $(-\pi,\pi)$ on $x$ and $y$ axes. Brightness indicates absolute magnitude, saturation represents imaginary and real magnitude. > > > Despite following the link and reading the page nothing I have tried is giving me the result shown. How should this be done?
2012/06/23
[ "https://mathematica.stackexchange.com/questions/7275", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/121/" ]
Building on Heike's `ColorFunction`, I came up with this: [![enter image description here](https://i.stack.imgur.com/ZU9kk.png)](https://i.stack.imgur.com/ZU9kk.png) The white bits are the trickiest - you need to make sure the brightness is high where the saturation is low, otherwise the black lines appear on top of the white ones. The code is below. The functions defined are: * `complexGrid[max,n]` simply generates an $n\times n$ grid of complex numbers ranging from $-max$ to $+max$ in both axes. * `complexHSB[Z]` takes an array $Z$ of complex numbers and returns an array of $\{h,s,b\}$ values. I've tweaked the colour functions slightly. The initial $\{h,s,b\}$ values are calculated using Heike's formulas, except I don't square $s$. The brightness is then adjusted so that it is high when the saturation is low. The formula is almost the same as $b2=\max (1-s,b)$ but written in a way that makes it `Listable`. * `domainImage[func,max,n]` calls the previous two functions to create an image. `func` is the function to be plotted. The image is generated at twice the desired size and then resized back down to provide a degree of antialiasing. * `domainPlot[func,max,n]` is the end user function which embeds the image in a graphics frame. --- ``` complexGrid = Compile[{{max, _Real}, {n, _Integer}}, Block[{r}, r = Range[-max, max, 2 max/(n - 1)]; Outer[Plus, -I r, r]]]; complexHSB = Compile[{{Z, _Complex, 2}}, Block[{h, s, b, b2}, h = Arg[Z]/(2 Pi); s = Abs[Sin[2 Pi Abs[Z]]]; b = Sqrt[Sqrt[Abs[Sin[2 Pi Im[Z]] Sin[2 Pi Re[Z]]]]]; b2 = 0.5 ((1 - s) + b + Sqrt[(1 - s - b)^2 + 0.01]); Transpose[{h, Sqrt[s], b2}, {3, 1, 2}]]]; domainImage[func_, max_, n_] := ImageResize[ColorConvert[ Image[complexHSB@func@complexGrid[max, 2 n], ColorSpace -> "HSB"], "RGB"], n, Resampling -> "Gaussian"]; domainPlot[func_: Identity, max_: Pi, n_: 500] := Graphics[{}, Frame -> True, PlotRange -> max, RotateLabel -> False, FrameLabel -> {"Re[z]", "Im[z]", "Domain Colouring of " <> ToString@StandardForm@func@"z"}, BaseStyle -> {FontFamily -> "Calibri", 12}, Prolog -> Inset[domainImage[func, max, n], {0, 0}, {Center, Center}, 2` max]]; domainPlot[Sin, Pi] ``` Other examples follow: It's informative to plot the untransformed complex plane to understand what the colours indicate: ``` domainPlot[] ``` [![enter image description here](https://i.stack.imgur.com/akXDv.png)](https://i.stack.imgur.com/akXDv.png) A simple example: ``` domainPlot[Sqrt] ``` [![enter image description here](https://i.stack.imgur.com/UsLQ9.png)](https://i.stack.imgur.com/UsLQ9.png) Plotting a pure function: ``` domainPlot[(# + 2 I)/(# - 1) &] ``` [![enter image description here](https://i.stack.imgur.com/0p0CP.png)](https://i.stack.imgur.com/0p0CP.png) I think this one is very pretty: ``` domainPlot[Log] ``` [![enter image description here](https://i.stack.imgur.com/66Ukq.png)](https://i.stack.imgur.com/66Ukq.png)
Not as pretty as the one in the original post, but it's getting in the right direction I think: ``` RegionPlot[True, {x, -Pi, Pi}, {y, -Pi, Pi}, ColorFunction -> (Hue[Rescale[Arg[Sin[#1 + I #2]], {-Pi, Pi}], Sin[2 Pi Abs[Sin[#1 + I #2]]]^2, Abs@(Sin[Pi Re[Sin[#1 + I #2]]] Sin[Pi Im[Sin[#1 + I #2]]])^(1/ 4), 1] &), ColorFunctionScaling -> False, PlotPoints -> 200] ``` ![Mathematica graphics](https://i.stack.imgur.com/SAba2.png) It seems that the hue of the colour function is a function of `Arg[Sin[z]]`, saturation is a function of `Abs[Sin[z]]` and the brightness is related to `Re[Sin[z]]` and `Im[Sin[z]]`.
7,275
I found this plot on Wikipedia: ![domain-colored plot of sine function](https://i.stack.imgur.com/GjMe4.jpg) > > [Domain coloring](http://en.wikipedia.org/wiki/Domain_coloring) of $\sin(z)$ over $(-\pi,\pi)$ on $x$ and $y$ axes. Brightness indicates absolute magnitude, saturation represents imaginary and real magnitude. > > > Despite following the link and reading the page nothing I have tried is giving me the result shown. How should this be done?
2012/06/23
[ "https://mathematica.stackexchange.com/questions/7275", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/121/" ]
Not as pretty as the one in the original post, but it's getting in the right direction I think: ``` RegionPlot[True, {x, -Pi, Pi}, {y, -Pi, Pi}, ColorFunction -> (Hue[Rescale[Arg[Sin[#1 + I #2]], {-Pi, Pi}], Sin[2 Pi Abs[Sin[#1 + I #2]]]^2, Abs@(Sin[Pi Re[Sin[#1 + I #2]]] Sin[Pi Im[Sin[#1 + I #2]]])^(1/ 4), 1] &), ColorFunctionScaling -> False, PlotPoints -> 200] ``` ![Mathematica graphics](https://i.stack.imgur.com/SAba2.png) It seems that the hue of the colour function is a function of `Arg[Sin[z]]`, saturation is a function of `Abs[Sin[z]]` and the brightness is related to `Re[Sin[z]]` and `Im[Sin[z]]`.
With Mathematica 12.0, there's now a [`ComplexPlot`](https://reference.wolfram.com/language/ref/ComplexPlot.html) function that replaces user made solutions. As with other `Plot` functions, it allows us to specify a [`ColorFunction`](https://reference.wolfram.com/language/ref/ColorFunction.html) option to manipulate how to color the plot. This particular coloring is implemented natively in the `"CyclicReImLogAbs"` option. So the modern equivalent is ``` ComplexPlot[Sin[z], {z, -Pi - Pi I, Pi + Pi I}, ColorFunction -> "CyclicReImLogAbs", Frame -> False] ``` [![Plot Result](https://i.stack.imgur.com/W0FEc.png)](https://i.stack.imgur.com/W0FEc.png)
7,275
I found this plot on Wikipedia: ![domain-colored plot of sine function](https://i.stack.imgur.com/GjMe4.jpg) > > [Domain coloring](http://en.wikipedia.org/wiki/Domain_coloring) of $\sin(z)$ over $(-\pi,\pi)$ on $x$ and $y$ axes. Brightness indicates absolute magnitude, saturation represents imaginary and real magnitude. > > > Despite following the link and reading the page nothing I have tried is giving me the result shown. How should this be done?
2012/06/23
[ "https://mathematica.stackexchange.com/questions/7275", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/121/" ]
Building on Heike's `ColorFunction`, I came up with this: [![enter image description here](https://i.stack.imgur.com/ZU9kk.png)](https://i.stack.imgur.com/ZU9kk.png) The white bits are the trickiest - you need to make sure the brightness is high where the saturation is low, otherwise the black lines appear on top of the white ones. The code is below. The functions defined are: * `complexGrid[max,n]` simply generates an $n\times n$ grid of complex numbers ranging from $-max$ to $+max$ in both axes. * `complexHSB[Z]` takes an array $Z$ of complex numbers and returns an array of $\{h,s,b\}$ values. I've tweaked the colour functions slightly. The initial $\{h,s,b\}$ values are calculated using Heike's formulas, except I don't square $s$. The brightness is then adjusted so that it is high when the saturation is low. The formula is almost the same as $b2=\max (1-s,b)$ but written in a way that makes it `Listable`. * `domainImage[func,max,n]` calls the previous two functions to create an image. `func` is the function to be plotted. The image is generated at twice the desired size and then resized back down to provide a degree of antialiasing. * `domainPlot[func,max,n]` is the end user function which embeds the image in a graphics frame. --- ``` complexGrid = Compile[{{max, _Real}, {n, _Integer}}, Block[{r}, r = Range[-max, max, 2 max/(n - 1)]; Outer[Plus, -I r, r]]]; complexHSB = Compile[{{Z, _Complex, 2}}, Block[{h, s, b, b2}, h = Arg[Z]/(2 Pi); s = Abs[Sin[2 Pi Abs[Z]]]; b = Sqrt[Sqrt[Abs[Sin[2 Pi Im[Z]] Sin[2 Pi Re[Z]]]]]; b2 = 0.5 ((1 - s) + b + Sqrt[(1 - s - b)^2 + 0.01]); Transpose[{h, Sqrt[s], b2}, {3, 1, 2}]]]; domainImage[func_, max_, n_] := ImageResize[ColorConvert[ Image[complexHSB@func@complexGrid[max, 2 n], ColorSpace -> "HSB"], "RGB"], n, Resampling -> "Gaussian"]; domainPlot[func_: Identity, max_: Pi, n_: 500] := Graphics[{}, Frame -> True, PlotRange -> max, RotateLabel -> False, FrameLabel -> {"Re[z]", "Im[z]", "Domain Colouring of " <> ToString@StandardForm@func@"z"}, BaseStyle -> {FontFamily -> "Calibri", 12}, Prolog -> Inset[domainImage[func, max, n], {0, 0}, {Center, Center}, 2` max]]; domainPlot[Sin, Pi] ``` Other examples follow: It's informative to plot the untransformed complex plane to understand what the colours indicate: ``` domainPlot[] ``` [![enter image description here](https://i.stack.imgur.com/akXDv.png)](https://i.stack.imgur.com/akXDv.png) A simple example: ``` domainPlot[Sqrt] ``` [![enter image description here](https://i.stack.imgur.com/UsLQ9.png)](https://i.stack.imgur.com/UsLQ9.png) Plotting a pure function: ``` domainPlot[(# + 2 I)/(# - 1) &] ``` [![enter image description here](https://i.stack.imgur.com/0p0CP.png)](https://i.stack.imgur.com/0p0CP.png) I think this one is very pretty: ``` domainPlot[Log] ``` [![enter image description here](https://i.stack.imgur.com/66Ukq.png)](https://i.stack.imgur.com/66Ukq.png)
I already mentioned Bernd Thaller's package `Graphics`ComplexPlot`` in the comments; if one blends the ideas from Artes's and Heike's answers, and then use the function `$ComplexToColorMap[]` from Thaller's package (I won't include it here; again, see the package for that), we get this: ![domain-colored plot](https://i.stack.imgur.com/8ic1B.png) ``` Needs["Graphics`ComplexPlot`"] (* Thaller's package; get it yourself *) f1 = RegionPlot[True, {x, -Pi, Pi}, {y, -Pi, Pi}, ColorFunction -> ($ComplexToColorMap[Abs[Sin[#1 + I #2]], Arg[Sin[#1 + I #2]], {Pi, 1/10, 1, 1/10, 1}] &), ColorFunctionScaling -> False, PlotPoints -> 200]; f2 = ContourPlot[ Evaluate@{Table[Re@Sin[x + I y] == 1/2 k, {k, -25, 25}], Table[Im@Sin[x + I y] == 1/2 k, {k, -25, 25}]}, {x, -Pi, Pi}, {y, -Pi, Pi}, PlotPoints -> 100, ContourStyle -> Gray]; f3 = ContourPlot[ Evaluate@Table[Abs@Sin[x + I y] == 1/2 k, {k, -25, 25}], {x, -Pi, Pi}, {y, -Pi, Pi}, PlotPoints -> 100, ContourStyle -> White, MaxRecursion -> 5]; Show[f1, f2, f3] ``` The `$ComplexToColorMap[]` function could probably be optimized a fair bit for new *Mathematica*, but I won't get into that for now. One might also consider tweaking the `Opacity[]` of the contour lines for the absolute value as well, but I'll leave that as an experiment for the reader. --- Another thing you can try: ``` RegionPlot[True, {x, -Pi, Pi}, {y, -Pi, Pi}, ColorFunction -> ($ComplexToColorMap[Abs[Sin[#1 + I #2]], Arg[Sin[#1 + I #2]], {Pi, 1/50, 1, 1/50, 1}] &), ColorFunctionScaling -> False, Mesh -> 51, MeshFunctions -> {Re[Sin[#1 + I #2]] &, Im[Sin[#1 + I #2]] &}, MeshStyle -> Gray, PlotPoints -> 95] ```
7,275
I found this plot on Wikipedia: ![domain-colored plot of sine function](https://i.stack.imgur.com/GjMe4.jpg) > > [Domain coloring](http://en.wikipedia.org/wiki/Domain_coloring) of $\sin(z)$ over $(-\pi,\pi)$ on $x$ and $y$ axes. Brightness indicates absolute magnitude, saturation represents imaginary and real magnitude. > > > Despite following the link and reading the page nothing I have tried is giving me the result shown. How should this be done?
2012/06/23
[ "https://mathematica.stackexchange.com/questions/7275", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/121/" ]
I already mentioned Bernd Thaller's package `Graphics`ComplexPlot`` in the comments; if one blends the ideas from Artes's and Heike's answers, and then use the function `$ComplexToColorMap[]` from Thaller's package (I won't include it here; again, see the package for that), we get this: ![domain-colored plot](https://i.stack.imgur.com/8ic1B.png) ``` Needs["Graphics`ComplexPlot`"] (* Thaller's package; get it yourself *) f1 = RegionPlot[True, {x, -Pi, Pi}, {y, -Pi, Pi}, ColorFunction -> ($ComplexToColorMap[Abs[Sin[#1 + I #2]], Arg[Sin[#1 + I #2]], {Pi, 1/10, 1, 1/10, 1}] &), ColorFunctionScaling -> False, PlotPoints -> 200]; f2 = ContourPlot[ Evaluate@{Table[Re@Sin[x + I y] == 1/2 k, {k, -25, 25}], Table[Im@Sin[x + I y] == 1/2 k, {k, -25, 25}]}, {x, -Pi, Pi}, {y, -Pi, Pi}, PlotPoints -> 100, ContourStyle -> Gray]; f3 = ContourPlot[ Evaluate@Table[Abs@Sin[x + I y] == 1/2 k, {k, -25, 25}], {x, -Pi, Pi}, {y, -Pi, Pi}, PlotPoints -> 100, ContourStyle -> White, MaxRecursion -> 5]; Show[f1, f2, f3] ``` The `$ComplexToColorMap[]` function could probably be optimized a fair bit for new *Mathematica*, but I won't get into that for now. One might also consider tweaking the `Opacity[]` of the contour lines for the absolute value as well, but I'll leave that as an experiment for the reader. --- Another thing you can try: ``` RegionPlot[True, {x, -Pi, Pi}, {y, -Pi, Pi}, ColorFunction -> ($ComplexToColorMap[Abs[Sin[#1 + I #2]], Arg[Sin[#1 + I #2]], {Pi, 1/50, 1, 1/50, 1}] &), ColorFunctionScaling -> False, Mesh -> 51, MeshFunctions -> {Re[Sin[#1 + I #2]] &, Im[Sin[#1 + I #2]] &}, MeshStyle -> Gray, PlotPoints -> 95] ```
With Mathematica 12.0, there's now a [`ComplexPlot`](https://reference.wolfram.com/language/ref/ComplexPlot.html) function that replaces user made solutions. As with other `Plot` functions, it allows us to specify a [`ColorFunction`](https://reference.wolfram.com/language/ref/ColorFunction.html) option to manipulate how to color the plot. This particular coloring is implemented natively in the `"CyclicReImLogAbs"` option. So the modern equivalent is ``` ComplexPlot[Sin[z], {z, -Pi - Pi I, Pi + Pi I}, ColorFunction -> "CyclicReImLogAbs", Frame -> False] ``` [![Plot Result](https://i.stack.imgur.com/W0FEc.png)](https://i.stack.imgur.com/W0FEc.png)
7,275
I found this plot on Wikipedia: ![domain-colored plot of sine function](https://i.stack.imgur.com/GjMe4.jpg) > > [Domain coloring](http://en.wikipedia.org/wiki/Domain_coloring) of $\sin(z)$ over $(-\pi,\pi)$ on $x$ and $y$ axes. Brightness indicates absolute magnitude, saturation represents imaginary and real magnitude. > > > Despite following the link and reading the page nothing I have tried is giving me the result shown. How should this be done?
2012/06/23
[ "https://mathematica.stackexchange.com/questions/7275", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/121/" ]
Building on Heike's `ColorFunction`, I came up with this: [![enter image description here](https://i.stack.imgur.com/ZU9kk.png)](https://i.stack.imgur.com/ZU9kk.png) The white bits are the trickiest - you need to make sure the brightness is high where the saturation is low, otherwise the black lines appear on top of the white ones. The code is below. The functions defined are: * `complexGrid[max,n]` simply generates an $n\times n$ grid of complex numbers ranging from $-max$ to $+max$ in both axes. * `complexHSB[Z]` takes an array $Z$ of complex numbers and returns an array of $\{h,s,b\}$ values. I've tweaked the colour functions slightly. The initial $\{h,s,b\}$ values are calculated using Heike's formulas, except I don't square $s$. The brightness is then adjusted so that it is high when the saturation is low. The formula is almost the same as $b2=\max (1-s,b)$ but written in a way that makes it `Listable`. * `domainImage[func,max,n]` calls the previous two functions to create an image. `func` is the function to be plotted. The image is generated at twice the desired size and then resized back down to provide a degree of antialiasing. * `domainPlot[func,max,n]` is the end user function which embeds the image in a graphics frame. --- ``` complexGrid = Compile[{{max, _Real}, {n, _Integer}}, Block[{r}, r = Range[-max, max, 2 max/(n - 1)]; Outer[Plus, -I r, r]]]; complexHSB = Compile[{{Z, _Complex, 2}}, Block[{h, s, b, b2}, h = Arg[Z]/(2 Pi); s = Abs[Sin[2 Pi Abs[Z]]]; b = Sqrt[Sqrt[Abs[Sin[2 Pi Im[Z]] Sin[2 Pi Re[Z]]]]]; b2 = 0.5 ((1 - s) + b + Sqrt[(1 - s - b)^2 + 0.01]); Transpose[{h, Sqrt[s], b2}, {3, 1, 2}]]]; domainImage[func_, max_, n_] := ImageResize[ColorConvert[ Image[complexHSB@func@complexGrid[max, 2 n], ColorSpace -> "HSB"], "RGB"], n, Resampling -> "Gaussian"]; domainPlot[func_: Identity, max_: Pi, n_: 500] := Graphics[{}, Frame -> True, PlotRange -> max, RotateLabel -> False, FrameLabel -> {"Re[z]", "Im[z]", "Domain Colouring of " <> ToString@StandardForm@func@"z"}, BaseStyle -> {FontFamily -> "Calibri", 12}, Prolog -> Inset[domainImage[func, max, n], {0, 0}, {Center, Center}, 2` max]]; domainPlot[Sin, Pi] ``` Other examples follow: It's informative to plot the untransformed complex plane to understand what the colours indicate: ``` domainPlot[] ``` [![enter image description here](https://i.stack.imgur.com/akXDv.png)](https://i.stack.imgur.com/akXDv.png) A simple example: ``` domainPlot[Sqrt] ``` [![enter image description here](https://i.stack.imgur.com/UsLQ9.png)](https://i.stack.imgur.com/UsLQ9.png) Plotting a pure function: ``` domainPlot[(# + 2 I)/(# - 1) &] ``` [![enter image description here](https://i.stack.imgur.com/0p0CP.png)](https://i.stack.imgur.com/0p0CP.png) I think this one is very pretty: ``` domainPlot[Log] ``` [![enter image description here](https://i.stack.imgur.com/66Ukq.png)](https://i.stack.imgur.com/66Ukq.png)
With Mathematica 12.0, there's now a [`ComplexPlot`](https://reference.wolfram.com/language/ref/ComplexPlot.html) function that replaces user made solutions. As with other `Plot` functions, it allows us to specify a [`ColorFunction`](https://reference.wolfram.com/language/ref/ColorFunction.html) option to manipulate how to color the plot. This particular coloring is implemented natively in the `"CyclicReImLogAbs"` option. So the modern equivalent is ``` ComplexPlot[Sin[z], {z, -Pi - Pi I, Pi + Pi I}, ColorFunction -> "CyclicReImLogAbs", Frame -> False] ``` [![Plot Result](https://i.stack.imgur.com/W0FEc.png)](https://i.stack.imgur.com/W0FEc.png)
55,329,028
To build context, my app has a stack of cards (similar to Tinder) that flip and each could contain a lot of text on one side that require a UITextView for scrolling. It's basically a flashcard app, so once the user is done looking at the card, they swipe it away to view the next one. I'm trying to make it so the user can tap anywhere on the card to flip it, so I added a clear button that fills up the card. My problem is that when the button is at the front, it blocks the text view from being scrollable, and when the button is at the back, the text view blocks it from being pressed. Is there a way around this somehow to allow for both functionalities?
2019/03/24
[ "https://Stackoverflow.com/questions/55329028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11116880/" ]
Maybe you can add a `UITapGestureRecognizer` to the text view itself. Something like: ``` let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.didTap(_:))) textView.addGestureRecognizer(tapGesture) @objc func didTap(_ gesture: UITapGestureRecognizer) { // Handle the tap } ```
did you try a tableView or a collectionView, you can customize your cell to look like a card then when a user clicks the cell it will flip or present a popup view, thats easier.
55,329,028
To build context, my app has a stack of cards (similar to Tinder) that flip and each could contain a lot of text on one side that require a UITextView for scrolling. It's basically a flashcard app, so once the user is done looking at the card, they swipe it away to view the next one. I'm trying to make it so the user can tap anywhere on the card to flip it, so I added a clear button that fills up the card. My problem is that when the button is at the front, it blocks the text view from being scrollable, and when the button is at the back, the text view blocks it from being pressed. Is there a way around this somehow to allow for both functionalities?
2019/03/24
[ "https://Stackoverflow.com/questions/55329028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11116880/" ]
You can create a `UITapGestureRecognizer`, like so: ``` let gesture = UITapGestureRecognizer(target: self, action: #selector(tap(gesture:))) addGestureRecognizer(gesture) ``` And the function to trigger: ``` @objc func tap(gesture: UITapGestureRecognizer) { print("Tap!") } ```
did you try a tableView or a collectionView, you can customize your cell to look like a card then when a user clicks the cell it will flip or present a popup view, thats easier.
55,329,028
To build context, my app has a stack of cards (similar to Tinder) that flip and each could contain a lot of text on one side that require a UITextView for scrolling. It's basically a flashcard app, so once the user is done looking at the card, they swipe it away to view the next one. I'm trying to make it so the user can tap anywhere on the card to flip it, so I added a clear button that fills up the card. My problem is that when the button is at the front, it blocks the text view from being scrollable, and when the button is at the back, the text view blocks it from being pressed. Is there a way around this somehow to allow for both functionalities?
2019/03/24
[ "https://Stackoverflow.com/questions/55329028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11116880/" ]
You can create a `UITapGestureRecognizer`, like so: ``` let gesture = UITapGestureRecognizer(target: self, action: #selector(tap(gesture:))) addGestureRecognizer(gesture) ``` And the function to trigger: ``` @objc func tap(gesture: UITapGestureRecognizer) { print("Tap!") } ```
Maybe you can add a `UITapGestureRecognizer` to the text view itself. Something like: ``` let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.didTap(_:))) textView.addGestureRecognizer(tapGesture) @objc func didTap(_ gesture: UITapGestureRecognizer) { // Handle the tap } ```
41,721
I wrote a module that adds a mass action for creating invoices and shipments from the invoice. This gets done by calling the URL ./sales\_order/finishorder (calls the finish\_order function. After finishing creating the invoices and shipments I wanted to redirect to pdfinvoices to directly print the PDFs for the orders. I tried this using ``` $this->_redirect('*/*/pdfinvoices'); ``` or ``` $this->_redirect('*/*/*/pdfinvoices'); ``` but neither will work: The first one just leads back to the order grid, the second one displays a blank page. I think the second one is correct but the required POST parameters are missing. Is there a way to redirect them to sales\_order/pdfinvoices?
2014/10/28
[ "https://magento.stackexchange.com/questions/41721", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/12910/" ]
The first line in `pdfinvoices` is: ``` $orderIds = $this->getRequest()->getPost('order_ids'); ``` Thus it is expecting an array list of order ids to work on. Make sure your mass action variable is called `order_ids`. If you then forward to the `pdfinvoice` action, it will use the same order ids you just worked on. If, for some reason you need to eliminate any ids from the list, (could not process shipping as an example), build a new array of allowed order ids. Then just before you `_forward`, inject the order ids you want to process into the post variable. ``` $this->getRequest()->setPost('order_ids',$orderIds); $this->_forward('pdfinvoices'); ```
As I see both methods are in the same controller, so you can do it like this in the end of `finishorder` method: ``` // set post $this->getRequest()->setPost('order_ids',$orderIds); $this->_forward('pdfinvoices'); ```
168,451
> > I found four injured men alive. > > > In this sentence, the adjective "alive" comes after the noun "men". Why we have to use adjective "alive" after the noun, not before? because in adjective order, adjectives should come before the nouns.
2018/06/04
[ "https://ell.stackexchange.com/questions/168451", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/76335/" ]
I think the structure is Subject +verb+object+ adjective as objective complement. > > **I found four injured men alive** > > > it is similar to the structure **He painted the house green** **The Jury found him guilty**
It's a stylized use of "find". You can "find [something] *to be* [some adjective]". The "to be" is optional. > > I **found** her (to be) **perfectly charming** > > > I **found** the dinner (to be) **almost inedible**. > > > I **found** the movie (to be) **exciting but implausible**. > > > In a similar way, in your example sentence, the writer *found* the injured men *to be* alive.
121,175
Say we are able to mass produce clones for our clone army and give them memories. Then we decide to give them the same template/personality/identity/etc. What psychological effects would this have on the clones? EDIT : They know they're clones.
2018/08/12
[ "https://worldbuilding.stackexchange.com/questions/121175", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/54091/" ]
**How do you interact with other members of H. sapiens?** What you describe is a clone that is mostly alike. They get to have different memories from the moment they are born. From a genetic perspective, something like 99.4% of our genome is cloned. How do you treat your almost-clones? Really, the more important psychological question is whether you treat them as an individual or not. If you call them all by numbers and give them bar codes, psychoses should form. However, if you recognize them as unique human beings, despite having the same appearances, they should treat themselves as unique individuals as well. Instinctively, I think tattooing would be popular. You should decide whether that is acceptable for your army or not. Tattooing would be a very powerful way to create uniqueness in a sea of identicalness. I think that it would be very popular, should you choose to admit it in your army.
When identical twins interact with each other, they're effectively dealing with clones -- they have the same genetics and even the same birthdate. Of course these twins **also** interact with others, but the same principles would apply: * Individuals who know each other would notice small differences, not large similarities. * To a lesser degree, that would also apply to individuals who don't know each other, but I expect that they have more trouble telling each other apart. * When one of them gets an illness that *may* have a genetic component, the other will be quite worried. Not just for a fellow human but also for himself. There are twins in my family. I haven't mixed them up *in person* since I was three years old. It is more difficult on pictures, especially old ones. As a kid, I couldn't understand how strangers could mistake the two ...
60,753,718
We are going to handle another team's work and move to use Azure DevOps Service instead of SVN. They put everything in a single Git Repo. That made the Repo quiet large. Have no idea how large it is. Per my understanding, Microsoft hold data in their own Azure SQL Database. If so, do we have any limited size of Git Repositories in Azure DevOps Service? Could we pay additional if there's any way to increase that limit?
2020/03/19
[ "https://Stackoverflow.com/questions/60753718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12911012/" ]
I found an answer: ``` pacman -S git ``` Now I can use git in my mysy terminal.
If you downloaded "Git for Windows" then that installs MSYS2 but it's different to the MSYS you installed. They would not know about each other. You can merge the to as this guy writes (number 3): <https://www.automationdojos.com/install-pacman-on-git-for-win-without-full-setup/> If you start fresh, the I would get MSYS2 first, then use pacman to install mingw64 toolchain and mingw64 version of git - which is what you get when you install "Git for Windows": <https://gist.github.com/piotrkundu/e7d94204dd3c48525b23c59fe5d23478> `pacman -S git` will get you the MSYS version of git which runs with POSIX emulation (potentially slower).
36,700,643
I'm having trouble getting a `glyphicon-search` button to line up in bootstrap. This is not a unique problem, I found [this question](https://stackoverflow.com/questions/10615872/bootstrap-align-input-with-button) that asks a similar thing, except the accepted and celebrated answer isn't working for me. Just like the answer, I have a div input group wrapper that should line up the field, but it isn't working, as you can see in my jsfiddle: <http://jsfiddle.net/pk84s94t/> ``` <div class="input-group"> <span class="input-group-btn"> <button class="btn btn-default glyphicon glyphicon-search input-sm" type="submit"></button> </span> <input type="text" class="form-control input-sm"> </div> ```
2016/04/18
[ "https://Stackoverflow.com/questions/36700643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4945793/" ]
<http://jsfiddle.net/kv8n7n5g/> ``` <div class="input-group"> <span class="input-group-btn"> <button class="btn btn-default" type="button"><i class="glyphicon glyphicon-search"></i></button> </span> <input type="text" class="form-control" placeholder="Search"> </div> ``` You had the glyphicon classes inside the button tag. If that doesn't work you may have to change the line-height of the icon to 1. I was using ionicons and the 1.4... line-height was throwing everything off.
That's interesting. I've never tried using a button with an input group like that, and I'm not sure why that behavior is occuring. Seems to be an easy fix though. I added `top:0` to the existing rule `.input-group-btn>.btn` which already had `position: relative;` ... <http://jsfiddle.net/pk84s94t/1/> **EDIT** While this does fix the behavior, Rachel S's answer is a better solution as it's not changing CSS rules, but using proper HTML within bootstrap to fix the problem.
36,700,643
I'm having trouble getting a `glyphicon-search` button to line up in bootstrap. This is not a unique problem, I found [this question](https://stackoverflow.com/questions/10615872/bootstrap-align-input-with-button) that asks a similar thing, except the accepted and celebrated answer isn't working for me. Just like the answer, I have a div input group wrapper that should line up the field, but it isn't working, as you can see in my jsfiddle: <http://jsfiddle.net/pk84s94t/> ``` <div class="input-group"> <span class="input-group-btn"> <button class="btn btn-default glyphicon glyphicon-search input-sm" type="submit"></button> </span> <input type="text" class="form-control input-sm"> </div> ```
2016/04/18
[ "https://Stackoverflow.com/questions/36700643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4945793/" ]
<http://jsfiddle.net/kv8n7n5g/> ``` <div class="input-group"> <span class="input-group-btn"> <button class="btn btn-default" type="button"><i class="glyphicon glyphicon-search"></i></button> </span> <input type="text" class="form-control" placeholder="Search"> </div> ``` You had the glyphicon classes inside the button tag. If that doesn't work you may have to change the line-height of the icon to 1. I was using ionicons and the 1.4... line-height was throwing everything off.
The problem you are having is due to the glyphicon button default size in bootstrap. But if you put some text in the button it aligns perfectly as now the button for the text is given more priority than the glyphicon's default. For the text I used &nbsp. It works fine now. ``` <div class="input-group"> <input class="form-control" type="text"> <span class="input-group-btn"> <button type="submit" class="btn btn-default"> <span class="glyphicon glyphicon-search"></span>&nbsp </button> </span> </div> ```
46,854,159
:) Is there an easy way to group a particular data set into a reduced data frame from certain characteristics? I was thinking of an algorithm for this, but is there any function in R that can be used for this? I've trying to use `dplyr`, but it didin't work very well... E.g.: [![enter image description here](https://i.stack.imgur.com/maZdJ.png)](https://i.stack.imgur.com/maZdJ.png) P.S .: My data is in an matrix of more than 1Gb, that is, I need a more automatic process. Example Data: ``` structure(list(Nun = 1:6, Event = c(1L, 1L, 1L, 1L, 2L, 2L), Time = structure(c(3L, 4L, 5L, 6L, 1L, 2L), .Label = c("11:34", "11:36", "8:50", "8:52", "8:54", "8:56"), class = "factor"), User = structure(c(1L, 1L, 1L, 1L, 2L, 2L), .Label = c("U1", "U7"), class = "factor")), .Names = c("Nun", "Event", "Time", "User"), class = "data.frame", row.names = c(NA, -6L)) ```
2017/10/20
[ "https://Stackoverflow.com/questions/46854159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6942928/" ]
You're getting caught out by the [`QueryDict.__setitem__`](https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.QueryDict.__setitem__). When you do `querydict['key'] = value`, it sets the key to `[value]`, not `value`. You can use the [`QueryDict.setlist`](https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.QueryDict.setlist) method to set the given key to the given list. ``` querydict = QueryDict('', mutable=True) for key in request.POST.iteritems(): postlist = post[key].split(',') querydict.setlist(key, postlist) ``` Since you are going to loop through every key in the post data, I think you can remove the `update()` step from your code.
If I've understood the constraints correctly, you should use [builtin array type](https://docs.python.org/2/library/array.html). ``` >>> q = U"2,4,6,7" >>> import array >>> ary = array.array('u', q) >>> [i for i in ary if i.isdigit()] [u'2', u'4', u'6', u'7'] ```
8,496,351
I have jQuery UI's demo form like below. How do i submit data via ajax to a page called add.html.php? style ``` <style> body { font-size: 62.5%; } label, input { display:block; } input.text { margin-bottom:12px; width:95%; padding: .4em; } fieldset { padding:0; border:0; margin-top:25px; } h1 { font-size: 1.2em; margin: .6em 0; } div#users-contain { width: 350px; margin: 20px 0; } div#users-contain table { margin: 1em 0; border-collapse: collapse; width: 100%; } div#users-contain table td, div#users-contain table th { border: 1px solid #eee; padding: .6em 10px; text-align: left; } .ui-dialog .ui-state-error { padding: .3em; } .validateTips { border: 1px solid transparent; padding: 0.3em; } </style> ``` script ``` <script> $(function() { // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore! $( "#dialog:ui-dialog" ).dialog( "destroy" ); var name = $( "#name" ), email = $( "#email" ), password = $( "#password" ), allFields = $( [] ).add( name ).add( email ).add( password ), tips = $( ".validateTips" ); $( "#dialog-form" ).dialog({ autoOpen: false, height: 300, width: 350, modal: true, buttons: { "Create an account": function() { var bValid = true; allFields.removeClass( "ui-state-error" ); if ( bValid ) { $( "#users tbody" ).append( "<tr>" + "<td>" + name.val() + "</td>" + "<td>" + email.val() + "</td>" + "<td>" + password.val() + "</td>" + "</tr>" ); $( this ).dialog( "close" ); } }, Cancel: function() { $( this ).dialog( "close" ); } }, close: function() { allFields.val( "" ).removeClass( "ui-state-error" ); } }); $( "#create-user" ) .button() .click(function() { $( "#dialog-form" ).dialog( "open" ); }); }); </script> ``` html ``` <div class="demo"> <div id="dialog-form" title="Create new user"> <p class="validateTips">All form fields are required.</p> <form> <fieldset> <label for="name">Name</label> <input type="text" name="name" id="name" class="text ui-widget-content ui-corner-all" /> <label for="email">Email</label> <input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all" /> <label for="password">Password</label> <input type="password" name="password" id="password" value="" class="text ui-widget-content ui-corner-all" /> </fieldset> </form> </div> <div id="users-contain" class="ui-widget"> <h1>Existing Users:</h1> <table id="users" class="ui-widget ui-widget-content"> <thead> <tr class="ui-widget-header "> <th>Name</th> <th>Email</th> <th>Password</th> </tr> </thead> <tbody> <tr> <td>John Doe</td> <td>john.doe@example.com</td> <td>johndoe1</td> </tr> </tbody> </table> </div> <button id="create-user">Create new user</button> </div><!-- End demo --> <div class="demo-description"> <p>Use a modal dialog to require that the user enter data during a multi-step process. Embed form markup in the content area, set the <code>modal</code> option to true, and specify primary and secondary user actions with the <code>buttons</code> option.</p> ```
2011/12/13
[ "https://Stackoverflow.com/questions/8496351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/867592/" ]
In your `form`, add an input type of submit: ``` <input type='submit' value='submit' /> ``` Alternatively, you can also just create a function that submits the form: ``` function fncSubmit() { $('form').trigger('submit'); } ``` Add this in the `ready` block: ``` $('form').submit(function() { $.ajax( { type: 'POST', url: 'add.html.php', data: $(this).serializeArray(), success: function(data, textStatus, jqXHR) { //code }, error: function(jqXHR, textStatus, errorThrown) { //code } }); }); ```
First, you'll need to give the form an ID and give it a way to submit. (a button in this example) ``` <form name="loginForm" id="loginForm"> //Inputs <button type="button" id="submitButton">Submit</button> </form> ``` Then, you'll want to throw a click event on on the button to submit the form to the ajax call. ``` $('button#submitButton').click( function() { $.ajax( { type:"POST", url:"add.html.php", data: $('#loginForm').serialize(), success: function(message) { //code to execute if the ajax doesn't throw an error }, error: function(jqXHR, textStatus, errorThrown) { //code to execute if the ajax does throw an error } }); }); ```
25,708,631
I have two class, main class is app.php in root directory, and db.php in \system How To Get property $config in class base, with namespace pattern?? I want to get $config in class base, this is what I want I define config for hostname,user,pass then I declare base class wit new \App\base I can get config in class db ``` <?php // \App.php namespace App; class base{ private $config; private $db; function __construct($config){ $this->config = $config; $this->db = new \App\system\db; } public function getTest() { return $this->test; } } function load($namespace) { $splitpath = explode('\\', $namespace); $path = ''; $name = ''; $firstword = true; for ($i = 0; $i < count($splitpath); $i++) { if ($splitpath[$i] && !$firstword) { if ($i == count($splitpath) - 1) { $name = $splitpath[$i]; } else { $path .= DIRECTORY_SEPARATOR . $splitpath[$i]; } } if ($splitpath[$i] && $firstword) { if ($splitpath[$i] != __NAMESPACE__) { break; } $firstword = false; } } if (!$firstword) { $fullpath = __DIR__ . $path . DIRECTORY_SEPARATOR . $name . '.php'; return include_once ($fullpath); } return false; } function loadPath($absPath) { return include_once ($absPath); } spl_autoload_register(__NAMESPACE__ . '\load'); ?> <?php // \System\db.php namespace App\system; class db{ private $config; function __construct(){ $this->config = "How To Get property $config in class base, with namespace pattern??"; } } ?> ```
2014/09/07
[ "https://Stackoverflow.com/questions/25708631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1286189/" ]
AFAIK all current implementations of websockets depend on a handshake via HTTP. After the handshake the existing connection is upgraded. You don't get a new one and the port stays the same. Basically all websocket connections start as HTTP connections. As a side note the ports, IP addresses etc. are subject of the server, not the application itself. It might be possible to configure your server so that two ports can be used for an application, but they would both be used for HTTP and websocket alike. On the other hand this might be useful in your situation.
Spring WebSocket different port for ws:// protocol -------------------------------------------------- Due to limitation and in order to use websockets on App Engine Flexible Environment, app need to connect directly to application instance using the instance's public external IP. This IP can be obtained from the metadata server. All MVC/Rest (http://) call should still serve from 8080 and in App Engine Flexible Environment ws:// server from ws://external\_ip:65080 ### working code <https://github.com/kevendra/springmvc-websocket-sample> ``` http://localhost:8080/ ws://localhost:8080/ ``` to work with App Engine need below ``` http://localhost:8080/ ws://localhost:65080/ - in local ws://external_ip:65080/ - App engine ``` ### Ref: Extends org.eclipse.jetty.websocket.server.WebSocketHandler and start server context to 65080, but I'm looking for server managed by spring * [How do I create an embedded WebSocket server Jetty 9?](https://stackoverflow.com/questions/15645341/how-do-i-create-an-embedded-websocket-server-jetty-9) * [Spring 4 WebSocket Remote Broker configuration](https://stackoverflow.com/questions/20747283/spring-4-websocket-remote-broker-configuration)
7,572
I would like to simulate the trajectory of a weather balloon in an altitude of 12 to 20 km. For this I would like to know how the velocity-field (i.e. wind-speed and direction as a function of position and time) looks like and how constant it is in the time and space domain. Is there some publicly available data about air-circulation in the stratosphere? Or do you have an idea how to generate test-data for my simulation?
2016/02/24
[ "https://earthscience.stackexchange.com/questions/7572", "https://earthscience.stackexchange.com", "https://earthscience.stackexchange.com/users/5526/" ]
[This presentation](http://www.goes-r.gov/downloads/AMS/AMS2015/January%208/Joint%20Session%2019/Cubesat%20FTS%20for%203D%20Winds%20AMS%20J19.4.pdf) mentions "Atmospheric Motion Vectors (AMVs)", and specifically mentions a number of AMVs, which separately cover the globe (GOES AMVs ±60N, plus polar AMVs from MODIS/AVHRR/VIIRS, and a combined product from UW CIMSS) but says that are all only 3 layers. That presentation is talking about producing a more global, higher resolution product, but it's only a year old, so I'd guess the data isn't available yet. However, the [UW CIMSS AMV page](http://tropic.ssec.wisc.edu/misc/winds/info.winds.gridded.html) says that their datasets have 13 layers, so maybe it is suited for what you need. The data is gap-filled with modelled data.
I have also found these maps: <http://earth.nullschool.net/> It is a nice visualization of winds at different elevations (from surface up to 10hPa).
24,936,123
I found that I cannot update my device to the ADB connectable driver, what's wrong with that??? When I updated my device to the adb connectable driver (..sdk\extras\google\usb\_driver), and then press 'Next, it shows 'Window has determined the driver software for your device is up to date. WPD Composite Device' I have already spent many hours to the solve,please help me.
2014/07/24
[ "https://Stackoverflow.com/questions/24936123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3873277/" ]
I had same problem with my xperia u, and I use [this](http://androidxda.com/download-sony-xperia-usb-driver) page to download driver. After intalling driver, adb works with device like a charm.
Try executing `adb kill-server`, `adb start-server` and replug the device. Also, find the `adb_usb.ini` file (usually in your home folder) and add a line with `054c` (Extracted from the [official documentation](https://developer.android.com/tools/device.html)).
20,192,531
What is the **difference** between a Windows **service** and a Windows **process**?
2013/11/25
[ "https://Stackoverflow.com/questions/20192531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192982/" ]
A service is a true-blooded Windows process, no difference there. The only thing that's special about a service is that it is started by the operating system and runs in a separate session. An isolated one that keeps it from interfering with the desktop session. Traditionally named a [*daemon*](http://en.wikipedia.org/wiki/Daemon_%28computing%29).
A service is a process **without** user interface. You can call service as a subset of process.
20,192,531
What is the **difference** between a Windows **service** and a Windows **process**?
2013/11/25
[ "https://Stackoverflow.com/questions/20192531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192982/" ]
A service is a true-blooded Windows process, no difference there. The only thing that's special about a service is that it is started by the operating system and runs in a separate session. An isolated one that keeps it from interfering with the desktop session. Traditionally named a [*daemon*](http://en.wikipedia.org/wiki/Daemon_%28computing%29).
Windows services are essentially long-running executable applications that run in their own windows sessions and do not possess any user interface. These can be automatically started when the computer boots up and can be paused and restarted.
20,192,531
What is the **difference** between a Windows **service** and a Windows **process**?
2013/11/25
[ "https://Stackoverflow.com/questions/20192531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192982/" ]
A service is a process **without** user interface. You can call service as a subset of process.
Windows services are essentially long-running executable applications that run in their own windows sessions and do not possess any user interface. These can be automatically started when the computer boots up and can be paused and restarted.
40,570,285
Some of the file I'm working with: <http://pastebin.com/WriQcuPs> Currently I had to make the population, latitude, and longitude strings or else I wouldn't get the desired output. I want for them to be int, double, and double in that order. ``` public class City { String countrycode; String city; String region; String population; String latitude; String longitude; public City (String countrycode, String city, String region, String population, String latitude, String longitude) { this.countrycode = countrycode; this.city = city; this.region = region; this.population = population; this.latitude = latitude; this.longitude = longitude; } public String toString() { return this.city + "," + this.population + "," + this.latitude + "," + this.longitude; } } ``` --- I suspect it has something to do with how I created the array list. Is there a way to make it so that some of the elements of the list are of a different type? I tried changing it to `ArrayList<City>` and changing the data types in the `City` class but it still gave me a ton of errors. ``` public class Reader { In input = new In("file:world_cities.txt"); private static City cityInfo; public static void main(String[] args) { // open file In input = new In("world_cities.txt"); input = new In("world_cities.txt"); try { // write output to file FileWriter fw = new FileWriter("cities_out.txt"); PrintWriter pw = new PrintWriter(fw); int line = 0; // iterate through all lines in the file while (line < 47913) { // read line String cityLine = input.readLine(); // create array list ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(","))); // add line to array list cityList.add(cityLine); // increase counter line += 1; // create instance cityInfo = new City(cityList.get(0), cityList.get(1), cityList.get(2), cityList.get(3), cityList.get(4), cityList.get(5)); System.out.println(cityInfo); // print output to file pw.println(cityInfo); } // close file pw.close(); } // what is printed when there is an error when saving to file catch (Exception e) { System.out.println("ERROR!"); } // close the file input.close(); } } ```
2016/11/13
[ "https://Stackoverflow.com/questions/40570285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7151725/" ]
If you declare the list as follows, you can put instances of any reference type into it: ``` List<Object> list = new ArrayList<>(); ``` But the downside is that when you get an element from the list, the static type of the element will be `Object`, and you will need to type cast it to the type that you need. Also note, that you can't put an `int` or a `double` into a `List`. Primitive types are not reference types, and the `List` API requires the elements to be instances of reference types. You need to use the corresponding wrapper types; i.e. `Integer` and `Double`. --- Looking at more of your code, I spotted this: ``` ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(","))); ``` If you change the list to `List<Object>` where the objects are either `Integer` or `Double`, you won't be able to build your list like that. In fact, the more I look this, the more I think that you don't need a list at all. You should be doing something like this: ``` // read line String cityLine = input.readLine(); String[] parts = cityLine.split(","); // increase counter line += 1; // create instance cityInfo = new City(parts[0], parts[1], parts[2], Integer.parseInt(parts[3]), Double.parseDouble(parts[4]), Double.parseDouble(parts[5])); ``` Notice: there is no `List` there at all!!
You could parse the string values before they are passed into a new `City` object. Then you could change the constructor and variables within a `City` to be an int, double, and double. ``` int pop = Integer.parseInt(cityList.get(3)); double latitude = Double.parseDouble(cityList.get(4)); double longitude = Double.parseDouble(cityList.get(5)); cityInfo = new City(cityList.get(0), cityList.get(1), cityList.get(2), pop, latitude, longitude); ```
40,570,285
Some of the file I'm working with: <http://pastebin.com/WriQcuPs> Currently I had to make the population, latitude, and longitude strings or else I wouldn't get the desired output. I want for them to be int, double, and double in that order. ``` public class City { String countrycode; String city; String region; String population; String latitude; String longitude; public City (String countrycode, String city, String region, String population, String latitude, String longitude) { this.countrycode = countrycode; this.city = city; this.region = region; this.population = population; this.latitude = latitude; this.longitude = longitude; } public String toString() { return this.city + "," + this.population + "," + this.latitude + "," + this.longitude; } } ``` --- I suspect it has something to do with how I created the array list. Is there a way to make it so that some of the elements of the list are of a different type? I tried changing it to `ArrayList<City>` and changing the data types in the `City` class but it still gave me a ton of errors. ``` public class Reader { In input = new In("file:world_cities.txt"); private static City cityInfo; public static void main(String[] args) { // open file In input = new In("world_cities.txt"); input = new In("world_cities.txt"); try { // write output to file FileWriter fw = new FileWriter("cities_out.txt"); PrintWriter pw = new PrintWriter(fw); int line = 0; // iterate through all lines in the file while (line < 47913) { // read line String cityLine = input.readLine(); // create array list ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(","))); // add line to array list cityList.add(cityLine); // increase counter line += 1; // create instance cityInfo = new City(cityList.get(0), cityList.get(1), cityList.get(2), cityList.get(3), cityList.get(4), cityList.get(5)); System.out.println(cityInfo); // print output to file pw.println(cityInfo); } // close file pw.close(); } // what is printed when there is an error when saving to file catch (Exception e) { System.out.println("ERROR!"); } // close the file input.close(); } } ```
2016/11/13
[ "https://Stackoverflow.com/questions/40570285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7151725/" ]
If you declare the list as follows, you can put instances of any reference type into it: ``` List<Object> list = new ArrayList<>(); ``` But the downside is that when you get an element from the list, the static type of the element will be `Object`, and you will need to type cast it to the type that you need. Also note, that you can't put an `int` or a `double` into a `List`. Primitive types are not reference types, and the `List` API requires the elements to be instances of reference types. You need to use the corresponding wrapper types; i.e. `Integer` and `Double`. --- Looking at more of your code, I spotted this: ``` ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(","))); ``` If you change the list to `List<Object>` where the objects are either `Integer` or `Double`, you won't be able to build your list like that. In fact, the more I look this, the more I think that you don't need a list at all. You should be doing something like this: ``` // read line String cityLine = input.readLine(); String[] parts = cityLine.split(","); // increase counter line += 1; // create instance cityInfo = new City(parts[0], parts[1], parts[2], Integer.parseInt(parts[3]), Double.parseDouble(parts[4]), Double.parseDouble(parts[5])); ``` Notice: there is no `List` there at all!!
By looking at the `City` class you have defined the members are of different primitive data types. When you read the file to create a City, you need to pass the constructor parameters with the defined data types as in your constructor. Modify your `City` class as below : ``` public class City { String countrycode; String city; String region; int population; double latitude; double longitude; ... ``` Try the following : ``` cityInfo = new City(cityList.get(0), cityList.get(1), cityList.get(2), Integer.parseInt(cityList.get(3)), Double.parseDouble(cityList.get(4)), Double.parseDouble(cityList.get(5))); ``` This will convert the Strings to int and double as desired by the `City` class.
40,570,285
Some of the file I'm working with: <http://pastebin.com/WriQcuPs> Currently I had to make the population, latitude, and longitude strings or else I wouldn't get the desired output. I want for them to be int, double, and double in that order. ``` public class City { String countrycode; String city; String region; String population; String latitude; String longitude; public City (String countrycode, String city, String region, String population, String latitude, String longitude) { this.countrycode = countrycode; this.city = city; this.region = region; this.population = population; this.latitude = latitude; this.longitude = longitude; } public String toString() { return this.city + "," + this.population + "," + this.latitude + "," + this.longitude; } } ``` --- I suspect it has something to do with how I created the array list. Is there a way to make it so that some of the elements of the list are of a different type? I tried changing it to `ArrayList<City>` and changing the data types in the `City` class but it still gave me a ton of errors. ``` public class Reader { In input = new In("file:world_cities.txt"); private static City cityInfo; public static void main(String[] args) { // open file In input = new In("world_cities.txt"); input = new In("world_cities.txt"); try { // write output to file FileWriter fw = new FileWriter("cities_out.txt"); PrintWriter pw = new PrintWriter(fw); int line = 0; // iterate through all lines in the file while (line < 47913) { // read line String cityLine = input.readLine(); // create array list ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(","))); // add line to array list cityList.add(cityLine); // increase counter line += 1; // create instance cityInfo = new City(cityList.get(0), cityList.get(1), cityList.get(2), cityList.get(3), cityList.get(4), cityList.get(5)); System.out.println(cityInfo); // print output to file pw.println(cityInfo); } // close file pw.close(); } // what is printed when there is an error when saving to file catch (Exception e) { System.out.println("ERROR!"); } // close the file input.close(); } } ```
2016/11/13
[ "https://Stackoverflow.com/questions/40570285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7151725/" ]
If you declare the list as follows, you can put instances of any reference type into it: ``` List<Object> list = new ArrayList<>(); ``` But the downside is that when you get an element from the list, the static type of the element will be `Object`, and you will need to type cast it to the type that you need. Also note, that you can't put an `int` or a `double` into a `List`. Primitive types are not reference types, and the `List` API requires the elements to be instances of reference types. You need to use the corresponding wrapper types; i.e. `Integer` and `Double`. --- Looking at more of your code, I spotted this: ``` ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(","))); ``` If you change the list to `List<Object>` where the objects are either `Integer` or `Double`, you won't be able to build your list like that. In fact, the more I look this, the more I think that you don't need a list at all. You should be doing something like this: ``` // read line String cityLine = input.readLine(); String[] parts = cityLine.split(","); // increase counter line += 1; // create instance cityInfo = new City(parts[0], parts[1], parts[2], Integer.parseInt(parts[3]), Double.parseDouble(parts[4]), Double.parseDouble(parts[5])); ``` Notice: there is no `List` there at all!!
I believe no, but you can do this ``` public class City { String countrycode; String city; String region; String population; double latitude; double longitude; public City (String countrycode, String city, String region, String population, double latitude, double longitude) { this.countrycode = countrycode; this.city = city; this.region = region; this.population = population; this.latitude = latitude; this.longitude = longitude; } public String toString() { return this.city + "," + this.population + "," + this.latitude + "," + this.longitude; } } public class Reader { In input = new In("file:world_cities.txt"); private static City cityInfo; public static void main(String[] args) { // open file In input = new In("world_cities.txt"); input = new In("world_cities.txt"); try { // write output to file FileWriter fw = new FileWriter("cities_out.txt"); PrintWriter pw = new PrintWriter(fw); int line = 0; // iterate through all lines in the file while (line < 47913) { // read line String cityLine = input.readLine(); // create array list ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(","))); // add line to array list cityList.add(cityLine); // increase counter line += 1; // create instance cityInfo = new City(cityList.get(0), cityList.get(1), cityList.get(2), cityList.get(3), Doule.parseDouble(cityList.get(4)), Doule.parseDouble(cityList.get(5))); System.out.println(cityInfo); // print output to file pw.println(cityInfo); } // close file pw.close(); } // what is printed when there is an error when saving to file catch (Exception e) { System.out.println("ERROR!"); } // close the file input.close(); } } ```
40,570,285
Some of the file I'm working with: <http://pastebin.com/WriQcuPs> Currently I had to make the population, latitude, and longitude strings or else I wouldn't get the desired output. I want for them to be int, double, and double in that order. ``` public class City { String countrycode; String city; String region; String population; String latitude; String longitude; public City (String countrycode, String city, String region, String population, String latitude, String longitude) { this.countrycode = countrycode; this.city = city; this.region = region; this.population = population; this.latitude = latitude; this.longitude = longitude; } public String toString() { return this.city + "," + this.population + "," + this.latitude + "," + this.longitude; } } ``` --- I suspect it has something to do with how I created the array list. Is there a way to make it so that some of the elements of the list are of a different type? I tried changing it to `ArrayList<City>` and changing the data types in the `City` class but it still gave me a ton of errors. ``` public class Reader { In input = new In("file:world_cities.txt"); private static City cityInfo; public static void main(String[] args) { // open file In input = new In("world_cities.txt"); input = new In("world_cities.txt"); try { // write output to file FileWriter fw = new FileWriter("cities_out.txt"); PrintWriter pw = new PrintWriter(fw); int line = 0; // iterate through all lines in the file while (line < 47913) { // read line String cityLine = input.readLine(); // create array list ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(","))); // add line to array list cityList.add(cityLine); // increase counter line += 1; // create instance cityInfo = new City(cityList.get(0), cityList.get(1), cityList.get(2), cityList.get(3), cityList.get(4), cityList.get(5)); System.out.println(cityInfo); // print output to file pw.println(cityInfo); } // close file pw.close(); } // what is printed when there is an error when saving to file catch (Exception e) { System.out.println("ERROR!"); } // close the file input.close(); } } ```
2016/11/13
[ "https://Stackoverflow.com/questions/40570285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7151725/" ]
If you declare the list as follows, you can put instances of any reference type into it: ``` List<Object> list = new ArrayList<>(); ``` But the downside is that when you get an element from the list, the static type of the element will be `Object`, and you will need to type cast it to the type that you need. Also note, that you can't put an `int` or a `double` into a `List`. Primitive types are not reference types, and the `List` API requires the elements to be instances of reference types. You need to use the corresponding wrapper types; i.e. `Integer` and `Double`. --- Looking at more of your code, I spotted this: ``` ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(","))); ``` If you change the list to `List<Object>` where the objects are either `Integer` or `Double`, you won't be able to build your list like that. In fact, the more I look this, the more I think that you don't need a list at all. You should be doing something like this: ``` // read line String cityLine = input.readLine(); String[] parts = cityLine.split(","); // increase counter line += 1; // create instance cityInfo = new City(parts[0], parts[1], parts[2], Integer.parseInt(parts[3]), Double.parseDouble(parts[4]), Double.parseDouble(parts[5])); ``` Notice: there is no `List` there at all!!
You can do something like this: **READER CLASS** ``` import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; public class Reader { In input = new In("file:world_cities.txt"); private static City cityInfo; public static void main(String[] args) { // open file // In input = new In("world_cities.txt"); // input = new In("world_cities.txt"); try { // write output to file FileWriter fw = new FileWriter("cities_out.txt"); PrintWriter pw = new PrintWriter(fw); int line = 0; // iterate through all lines in the file while (line < 47913) { // read line String cityLine = input.readLine(); // create array list ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(","))); // add line to array list cityList.add(cityLine); // increase counter line += 1; // create instance cityInfo = new City(cityList.get(0), cityList.get(1), cityList.get(2), Integer.parseInt(cityList.get(3)), Double.parseDouble(cityList.get(4)), Double.parseDouble(cityList.get(5))); System.out.println(cityInfo); // print output to file pw.println(cityInfo); } // close file pw.close(); } // what is printed when there is an error when saving to file catch (Exception e) { System.out.println("ERROR!"); } // close the file input.close(); } } ``` **CITY CLASS** ``` public class City { String countrycode; String city; String region; int population; double latitude; double longitude; public City (String countrycode, String city, String region, int population, double latitude, double longitude) { this.countrycode = countrycode; this.city = city; this.region = region; this.population = population; this.latitude = latitude; this.longitude = longitude; } public String toString() { return this.city + "," + this.population + "," + this.latitude + "," + this.longitude; } } ```
40,570,285
Some of the file I'm working with: <http://pastebin.com/WriQcuPs> Currently I had to make the population, latitude, and longitude strings or else I wouldn't get the desired output. I want for them to be int, double, and double in that order. ``` public class City { String countrycode; String city; String region; String population; String latitude; String longitude; public City (String countrycode, String city, String region, String population, String latitude, String longitude) { this.countrycode = countrycode; this.city = city; this.region = region; this.population = population; this.latitude = latitude; this.longitude = longitude; } public String toString() { return this.city + "," + this.population + "," + this.latitude + "," + this.longitude; } } ``` --- I suspect it has something to do with how I created the array list. Is there a way to make it so that some of the elements of the list are of a different type? I tried changing it to `ArrayList<City>` and changing the data types in the `City` class but it still gave me a ton of errors. ``` public class Reader { In input = new In("file:world_cities.txt"); private static City cityInfo; public static void main(String[] args) { // open file In input = new In("world_cities.txt"); input = new In("world_cities.txt"); try { // write output to file FileWriter fw = new FileWriter("cities_out.txt"); PrintWriter pw = new PrintWriter(fw); int line = 0; // iterate through all lines in the file while (line < 47913) { // read line String cityLine = input.readLine(); // create array list ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(","))); // add line to array list cityList.add(cityLine); // increase counter line += 1; // create instance cityInfo = new City(cityList.get(0), cityList.get(1), cityList.get(2), cityList.get(3), cityList.get(4), cityList.get(5)); System.out.println(cityInfo); // print output to file pw.println(cityInfo); } // close file pw.close(); } // what is printed when there is an error when saving to file catch (Exception e) { System.out.println("ERROR!"); } // close the file input.close(); } } ```
2016/11/13
[ "https://Stackoverflow.com/questions/40570285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7151725/" ]
If you declare the list as follows, you can put instances of any reference type into it: ``` List<Object> list = new ArrayList<>(); ``` But the downside is that when you get an element from the list, the static type of the element will be `Object`, and you will need to type cast it to the type that you need. Also note, that you can't put an `int` or a `double` into a `List`. Primitive types are not reference types, and the `List` API requires the elements to be instances of reference types. You need to use the corresponding wrapper types; i.e. `Integer` and `Double`. --- Looking at more of your code, I spotted this: ``` ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(","))); ``` If you change the list to `List<Object>` where the objects are either `Integer` or `Double`, you won't be able to build your list like that. In fact, the more I look this, the more I think that you don't need a list at all. You should be doing something like this: ``` // read line String cityLine = input.readLine(); String[] parts = cityLine.split(","); // increase counter line += 1; // create instance cityInfo = new City(parts[0], parts[1], parts[2], Integer.parseInt(parts[3]), Double.parseDouble(parts[4]), Double.parseDouble(parts[5])); ``` Notice: there is no `List` there at all!!
> > Is there a way to make it so that some of the elements of the list are > of a different type? > > > It is possible to have a `List` with elements of different type, but not if you're populating it with `String.split()` -- because that returns a `String[]`. You can convert the strings you get back fro `String.split()` into the desired types with the `valueOf` methods on the Java primitive type wrappers, for example... ``` Integer population = Integer.valueOf("1234567"); // Returns 1234567 as an Integer, which can autobox to an int if you prefer ```
40,570,285
Some of the file I'm working with: <http://pastebin.com/WriQcuPs> Currently I had to make the population, latitude, and longitude strings or else I wouldn't get the desired output. I want for them to be int, double, and double in that order. ``` public class City { String countrycode; String city; String region; String population; String latitude; String longitude; public City (String countrycode, String city, String region, String population, String latitude, String longitude) { this.countrycode = countrycode; this.city = city; this.region = region; this.population = population; this.latitude = latitude; this.longitude = longitude; } public String toString() { return this.city + "," + this.population + "," + this.latitude + "," + this.longitude; } } ``` --- I suspect it has something to do with how I created the array list. Is there a way to make it so that some of the elements of the list are of a different type? I tried changing it to `ArrayList<City>` and changing the data types in the `City` class but it still gave me a ton of errors. ``` public class Reader { In input = new In("file:world_cities.txt"); private static City cityInfo; public static void main(String[] args) { // open file In input = new In("world_cities.txt"); input = new In("world_cities.txt"); try { // write output to file FileWriter fw = new FileWriter("cities_out.txt"); PrintWriter pw = new PrintWriter(fw); int line = 0; // iterate through all lines in the file while (line < 47913) { // read line String cityLine = input.readLine(); // create array list ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(","))); // add line to array list cityList.add(cityLine); // increase counter line += 1; // create instance cityInfo = new City(cityList.get(0), cityList.get(1), cityList.get(2), cityList.get(3), cityList.get(4), cityList.get(5)); System.out.println(cityInfo); // print output to file pw.println(cityInfo); } // close file pw.close(); } // what is printed when there is an error when saving to file catch (Exception e) { System.out.println("ERROR!"); } // close the file input.close(); } } ```
2016/11/13
[ "https://Stackoverflow.com/questions/40570285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7151725/" ]
If you declare the list as follows, you can put instances of any reference type into it: ``` List<Object> list = new ArrayList<>(); ``` But the downside is that when you get an element from the list, the static type of the element will be `Object`, and you will need to type cast it to the type that you need. Also note, that you can't put an `int` or a `double` into a `List`. Primitive types are not reference types, and the `List` API requires the elements to be instances of reference types. You need to use the corresponding wrapper types; i.e. `Integer` and `Double`. --- Looking at more of your code, I spotted this: ``` ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(","))); ``` If you change the list to `List<Object>` where the objects are either `Integer` or `Double`, you won't be able to build your list like that. In fact, the more I look this, the more I think that you don't need a list at all. You should be doing something like this: ``` // read line String cityLine = input.readLine(); String[] parts = cityLine.split(","); // increase counter line += 1; // create instance cityInfo = new City(parts[0], parts[1], parts[2], Integer.parseInt(parts[3]), Double.parseDouble(parts[4]), Double.parseDouble(parts[5])); ``` Notice: there is no `List` there at all!!
Like Stephen suggested, you can use `List<Object>`, besides that, you can just pass String to City but let City itself to handle the datatype. ``` public class City { String countrycode; String city; String region; int population; double latitude; double longitude; public City (String countrycode, String city, String region, String population, String latitude, String longitude) { this.countrycode = countrycode; this.city = city; this.region = region; try{ this.population = Integer.parseInt(population); this.latitude = Double.parseDouble(latitude); this.longitude = Double.parseDouble(longitude); }catch(Exception e){ e.printStacktrace(); } } public String toString() { return this.city + "," + this.population + "," + this.latitude + "," + this.longitude; } } ``` Btw, you have initiated `In` twice. ``` In input = new In("world_cities.txt"); input = new In("world_cities.txt"); ``` Modify it to ``` In input = new In("world_cities.txt"); ```
3,225,027
$ \sin 30° \sin x \sin 10° = \sin 20° \sin ({80°-x}) \sin 40° $ I tried transformation formulas , $ 2\sin a \sin b $ one. I know the value of sin 30° but what about others? Original problem In triangle ABC, P is an interior point such that $ \angle PAB = 10°. \angle PBA = 20° PAC = 40° \angle PCA = 30° $ then what kind of triangle it is ? I solved it till I got stuck here.
2019/05/13
[ "https://math.stackexchange.com/questions/3225027", "https://math.stackexchange.com", "https://math.stackexchange.com/users/665572/" ]
Assume AB = 1. [![enter image description here](https://i.stack.imgur.com/za8tk.png)](https://i.stack.imgur.com/za8tk.png) Apply sine law to PAB to get $PB = 2 \sin 10^0$. Apply sine law to PAC to get $PB = 2 \sin 20^0$ and $PC = 4 \sin 20^0 \sin 40^0$. Apply cosine law to PBC to get $BC$ in terms of those angles. Note that $\cos 100^0 = - \sin 10^0$. $BC^2 = 4 \sin^2 10 + 16 \sin^220^0\sin^2 40^0 + 16 \sin 20^0 \sin 40^0 \sin^210^0$ Suggestion:- Convert all angles in $BC^2$to $\sin 10^0$ (or $\sin 20^0$) by compound angle formula. Hope that the result is 1.
Like [Solve $\frac{\sin(xº)\sin(80º)}{\sin(170º - xº) \sin(70º)} = \frac {\sin(60º)}{\sin (100º)}$](https://math.stackexchange.com/questions/3252593/solve-frac-sinx%C2%BA-sin80%C2%BA-sin170%C2%BA-x%C2%BA-sin70%C2%BA-frac-sin60%C2%BA/3252622#3252622) $$\dfrac{\sin(80-x)}{\sin x}=\dfrac{\sin30\sin10}{\sin20\sin40}$$ $$\implies\sin80\cot x-\cos80=\dfrac{\sin30\sin10}{\sin20\sin40}=\dfrac{4\sin10\sin80}{2\sin(3\cdot20)}$$ using <https://brainly.in/question/3475250> $$\implies\cos10\cot x=\sin10\left(1+4\cos10\tan30\right)$$ $$\implies\sqrt3\cot x=\sqrt3\tan10+4\sin10$$ Like [Simplifying $\tan100^{\circ}+4\sin100^{\circ}$](https://math.stackexchange.com/questions/1434561/simplifying-tan100-circ4-sin100-circ/1436702#1436702) set $A=360 n-3x$ in $2\sec A\sin x+\tan x=-\tan A$ $$2\sec3x\sin x+\tan x=\tan3x$$ Here $x=10\implies2\cdot\dfrac2{\sqrt3}\sin10+\tan10=\dfrac1{\sqrt3}\iff4\sin10+\sqrt3\tan10=1$ Can you take it from here?
32,995,675
I would like to know the behavior of a C program calling free on a pointer to an extern variable. The background is that I'm a developer of a verifier analyzing C code and I wonder what my verifier should do if it encounters such a situation (e.g., say why the program is undefined - if it is). To find out the behavior experimentally, I tried to run the following C program: ``` #include <stdlib.h> extern int g = 1; int main() { int *ptr = &g; free(ptr); return g; } ``` On a Debian GNU/Linux 7 system, this program crashes with an error message indicating that the pointer passed to free is invalid. On a Windows 7 system, I could run this program without any error message. Would you know of an explanation for this observation? **UPDATE** I did read the definition of `free`. My question aims at whether this definition actually rules out the possibility that such a program might reliably work on a standard-complying system (and not just by "it can do anything if the behavior is undefined"). So I would like to know if you could think of a configuration/system/whatever where this program does not expose undefined behavior. In other words: Are there conditions under which the call to `free` here would be defined properly according to the C standard?
2015/10/07
[ "https://Stackoverflow.com/questions/32995675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5418937/" ]
The C standard is unambigous about this. Quoting document [N1570](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf), the closest approximation to C11 available online at no charge, section 7.22.3.3 para 2 (the specification of `free`): > > The `free` function causes the space pointed to by `ptr` > to be deallocated, that is, made available for further allocation. If > `ptr` is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to `free` or `realloc`, the > behavior is undefined. > > > "Memory management functions" are listed at the beginning of 7.22.3: `malloc`, `calloc`, `realloc`, and `aligned_alloc`. (An implementation could add more such functions, e.g. [`posix_memalign`](http://linux.die.net/man/3/posix_memalign) -- read the notes at the bottom!) Now, "the behavior is undefined" licenses an implementation to do *anything* when the situation occurs. Crashing is common, but MSVC's runtime library is perfectly entitled to detect that a pointer is outside the "heap" and do nothing. Experiment with debugging modes: there's probably a mode where it will crash the program instead. As the author of a code-verifying tool, *you* should be maximally strict: if you can't *prove* that a pointer passed to `free` is either `NULL` or a value previously returned by a memory management function, flag that as an error. --- Addendum: the somewhat confusing "or if the space has been deallocated..." clause is intended to prohibit double deallocation: ``` char *x = malloc(42); free(x); // ok free(x); // undefined behavior ``` ... but beware of memory reuse: ``` char *x = malloc(42); uintptr_t a = (uintptr_t)x; free(x); x = malloc(42); uintptr_t b = (uintptr_t)x; observe(a == b); // un*specified* behavior - must be either true or false, // but no guarantee which free(x); // ok regardless of whether a == b ``` --- Double addendum: > > Are there conditions under which the call to `free` here would be defined properly according to the C standard? > > > No. If there were such a condition, it would have to appear *in the text of the standard* as an exception to the rule I quoted at the beginning of this answer, and there aren't any such exceptions. However, there is a subtle variation to which the answer is 'yes': > > Could there be an *implementation* of C under which the behavior of the program shown is always well-defined? > > > For instance, an implementation in which `free` is documented to do nothing, regardless of its input, would qualify and is not even a crazy idea—many programs can get away with never *calling* `free`, after all. But the behavior of the program is still undefined *according to the C standard*; it is just that the C implementation has chosen to make this particular UB scenario well-defined itself. (From the language-lawyer perspective, *every implementation extension to the language* is a case of the implementation making an UB scenario well-defined. Even nigh-ubiquitous things like `#include <unistd.h>`.)
You should only call `free` on a pointer which was previously allocated by `malloc` or `calloc` or `realloc` or `aligned_alloc`. Otherwise it doesn't matter if it is "extern'd" or not. --- **UPDATE #1** It does not always run without errors, also check what the output of `valgrind` is: ```none ==21569== Invalid free() / delete / delete[] / realloc() ==21569== at 0x4C29D2A: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==21569== by 0x4004FA: main (main.c:7) ==21569== Address 0x6008e8 is 0 bytes inside data symbol "g" ``` --- **UPDATE #2** `void free(void *ptr);` > > The `free` function causes the space pointed to by `ptr` to be deallocated, that is, made available for further allocation. If `ptr` is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to `free` or `realloc`, the behavior is undefined. > > > C11 Standard -- 7.22.3.3
32,995,675
I would like to know the behavior of a C program calling free on a pointer to an extern variable. The background is that I'm a developer of a verifier analyzing C code and I wonder what my verifier should do if it encounters such a situation (e.g., say why the program is undefined - if it is). To find out the behavior experimentally, I tried to run the following C program: ``` #include <stdlib.h> extern int g = 1; int main() { int *ptr = &g; free(ptr); return g; } ``` On a Debian GNU/Linux 7 system, this program crashes with an error message indicating that the pointer passed to free is invalid. On a Windows 7 system, I could run this program without any error message. Would you know of an explanation for this observation? **UPDATE** I did read the definition of `free`. My question aims at whether this definition actually rules out the possibility that such a program might reliably work on a standard-complying system (and not just by "it can do anything if the behavior is undefined"). So I would like to know if you could think of a configuration/system/whatever where this program does not expose undefined behavior. In other words: Are there conditions under which the call to `free` here would be defined properly according to the C standard?
2015/10/07
[ "https://Stackoverflow.com/questions/32995675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5418937/" ]
The C standard is unambigous about this. Quoting document [N1570](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf), the closest approximation to C11 available online at no charge, section 7.22.3.3 para 2 (the specification of `free`): > > The `free` function causes the space pointed to by `ptr` > to be deallocated, that is, made available for further allocation. If > `ptr` is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to `free` or `realloc`, the > behavior is undefined. > > > "Memory management functions" are listed at the beginning of 7.22.3: `malloc`, `calloc`, `realloc`, and `aligned_alloc`. (An implementation could add more such functions, e.g. [`posix_memalign`](http://linux.die.net/man/3/posix_memalign) -- read the notes at the bottom!) Now, "the behavior is undefined" licenses an implementation to do *anything* when the situation occurs. Crashing is common, but MSVC's runtime library is perfectly entitled to detect that a pointer is outside the "heap" and do nothing. Experiment with debugging modes: there's probably a mode where it will crash the program instead. As the author of a code-verifying tool, *you* should be maximally strict: if you can't *prove* that a pointer passed to `free` is either `NULL` or a value previously returned by a memory management function, flag that as an error. --- Addendum: the somewhat confusing "or if the space has been deallocated..." clause is intended to prohibit double deallocation: ``` char *x = malloc(42); free(x); // ok free(x); // undefined behavior ``` ... but beware of memory reuse: ``` char *x = malloc(42); uintptr_t a = (uintptr_t)x; free(x); x = malloc(42); uintptr_t b = (uintptr_t)x; observe(a == b); // un*specified* behavior - must be either true or false, // but no guarantee which free(x); // ok regardless of whether a == b ``` --- Double addendum: > > Are there conditions under which the call to `free` here would be defined properly according to the C standard? > > > No. If there were such a condition, it would have to appear *in the text of the standard* as an exception to the rule I quoted at the beginning of this answer, and there aren't any such exceptions. However, there is a subtle variation to which the answer is 'yes': > > Could there be an *implementation* of C under which the behavior of the program shown is always well-defined? > > > For instance, an implementation in which `free` is documented to do nothing, regardless of its input, would qualify and is not even a crazy idea—many programs can get away with never *calling* `free`, after all. But the behavior of the program is still undefined *according to the C standard*; it is just that the C implementation has chosen to make this particular UB scenario well-defined itself. (From the language-lawyer perspective, *every implementation extension to the language* is a case of the implementation making an UB scenario well-defined. Even nigh-ubiquitous things like `#include <unistd.h>`.)
When you call free on a pointer that was not previously allocated by malloc, calloc or realloc, the behavior is undefined. That means it can have different behavior in different tool chains, and also different behavior at different times in the same program. Whether it generates a crash with an error message depends on whether that specific platform's library implementation checks for the validity of the pointer. Since checking for validity can have non-zero performance cost, not all programs will do it. Also, even if the implementation does some validity checks, it might not detect all invalid pointers. One implementation may detect that a pointer to the static memory area can not be a valid heap pointer; others may treat it like a valid heap pointer and try to add the "free" memory back to the heap, corrupting the heap as well as values adjacent to your extern value in static memory in the process. The program may run fine, for a time, with the corrupted heap and static memory. This is why there are alternate, instrumented heap implementations available for C that provide additional checking.
32,995,675
I would like to know the behavior of a C program calling free on a pointer to an extern variable. The background is that I'm a developer of a verifier analyzing C code and I wonder what my verifier should do if it encounters such a situation (e.g., say why the program is undefined - if it is). To find out the behavior experimentally, I tried to run the following C program: ``` #include <stdlib.h> extern int g = 1; int main() { int *ptr = &g; free(ptr); return g; } ``` On a Debian GNU/Linux 7 system, this program crashes with an error message indicating that the pointer passed to free is invalid. On a Windows 7 system, I could run this program without any error message. Would you know of an explanation for this observation? **UPDATE** I did read the definition of `free`. My question aims at whether this definition actually rules out the possibility that such a program might reliably work on a standard-complying system (and not just by "it can do anything if the behavior is undefined"). So I would like to know if you could think of a configuration/system/whatever where this program does not expose undefined behavior. In other words: Are there conditions under which the call to `free` here would be defined properly according to the C standard?
2015/10/07
[ "https://Stackoverflow.com/questions/32995675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5418937/" ]
The C standard is unambigous about this. Quoting document [N1570](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf), the closest approximation to C11 available online at no charge, section 7.22.3.3 para 2 (the specification of `free`): > > The `free` function causes the space pointed to by `ptr` > to be deallocated, that is, made available for further allocation. If > `ptr` is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to `free` or `realloc`, the > behavior is undefined. > > > "Memory management functions" are listed at the beginning of 7.22.3: `malloc`, `calloc`, `realloc`, and `aligned_alloc`. (An implementation could add more such functions, e.g. [`posix_memalign`](http://linux.die.net/man/3/posix_memalign) -- read the notes at the bottom!) Now, "the behavior is undefined" licenses an implementation to do *anything* when the situation occurs. Crashing is common, but MSVC's runtime library is perfectly entitled to detect that a pointer is outside the "heap" and do nothing. Experiment with debugging modes: there's probably a mode where it will crash the program instead. As the author of a code-verifying tool, *you* should be maximally strict: if you can't *prove* that a pointer passed to `free` is either `NULL` or a value previously returned by a memory management function, flag that as an error. --- Addendum: the somewhat confusing "or if the space has been deallocated..." clause is intended to prohibit double deallocation: ``` char *x = malloc(42); free(x); // ok free(x); // undefined behavior ``` ... but beware of memory reuse: ``` char *x = malloc(42); uintptr_t a = (uintptr_t)x; free(x); x = malloc(42); uintptr_t b = (uintptr_t)x; observe(a == b); // un*specified* behavior - must be either true or false, // but no guarantee which free(x); // ok regardless of whether a == b ``` --- Double addendum: > > Are there conditions under which the call to `free` here would be defined properly according to the C standard? > > > No. If there were such a condition, it would have to appear *in the text of the standard* as an exception to the rule I quoted at the beginning of this answer, and there aren't any such exceptions. However, there is a subtle variation to which the answer is 'yes': > > Could there be an *implementation* of C under which the behavior of the program shown is always well-defined? > > > For instance, an implementation in which `free` is documented to do nothing, regardless of its input, would qualify and is not even a crazy idea—many programs can get away with never *calling* `free`, after all. But the behavior of the program is still undefined *according to the C standard*; it is just that the C implementation has chosen to make this particular UB scenario well-defined itself. (From the language-lawyer perspective, *every implementation extension to the language* is a case of the implementation making an UB scenario well-defined. Even nigh-ubiquitous things like `#include <unistd.h>`.)
[Chapter and verse](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) > > **7.22.3.3 The `free` function** > > ... > > 2 The `free` function causes the space pointed to by `ptr` to be deallocated, that is, made > available for further allocation. If `ptr` is a null pointer, no action occurs. Otherwise, **if > the argument does not match a pointer earlier returned by a memory management > function**, or if the space has been deallocated by a call to `free` or `realloc`, **the > behavior is undefined.** > Emphasis mine. Since the behavior is undefined, *any* action taken by the compiler or the run time environment is acceptable. It may reject the code with a diagnostic, it may translate the code with a diagnostic, it may translate the code without a diagnostic, your code may crash at runtime, your code may appear to run without any issues, your code may invoke Rogue, etc.
27,424,831
After last firefox-update some of css3-code has been broken... [Example](http://jsfiddle.net/944tL115/4/) (jsfiddle). * In chromium: ![normal, chome](https://i.stack.imgur.com/8jREh.png) * In firefox 34: ![firefox 34, bad](https://i.stack.imgur.com/CBIwF.png) Is it bug? Or normal working? What do i need to change to fix it? Why `#flex` don't resize properly? HTML: ``` <div id="outer"> <div id="flex"> <label>123</label> <input type="text" value="some text" /> </div> </div> ``` CSS: ``` #outer { display: flex; } #flex { display: flex; border: 1px solid green; outline: 1px solid red; } label { flex: 0 0 80px; } ```
2014/12/11
[ "https://Stackoverflow.com/questions/27424831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/892741/" ]
What you could do is, subtract `80px` from `100%` and set that a `width` for `input`. Additionally, add `box-sizing: border-box` to prevent overflow. ```css form { display: flex; } #flex { display: flex; border: 1px solid green; outline: 1px solid red; } label { display: flex; flex: 0 0 80px; } input { width: calc(100% - 80px); box-sizing: border-box; } ``` ```html <form> <div id="flex"> <label>123</label> <input type="text" value="some text" /> </div> </form> ```
`Display: flex;` **only** needs to be on the container that needs to be flexible, not the inner elements. Here's the updated CSS, if you need a specific width, you can set that on `form {}`. CSS ``` form {} #flex { display: flex; border: 1px solid green; outline: 1px solid red; } #flex > * { flex: 1; } label {} input {} ```
27,424,831
After last firefox-update some of css3-code has been broken... [Example](http://jsfiddle.net/944tL115/4/) (jsfiddle). * In chromium: ![normal, chome](https://i.stack.imgur.com/8jREh.png) * In firefox 34: ![firefox 34, bad](https://i.stack.imgur.com/CBIwF.png) Is it bug? Or normal working? What do i need to change to fix it? Why `#flex` don't resize properly? HTML: ``` <div id="outer"> <div id="flex"> <label>123</label> <input type="text" value="some text" /> </div> </div> ``` CSS: ``` #outer { display: flex; } #flex { display: flex; border: 1px solid green; outline: 1px solid red; } label { flex: 0 0 80px; } ```
2014/12/11
[ "https://Stackoverflow.com/questions/27424831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/892741/" ]
There is a bug in Firefox 34. One of the elements is not playing nicely as a flex child, and the input seems to be too wide. This extra width is not taken into account by the flex containers green border. --- This can be confirmed as a bug because in Firefox 33.1 (and Chrome / IE) there is no problem with your example: Your Example Firefox 33.1 ![Working Fine](https://i.stack.imgur.com/8Mx0C.png) Your Example Firefox 34.0.5 — The input width is miscalculated by the flex container and the input itself cannot be given a smaller width. ![Not working](https://i.stack.imgur.com/IWnSZ.png) --- As a workaround, we can set a width on the label; this width is recognised by the container and the bug is prevented in Firefox 34. In order to be used only in Firefox, we can set the width using the `-moz-` prefix with calc: ``` label { width: -moz-calc(80px); } ``` (Obviously previous versions of Firefox will also recognise this width) Bug Workaround Example ---------------------- ### Using inline-flex From your example, it looks like you want to use `inline-flex` in order to contain the width of the form to the width of its children. I have used this and removed the extra div that is no longer needed. There is a big difference in input widths per browser (this is consistent with the example in your question). ### Firefox 33 ![Old Firefox Screenshot](https://i.stack.imgur.com/DeTmi.png) ### Firefox 34 ![Firefox Example](https://i.stack.imgur.com/WqGnN.png) ### Chrome ![Chrome Screenshot](https://i.stack.imgur.com/pUqFi.png) ### IE11 ![IE Example](https://i.stack.imgur.com/6ZBvo.png) ```css form { display: inline-flex; border: solid 1px green; outline: 1px solid red; } label { flex: 0 0 80px; width: -moz-calc(80px); } ``` ```html <form> <label>123</label> <input type="text" value="some text" /> </form> ```
What you could do is, subtract `80px` from `100%` and set that a `width` for `input`. Additionally, add `box-sizing: border-box` to prevent overflow. ```css form { display: flex; } #flex { display: flex; border: 1px solid green; outline: 1px solid red; } label { display: flex; flex: 0 0 80px; } input { width: calc(100% - 80px); box-sizing: border-box; } ``` ```html <form> <div id="flex"> <label>123</label> <input type="text" value="some text" /> </div> </form> ```
27,424,831
After last firefox-update some of css3-code has been broken... [Example](http://jsfiddle.net/944tL115/4/) (jsfiddle). * In chromium: ![normal, chome](https://i.stack.imgur.com/8jREh.png) * In firefox 34: ![firefox 34, bad](https://i.stack.imgur.com/CBIwF.png) Is it bug? Or normal working? What do i need to change to fix it? Why `#flex` don't resize properly? HTML: ``` <div id="outer"> <div id="flex"> <label>123</label> <input type="text" value="some text" /> </div> </div> ``` CSS: ``` #outer { display: flex; } #flex { display: flex; border: 1px solid green; outline: 1px solid red; } label { flex: 0 0 80px; } ```
2014/12/11
[ "https://Stackoverflow.com/questions/27424831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/892741/" ]
Fix: ``` input { min-width: 1px; } ``` For vertical direction - `min-height`;
What you could do is, subtract `80px` from `100%` and set that a `width` for `input`. Additionally, add `box-sizing: border-box` to prevent overflow. ```css form { display: flex; } #flex { display: flex; border: 1px solid green; outline: 1px solid red; } label { display: flex; flex: 0 0 80px; } input { width: calc(100% - 80px); box-sizing: border-box; } ``` ```html <form> <div id="flex"> <label>123</label> <input type="text" value="some text" /> </div> </form> ```
27,424,831
After last firefox-update some of css3-code has been broken... [Example](http://jsfiddle.net/944tL115/4/) (jsfiddle). * In chromium: ![normal, chome](https://i.stack.imgur.com/8jREh.png) * In firefox 34: ![firefox 34, bad](https://i.stack.imgur.com/CBIwF.png) Is it bug? Or normal working? What do i need to change to fix it? Why `#flex` don't resize properly? HTML: ``` <div id="outer"> <div id="flex"> <label>123</label> <input type="text" value="some text" /> </div> </div> ``` CSS: ``` #outer { display: flex; } #flex { display: flex; border: 1px solid green; outline: 1px solid red; } label { flex: 0 0 80px; } ```
2014/12/11
[ "https://Stackoverflow.com/questions/27424831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/892741/" ]
variant with ``` min-width: 0 ``` also works
What you could do is, subtract `80px` from `100%` and set that a `width` for `input`. Additionally, add `box-sizing: border-box` to prevent overflow. ```css form { display: flex; } #flex { display: flex; border: 1px solid green; outline: 1px solid red; } label { display: flex; flex: 0 0 80px; } input { width: calc(100% - 80px); box-sizing: border-box; } ``` ```html <form> <div id="flex"> <label>123</label> <input type="text" value="some text" /> </div> </form> ```
27,424,831
After last firefox-update some of css3-code has been broken... [Example](http://jsfiddle.net/944tL115/4/) (jsfiddle). * In chromium: ![normal, chome](https://i.stack.imgur.com/8jREh.png) * In firefox 34: ![firefox 34, bad](https://i.stack.imgur.com/CBIwF.png) Is it bug? Or normal working? What do i need to change to fix it? Why `#flex` don't resize properly? HTML: ``` <div id="outer"> <div id="flex"> <label>123</label> <input type="text" value="some text" /> </div> </div> ``` CSS: ``` #outer { display: flex; } #flex { display: flex; border: 1px solid green; outline: 1px solid red; } label { flex: 0 0 80px; } ```
2014/12/11
[ "https://Stackoverflow.com/questions/27424831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/892741/" ]
There is a bug in Firefox 34. One of the elements is not playing nicely as a flex child, and the input seems to be too wide. This extra width is not taken into account by the flex containers green border. --- This can be confirmed as a bug because in Firefox 33.1 (and Chrome / IE) there is no problem with your example: Your Example Firefox 33.1 ![Working Fine](https://i.stack.imgur.com/8Mx0C.png) Your Example Firefox 34.0.5 — The input width is miscalculated by the flex container and the input itself cannot be given a smaller width. ![Not working](https://i.stack.imgur.com/IWnSZ.png) --- As a workaround, we can set a width on the label; this width is recognised by the container and the bug is prevented in Firefox 34. In order to be used only in Firefox, we can set the width using the `-moz-` prefix with calc: ``` label { width: -moz-calc(80px); } ``` (Obviously previous versions of Firefox will also recognise this width) Bug Workaround Example ---------------------- ### Using inline-flex From your example, it looks like you want to use `inline-flex` in order to contain the width of the form to the width of its children. I have used this and removed the extra div that is no longer needed. There is a big difference in input widths per browser (this is consistent with the example in your question). ### Firefox 33 ![Old Firefox Screenshot](https://i.stack.imgur.com/DeTmi.png) ### Firefox 34 ![Firefox Example](https://i.stack.imgur.com/WqGnN.png) ### Chrome ![Chrome Screenshot](https://i.stack.imgur.com/pUqFi.png) ### IE11 ![IE Example](https://i.stack.imgur.com/6ZBvo.png) ```css form { display: inline-flex; border: solid 1px green; outline: 1px solid red; } label { flex: 0 0 80px; width: -moz-calc(80px); } ``` ```html <form> <label>123</label> <input type="text" value="some text" /> </form> ```
`Display: flex;` **only** needs to be on the container that needs to be flexible, not the inner elements. Here's the updated CSS, if you need a specific width, you can set that on `form {}`. CSS ``` form {} #flex { display: flex; border: 1px solid green; outline: 1px solid red; } #flex > * { flex: 1; } label {} input {} ```
27,424,831
After last firefox-update some of css3-code has been broken... [Example](http://jsfiddle.net/944tL115/4/) (jsfiddle). * In chromium: ![normal, chome](https://i.stack.imgur.com/8jREh.png) * In firefox 34: ![firefox 34, bad](https://i.stack.imgur.com/CBIwF.png) Is it bug? Or normal working? What do i need to change to fix it? Why `#flex` don't resize properly? HTML: ``` <div id="outer"> <div id="flex"> <label>123</label> <input type="text" value="some text" /> </div> </div> ``` CSS: ``` #outer { display: flex; } #flex { display: flex; border: 1px solid green; outline: 1px solid red; } label { flex: 0 0 80px; } ```
2014/12/11
[ "https://Stackoverflow.com/questions/27424831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/892741/" ]
Fix: ``` input { min-width: 1px; } ``` For vertical direction - `min-height`;
`Display: flex;` **only** needs to be on the container that needs to be flexible, not the inner elements. Here's the updated CSS, if you need a specific width, you can set that on `form {}`. CSS ``` form {} #flex { display: flex; border: 1px solid green; outline: 1px solid red; } #flex > * { flex: 1; } label {} input {} ```
27,424,831
After last firefox-update some of css3-code has been broken... [Example](http://jsfiddle.net/944tL115/4/) (jsfiddle). * In chromium: ![normal, chome](https://i.stack.imgur.com/8jREh.png) * In firefox 34: ![firefox 34, bad](https://i.stack.imgur.com/CBIwF.png) Is it bug? Or normal working? What do i need to change to fix it? Why `#flex` don't resize properly? HTML: ``` <div id="outer"> <div id="flex"> <label>123</label> <input type="text" value="some text" /> </div> </div> ``` CSS: ``` #outer { display: flex; } #flex { display: flex; border: 1px solid green; outline: 1px solid red; } label { flex: 0 0 80px; } ```
2014/12/11
[ "https://Stackoverflow.com/questions/27424831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/892741/" ]
variant with ``` min-width: 0 ``` also works
`Display: flex;` **only** needs to be on the container that needs to be flexible, not the inner elements. Here's the updated CSS, if you need a specific width, you can set that on `form {}`. CSS ``` form {} #flex { display: flex; border: 1px solid green; outline: 1px solid red; } #flex > * { flex: 1; } label {} input {} ```
27,424,831
After last firefox-update some of css3-code has been broken... [Example](http://jsfiddle.net/944tL115/4/) (jsfiddle). * In chromium: ![normal, chome](https://i.stack.imgur.com/8jREh.png) * In firefox 34: ![firefox 34, bad](https://i.stack.imgur.com/CBIwF.png) Is it bug? Or normal working? What do i need to change to fix it? Why `#flex` don't resize properly? HTML: ``` <div id="outer"> <div id="flex"> <label>123</label> <input type="text" value="some text" /> </div> </div> ``` CSS: ``` #outer { display: flex; } #flex { display: flex; border: 1px solid green; outline: 1px solid red; } label { flex: 0 0 80px; } ```
2014/12/11
[ "https://Stackoverflow.com/questions/27424831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/892741/" ]
Fix: ``` input { min-width: 1px; } ``` For vertical direction - `min-height`;
There is a bug in Firefox 34. One of the elements is not playing nicely as a flex child, and the input seems to be too wide. This extra width is not taken into account by the flex containers green border. --- This can be confirmed as a bug because in Firefox 33.1 (and Chrome / IE) there is no problem with your example: Your Example Firefox 33.1 ![Working Fine](https://i.stack.imgur.com/8Mx0C.png) Your Example Firefox 34.0.5 — The input width is miscalculated by the flex container and the input itself cannot be given a smaller width. ![Not working](https://i.stack.imgur.com/IWnSZ.png) --- As a workaround, we can set a width on the label; this width is recognised by the container and the bug is prevented in Firefox 34. In order to be used only in Firefox, we can set the width using the `-moz-` prefix with calc: ``` label { width: -moz-calc(80px); } ``` (Obviously previous versions of Firefox will also recognise this width) Bug Workaround Example ---------------------- ### Using inline-flex From your example, it looks like you want to use `inline-flex` in order to contain the width of the form to the width of its children. I have used this and removed the extra div that is no longer needed. There is a big difference in input widths per browser (this is consistent with the example in your question). ### Firefox 33 ![Old Firefox Screenshot](https://i.stack.imgur.com/DeTmi.png) ### Firefox 34 ![Firefox Example](https://i.stack.imgur.com/WqGnN.png) ### Chrome ![Chrome Screenshot](https://i.stack.imgur.com/pUqFi.png) ### IE11 ![IE Example](https://i.stack.imgur.com/6ZBvo.png) ```css form { display: inline-flex; border: solid 1px green; outline: 1px solid red; } label { flex: 0 0 80px; width: -moz-calc(80px); } ``` ```html <form> <label>123</label> <input type="text" value="some text" /> </form> ```
27,424,831
After last firefox-update some of css3-code has been broken... [Example](http://jsfiddle.net/944tL115/4/) (jsfiddle). * In chromium: ![normal, chome](https://i.stack.imgur.com/8jREh.png) * In firefox 34: ![firefox 34, bad](https://i.stack.imgur.com/CBIwF.png) Is it bug? Or normal working? What do i need to change to fix it? Why `#flex` don't resize properly? HTML: ``` <div id="outer"> <div id="flex"> <label>123</label> <input type="text" value="some text" /> </div> </div> ``` CSS: ``` #outer { display: flex; } #flex { display: flex; border: 1px solid green; outline: 1px solid red; } label { flex: 0 0 80px; } ```
2014/12/11
[ "https://Stackoverflow.com/questions/27424831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/892741/" ]
Fix: ``` input { min-width: 1px; } ``` For vertical direction - `min-height`;
variant with ``` min-width: 0 ``` also works
92,346
I'm trying to print a set of beamer slides with multiple slides per page (4-up or 6-up). When I select 4 pages or 6 pages per sheet in the Okular print dialog, the pages print quite small (perhaps even tiny -- about 1.75" by 1.25") and leave significant white-space on the page. I can get around this behavior by using the pdfnup utility (in the pdfjam package); which will correctly generate a 4- or 6-up pdf file but it's annoying to generate a second pdf file when I should be able to accomplish this task from the print dialog. Details: Ubuntu 9.10 (Karmic), 64-bit, Color Postscript printer.
2010/01/06
[ "https://superuser.com/questions/92346", "https://superuser.com", "https://superuser.com/users/-1/" ]
As Tomas Markauskas said, the .app is a bundle. Why did you try to move a .app file to /usr/bin? I'm going to guess that what you really want to know is "how do I open a file using Foo.app when I'm at the command line?" If I'm right, the answer isn't to move the .app file to /usr/bin. The right answer is to use the `open` command: ``` $ open -a Foo some_file ``` Using `open` without the `-a` will open the file with its default application -- just as if you double-clicked on `some_file` in the Finder.
.app is actually not a file, but a folder (or Application bundle) with many different files in it. It also contains the executable files that you actually run.
92,346
I'm trying to print a set of beamer slides with multiple slides per page (4-up or 6-up). When I select 4 pages or 6 pages per sheet in the Okular print dialog, the pages print quite small (perhaps even tiny -- about 1.75" by 1.25") and leave significant white-space on the page. I can get around this behavior by using the pdfnup utility (in the pdfjam package); which will correctly generate a 4- or 6-up pdf file but it's annoying to generate a second pdf file when I should be able to accomplish this task from the print dialog. Details: Ubuntu 9.10 (Karmic), 64-bit, Color Postscript printer.
2010/01/06
[ "https://superuser.com/questions/92346", "https://superuser.com", "https://superuser.com/users/-1/" ]
.app is actually not a file, but a folder (or Application bundle) with many different files in it. It also contains the executable files that you actually run.
You can also run the app directly with the `open` command: ``` open /Applications/Safari.app/ ```
92,346
I'm trying to print a set of beamer slides with multiple slides per page (4-up or 6-up). When I select 4 pages or 6 pages per sheet in the Okular print dialog, the pages print quite small (perhaps even tiny -- about 1.75" by 1.25") and leave significant white-space on the page. I can get around this behavior by using the pdfnup utility (in the pdfjam package); which will correctly generate a 4- or 6-up pdf file but it's annoying to generate a second pdf file when I should be able to accomplish this task from the print dialog. Details: Ubuntu 9.10 (Karmic), 64-bit, Color Postscript printer.
2010/01/06
[ "https://superuser.com/questions/92346", "https://superuser.com", "https://superuser.com/users/-1/" ]
Wikipedia has a good article on [Application Bundle](http://en.wikipedia.org/wiki/Application_Bundle)s. In short, a `.app` is not a file: it's a directory tree with a specific structure. The actual binary that runs (ie, the equivalent of the binary you'd find in `/usr/bin`) is `PackageName.app/Contents/MacOS/PackageName`. However, you (generally) can't just copy that file to '/usr/bin' and run it, because it will expect to have lots of other files it needs inside the .app folder as well - for instance, many applications have the translation files that allow them to present the UI in different languages under `PackageName.app/Contents/Resources/de.lproj` (where `de` happens to mean `german`). In some cases, the `.app` bundle may contain executables you can execute directly - for instance, I often use the `ebook-convert` binary from the `calibre.app` bundle, by running `/Applications/calibre.app/Contents/Resources/loaders/ebook-convert`. In this case, ebook-convert happens to be a self-contained python script and is perfectly happy being called this way - not all executables will be as happy. You can usually start a `.app` by calling the main binary directly - eg, `/Applications/Safari.app/Contents/MacOS/Safari` will launch Safari. However, this is a lot of typing - `open /Applications/Safari.app` is a shortcut that does the same thing. `man open` has many more examples of using `open` to act as though the user had double-clicked on an icon in finder.
.app is actually not a file, but a folder (or Application bundle) with many different files in it. It also contains the executable files that you actually run.
92,346
I'm trying to print a set of beamer slides with multiple slides per page (4-up or 6-up). When I select 4 pages or 6 pages per sheet in the Okular print dialog, the pages print quite small (perhaps even tiny -- about 1.75" by 1.25") and leave significant white-space on the page. I can get around this behavior by using the pdfnup utility (in the pdfjam package); which will correctly generate a 4- or 6-up pdf file but it's annoying to generate a second pdf file when I should be able to accomplish this task from the print dialog. Details: Ubuntu 9.10 (Karmic), 64-bit, Color Postscript printer.
2010/01/06
[ "https://superuser.com/questions/92346", "https://superuser.com", "https://superuser.com/users/-1/" ]
As Tomas Markauskas said, the .app is a bundle. Why did you try to move a .app file to /usr/bin? I'm going to guess that what you really want to know is "how do I open a file using Foo.app when I'm at the command line?" If I'm right, the answer isn't to move the .app file to /usr/bin. The right answer is to use the `open` command: ``` $ open -a Foo some_file ``` Using `open` without the `-a` will open the file with its default application -- just as if you double-clicked on `some_file` in the Finder.
You can also run the app directly with the `open` command: ``` open /Applications/Safari.app/ ```
92,346
I'm trying to print a set of beamer slides with multiple slides per page (4-up or 6-up). When I select 4 pages or 6 pages per sheet in the Okular print dialog, the pages print quite small (perhaps even tiny -- about 1.75" by 1.25") and leave significant white-space on the page. I can get around this behavior by using the pdfnup utility (in the pdfjam package); which will correctly generate a 4- or 6-up pdf file but it's annoying to generate a second pdf file when I should be able to accomplish this task from the print dialog. Details: Ubuntu 9.10 (Karmic), 64-bit, Color Postscript printer.
2010/01/06
[ "https://superuser.com/questions/92346", "https://superuser.com", "https://superuser.com/users/-1/" ]
Wikipedia has a good article on [Application Bundle](http://en.wikipedia.org/wiki/Application_Bundle)s. In short, a `.app` is not a file: it's a directory tree with a specific structure. The actual binary that runs (ie, the equivalent of the binary you'd find in `/usr/bin`) is `PackageName.app/Contents/MacOS/PackageName`. However, you (generally) can't just copy that file to '/usr/bin' and run it, because it will expect to have lots of other files it needs inside the .app folder as well - for instance, many applications have the translation files that allow them to present the UI in different languages under `PackageName.app/Contents/Resources/de.lproj` (where `de` happens to mean `german`). In some cases, the `.app` bundle may contain executables you can execute directly - for instance, I often use the `ebook-convert` binary from the `calibre.app` bundle, by running `/Applications/calibre.app/Contents/Resources/loaders/ebook-convert`. In this case, ebook-convert happens to be a self-contained python script and is perfectly happy being called this way - not all executables will be as happy. You can usually start a `.app` by calling the main binary directly - eg, `/Applications/Safari.app/Contents/MacOS/Safari` will launch Safari. However, this is a lot of typing - `open /Applications/Safari.app` is a shortcut that does the same thing. `man open` has many more examples of using `open` to act as though the user had double-clicked on an icon in finder.
As Tomas Markauskas said, the .app is a bundle. Why did you try to move a .app file to /usr/bin? I'm going to guess that what you really want to know is "how do I open a file using Foo.app when I'm at the command line?" If I'm right, the answer isn't to move the .app file to /usr/bin. The right answer is to use the `open` command: ``` $ open -a Foo some_file ``` Using `open` without the `-a` will open the file with its default application -- just as if you double-clicked on `some_file` in the Finder.
92,346
I'm trying to print a set of beamer slides with multiple slides per page (4-up or 6-up). When I select 4 pages or 6 pages per sheet in the Okular print dialog, the pages print quite small (perhaps even tiny -- about 1.75" by 1.25") and leave significant white-space on the page. I can get around this behavior by using the pdfnup utility (in the pdfjam package); which will correctly generate a 4- or 6-up pdf file but it's annoying to generate a second pdf file when I should be able to accomplish this task from the print dialog. Details: Ubuntu 9.10 (Karmic), 64-bit, Color Postscript printer.
2010/01/06
[ "https://superuser.com/questions/92346", "https://superuser.com", "https://superuser.com/users/-1/" ]
Wikipedia has a good article on [Application Bundle](http://en.wikipedia.org/wiki/Application_Bundle)s. In short, a `.app` is not a file: it's a directory tree with a specific structure. The actual binary that runs (ie, the equivalent of the binary you'd find in `/usr/bin`) is `PackageName.app/Contents/MacOS/PackageName`. However, you (generally) can't just copy that file to '/usr/bin' and run it, because it will expect to have lots of other files it needs inside the .app folder as well - for instance, many applications have the translation files that allow them to present the UI in different languages under `PackageName.app/Contents/Resources/de.lproj` (where `de` happens to mean `german`). In some cases, the `.app` bundle may contain executables you can execute directly - for instance, I often use the `ebook-convert` binary from the `calibre.app` bundle, by running `/Applications/calibre.app/Contents/Resources/loaders/ebook-convert`. In this case, ebook-convert happens to be a self-contained python script and is perfectly happy being called this way - not all executables will be as happy. You can usually start a `.app` by calling the main binary directly - eg, `/Applications/Safari.app/Contents/MacOS/Safari` will launch Safari. However, this is a lot of typing - `open /Applications/Safari.app` is a shortcut that does the same thing. `man open` has many more examples of using `open` to act as though the user had double-clicked on an icon in finder.
You can also run the app directly with the `open` command: ``` open /Applications/Safari.app/ ```
2,900,340
I am introducing auto-rotation to my app and I'm having an issue with a memory warning. Whatever orientation I start my app in, as long as the device remains in that orientation, I get no memory warnings. However, the first time I rotate the device the following warning is placed on the console: Safari got memory level warning, killing all documents except active. When this happens all view controllers, other than the one be viewed, are unloaded - this produces unexpected behaviors when navigating back to view controllers that should normally already be on the stack. The app never crashes and this warning occurs once upon the first rotation, after that it never happens (until I stop/start the app again). Also, this only happens on the device - no memory warning when running in simulator. Has anyone seen this behavior? In any case, does anyone have any suggestions on what I might try in order to remove the memory warning. Thanks in advance.
2010/05/24
[ "https://Stackoverflow.com/questions/2900340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/334440/" ]
You can't assume that memory warnings will never happen; you have to handle them gracefully. Suggestions: * Check for memory leaks with Leaks (note that it doesn't catch all leaks). * Fix your view controllers to handle a view reload. Specifically (unless you override -(void)loadView), it'll call -(void)viewDidUnload on a memory warning and -(void)viewDidLoad when it becomes visible again. You might fix this by saving state in the view controller and restoring it to the views in -(void)viewDidLoad. * If you can't be bothered handling the memory warning, implement -(void)didReceiveMemoryWarning and do not super-call (i.e. comment out `[super didReceiveMemoryWarning]`). This is lazy, and might cause a crash if your app ends up using too much memory (background apps like Safari and Phone will be killed first). You can test memory warning behaviour with the "simulate memory warning" option in the simulator.
Memory warnings are part of a normal iOS behavior, due to its limited memory, especially now that multi-tasking is supported. UIKit doesn’t only allow navigation back from a view controller, but also allows navigation to other view controllers from existing ones. In such a case, a new UIViewController will be allocated, and then loaded into view. The old view controller will go off-screen and becomes inactive, but still owns many objects – some in custom properties and variables and others in the view property/hierarchy. And so does the new visible view controller, in regard to its view objects. Due to the limited amount of memory of mobile devices, owning the two sets of objects – one in the off-screen view controller and another in the on-screen view controller – might be too much to handle. If UIKit deems it necessary, it can reclaim some of the off-screen view controller’s memory, which is not shown anyway; UIKit knows which view controller is on-screen and which is off-screen, as after all, it is the one managing them (when you call presentModalViewController:animated: or dismissModalViewControllerAnimated:). So, every time it feels pressured, UIKit generates a memory warning, which unloads and releases your off-screen view from the view hierarchy, then call your custom viewDidUnload method for you to do the same for your properties and variables. UIKit releases self.view automatically, allowing us then to manually release our variables and properties in our viewDidUnload code. It does so for all off-screen view controllers. When the system is running out of memory, it fires a didReceiveMemoryWarning. Off-screen views will be reclaimed and released upon memory warning, but your on-screen view will not get released – it is visible and needed. In case your class owns a lot of memory, such as caches, images, or the like, didReceiveMemoryWarning is where you should purge them, even if they are on-screen; otherwise, your app might be terminated for glutting system resources. You need to override this method to make sure you clean up your memory; just remember you call [super didReceiveMemoryWarning];. An even more elaborate explanation is available here: <http://myok12.wordpress.com/2010/11/30/custom-uiviewcontrollers-their-views-and-their-memory-management/>
21,843,647
In the following string, I want to match only 10.00 ``` Test(+$15.00)(dsfa) (+$10.00) ``` Right now I have: ``` \([\+|\-]\$(?:[0-9\.]+?)\)$ ``` but it captures (+$10.00), I'd like to have only the interior of the capture group. Edit: I'm using JS
2014/02/18
[ "https://Stackoverflow.com/questions/21843647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/618450/" ]
The problem is that you haven't defined a capturing group in your pattern, you only have literal parenthesis that is totally different. This will give you the result in the capturing group 1 *that is defined with simple parenthesis `(...)`*: ``` \([+-]\$([0-9.]+)\)$ ``` *(Note that several characters don't need to be escaped, in particular all special characters are seen as literals inside a character class.)* In the precedent pattern, I use a capturing group to extract what i want from the whole result. It is possible to obtain only what you want as whole result by using lookarounds (with regex engines that supports lookarounds): ``` (?<=\([+-]\$)[0-9.]+(?=\)$) ```
It's easy in JavaScript when using a capturing group. The return value of your test function will be an array where element 0 is the full capture and element 1 is your target result. ``` str = "Test(+$15.00)(dsfa) (+$10.00)" matches = str.match(/(?:[+-]\$)(\d+\.\d\d)(?:\))$/) result = matches[1] ``` `matches` here will be `["+$10.00)", "10.00"]` and `result` will be `"10.00"`.
73,842,262
I'm using C and I want to get the String "ABCABCABCABCABCABC" in the output screen through multithreading. One thread displays the 'A' character, the second one displays the 'B' and the third one displays the 'C'. If I compile the following code: ``` #include <pthread.h> #include <stdlib.h> #include <stdio.h> #define cantidad_impresion_letra 6 pthread_mutex_t semaforo = PTHREAD_MUTEX_INITIALIZER; void *escribirA(void *unused){ int i; for(i=0;i<cantidad_impresion_letra;i++){ pthread_mutex_lock(&semaforo); printf("A"); pthread_mutex_unlock(&semaforo); } } void *escribirB(void *unused){ int i; for(i=0;i<cantidad_impresion_letra;i++){ pthread_mutex_lock(&semaforo); printf("B"); pthread_mutex_unlock(&semaforo); } } void *escribirC(void *unused){ int i; for(i=0;i<cantidad_impresion_letra;i++){ pthread_mutex_lock(&semaforo); printf("C"); pthread_mutex_unlock(&semaforo); } } int main(){ pthread_t thread1, thread2, thread3; pthread_create(&thread1,NULL,escribirA,NULL); pthread_create(&thread2,NULL,escribirB,NULL); pthread_create(&thread3,NULL,escribirC,NULL); pthread_join(thread1, NULL); pthread_join(thread2, NULL); pthread_join(thread3, NULL); return(0); } ``` On Windows through Dev-C++, the console throws me: `ABACBACBACBACBACBC` but if I compile **the same** code in Linux, I get `CCCCCCBBBBBBAAAAAA`. Can someone explain me this please?
2022/09/25
[ "https://Stackoverflow.com/questions/73842262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20080932/" ]
> > Can someone explain me this please? > > > The different output in linux has to do with the used scheduler. [man sched](https://man7.org/linux/man-pages/man7/sched.7.html) > > Since Linux 2.6.23, the default scheduler is CFS, the "Completely Fair Scheduler". > > > [Completely Fair Scheduler](https://en.wikipedia.org/wiki/Completely_Fair_Scheduler): > > Each per-CPU run-queue of type cfs\_rq **sorts** sched\_entity structures in a **time-ordered** fashion into a red-black tree (or 'rbtree' in Linux lingo), where the leftmost node is occupied by the entity that has received the **least** slice of **execution time** (which is saved in the vruntime field of the entity). The nodes are indexed by processor "execution time" in nanoseconds. > > > **What does that mean:** Each thread runs so fast, that the scheduler doesn't deem it necessary to perform a context switch. There are only 6 iteration steps and an output into a buffered stream (no newline, therefore no output to the terminal until a flush occurs). Do the test, increase the iteration steps, add more characters to the output and add a newline character (`\n`). The sequence will start to change. On my system, the sequence started to change with 200 iteration steps and 3 characters (plus `\n`). --- > > I'm using C and I want to get the String "ABCABCABCABCABCABC" > > > **1. Sequential output is best achieved through sequential execution.** * use only one thread (single threaded) **2. Notify/Wait** * each thread performs an iteration, signals the other thread and then waits for a signal to arrive in order to continue on the next cycle **3. Barrier** ``` //introduce NUM_THREAD lists char dataA[cantidad_impresion_letra]; char dataB[cantidad_impresion_letra]; char dataC[cantidad_impresion_letra]; //let the thread do their work without any disturbance void *escribirA(void *unused){ //unused could be used to pass the lists int i; for(i=0;i<cantidad_impresion_letra;i++){ //pthread_mutex_lock(&semaforo); //not needed //instead of printf("A"); dataA[i] = 'A'; //pthread_mutex_unlock(&semaforo); //not needed } } //same for escribirB but write into dataB //same for escribirC but write into dataC int main() { //... //after joining the threads //collective output in any desired order for (int i=0; i < cantidad_impresion_letra; ++i) { printf("%c", dataA[i]); printf("%c", dataB[i]); printf("%c", dataC[i]); } return 0; } ``` The advantages: * no lock/unlock (if the global lists are not accessed otherwise) * no waiting and broadcasting * guaranteed synchronized output * let the OS decide when it is best to yield a thread (scheduler) Disadvantage: * more memory intensive (depends on the number of threads and the iteration steps)
You can store the order of execution in a global volatile variable named for example *order* which is set with the values 0, 1 and 2 circularly (thanks to an incrementation and a modulo operation). This variable is checked with a condition variable: ```c #include <pthread.h> #include <stdlib.h> #include <stdio.h> int order = 0; #define cantidad_impresion_letra 6 pthread_mutex_t semaforo = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void *escribirA(void *unused){ int i; for(i=0;i<cantidad_impresion_letra;i++){ pthread_mutex_lock(&semaforo); while (order != 0) { // Wake up another thread before going to sleep pthread_cond_signal(&cond); pthread_cond_wait(&cond, &semaforo); } printf("A"); order = (order + 1) % 3; fflush(stdout); // Wake up another thread pthread_cond_signal(&cond); pthread_mutex_unlock(&semaforo); } } void *escribirB(void *unused){ int i; for(i=0;i<cantidad_impresion_letra;i++){ pthread_mutex_lock(&semaforo); while (order != 1) { // Wake up another thread before going to sleep pthread_cond_signal(&cond); pthread_cond_wait(&cond, &semaforo); } printf("B"); order = (order + 1) % 3; fflush(stdout); // Wake up another thread pthread_cond_signal(&cond); pthread_mutex_unlock(&semaforo); } } void *escribirC(void *unused){ int i; for(i=0;i<cantidad_impresion_letra;i++){ pthread_mutex_lock(&semaforo); while (order != 2) { // Wake up another thread before going to sleep pthread_cond_signal(&cond); pthread_cond_wait(&cond, &semaforo); } printf("C"); order = (order + 1) % 3; fflush(stdout); // Wake up another thread pthread_cond_signal(&cond); pthread_mutex_unlock(&semaforo); } } int main(){ pthread_t thread1, thread2, thread3; pthread_create(&thread1,NULL,escribirA,NULL); pthread_create(&thread2,NULL,escribirB,NULL); pthread_create(&thread3,NULL,escribirC,NULL); pthread_join(thread1, NULL); pthread_join(thread2, NULL); pthread_join(thread3, NULL); return(0); } ``` Example of execution: ```none $ gcc order.c -o order -lpthread $ ./order ABCABCABCABCABCABC ```
73,842,262
I'm using C and I want to get the String "ABCABCABCABCABCABC" in the output screen through multithreading. One thread displays the 'A' character, the second one displays the 'B' and the third one displays the 'C'. If I compile the following code: ``` #include <pthread.h> #include <stdlib.h> #include <stdio.h> #define cantidad_impresion_letra 6 pthread_mutex_t semaforo = PTHREAD_MUTEX_INITIALIZER; void *escribirA(void *unused){ int i; for(i=0;i<cantidad_impresion_letra;i++){ pthread_mutex_lock(&semaforo); printf("A"); pthread_mutex_unlock(&semaforo); } } void *escribirB(void *unused){ int i; for(i=0;i<cantidad_impresion_letra;i++){ pthread_mutex_lock(&semaforo); printf("B"); pthread_mutex_unlock(&semaforo); } } void *escribirC(void *unused){ int i; for(i=0;i<cantidad_impresion_letra;i++){ pthread_mutex_lock(&semaforo); printf("C"); pthread_mutex_unlock(&semaforo); } } int main(){ pthread_t thread1, thread2, thread3; pthread_create(&thread1,NULL,escribirA,NULL); pthread_create(&thread2,NULL,escribirB,NULL); pthread_create(&thread3,NULL,escribirC,NULL); pthread_join(thread1, NULL); pthread_join(thread2, NULL); pthread_join(thread3, NULL); return(0); } ``` On Windows through Dev-C++, the console throws me: `ABACBACBACBACBACBC` but if I compile **the same** code in Linux, I get `CCCCCCBBBBBBAAAAAA`. Can someone explain me this please?
2022/09/25
[ "https://Stackoverflow.com/questions/73842262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20080932/" ]
> > Can someone explain me this please? > > > The different output in linux has to do with the used scheduler. [man sched](https://man7.org/linux/man-pages/man7/sched.7.html) > > Since Linux 2.6.23, the default scheduler is CFS, the "Completely Fair Scheduler". > > > [Completely Fair Scheduler](https://en.wikipedia.org/wiki/Completely_Fair_Scheduler): > > Each per-CPU run-queue of type cfs\_rq **sorts** sched\_entity structures in a **time-ordered** fashion into a red-black tree (or 'rbtree' in Linux lingo), where the leftmost node is occupied by the entity that has received the **least** slice of **execution time** (which is saved in the vruntime field of the entity). The nodes are indexed by processor "execution time" in nanoseconds. > > > **What does that mean:** Each thread runs so fast, that the scheduler doesn't deem it necessary to perform a context switch. There are only 6 iteration steps and an output into a buffered stream (no newline, therefore no output to the terminal until a flush occurs). Do the test, increase the iteration steps, add more characters to the output and add a newline character (`\n`). The sequence will start to change. On my system, the sequence started to change with 200 iteration steps and 3 characters (plus `\n`). --- > > I'm using C and I want to get the String "ABCABCABCABCABCABC" > > > **1. Sequential output is best achieved through sequential execution.** * use only one thread (single threaded) **2. Notify/Wait** * each thread performs an iteration, signals the other thread and then waits for a signal to arrive in order to continue on the next cycle **3. Barrier** ``` //introduce NUM_THREAD lists char dataA[cantidad_impresion_letra]; char dataB[cantidad_impresion_letra]; char dataC[cantidad_impresion_letra]; //let the thread do their work without any disturbance void *escribirA(void *unused){ //unused could be used to pass the lists int i; for(i=0;i<cantidad_impresion_letra;i++){ //pthread_mutex_lock(&semaforo); //not needed //instead of printf("A"); dataA[i] = 'A'; //pthread_mutex_unlock(&semaforo); //not needed } } //same for escribirB but write into dataB //same for escribirC but write into dataC int main() { //... //after joining the threads //collective output in any desired order for (int i=0; i < cantidad_impresion_letra; ++i) { printf("%c", dataA[i]); printf("%c", dataB[i]); printf("%c", dataC[i]); } return 0; } ``` The advantages: * no lock/unlock (if the global lists are not accessed otherwise) * no waiting and broadcasting * guaranteed synchronized output * let the OS decide when it is best to yield a thread (scheduler) Disadvantage: * more memory intensive (depends on the number of threads and the iteration steps)
> > On Windows through Dev-C++, the console throws me: ABACBACBACBACBACBC but if I compile the same code in Linux, I get CCCCCCBBBBBBAAAAAA. > Can someone explain me this please? > > > The Linux behavior is what you should expect. Some thread has to start running first. Whichever thread it is, the other two threads will be blocked. That thread will be able to continue running for some time since there is nothing that it needs to wait for. The behavior you see in Windows is awful -- the worst possible. Either it's keeping all three threads scheduled or it's not. If it's keeping all three threads scheduled, it's using three cores for work that can be done equally fast with just one core. If it's not keeping all three threads scheduled, then you are getting one context switch per character of output and wasting CPU time constantly populating the code and data caches because you just switched from another task.
32,849,355
I have a big dataframe and I need to create a new dataframe only with the data where one index is consecutive to the other. For Example: ``` import pandas as pd import numpy as np indexer = [0,1,3,5,6,8,10,12,13,17,18,20,22,24,25,26] df = pd.DataFrame(range(50,66), index=indexer, columns = ['A']) ``` So the desired output in this case is: ``` A 0 50 1 51 5 53 6 54 12 57 13 58 17 59 18 60 24 63 25 64 26 65 ``` Is there a fast way of doing it in pandas? or need to do it with some kind of loop and function over each row?
2015/09/29
[ "https://Stackoverflow.com/questions/32849355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5235265/" ]
You can't shift the index, so you first need to reset it. Then use a `loc` operation together with testing both up and down one shift. Remember to set your index back to the original. ``` df.reset_index(inplace=True) >>> df.loc[(df['index'] == df['index'].shift(1) + 1) | (df['index'] == df['index'].shift(-1) - 1), :].set_index('index') A index 0 50 1 51 5 53 6 54 12 57 13 58 17 59 18 60 24 63 25 64 26 65 ```
Yes there's a faster way, using the [`.diff()` method, which exists on `Series` and `DataFrame`, but not `Int64Index`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.diff.html). We want all the rows where either forward difference == 1 or backward difference == -1. We use logical indexing directly, and no need to otherwise mess with the index or df. ``` ixdiff = df.index.to_series().diff df[ixdiff(1).eq(1) | ixdiff(-1).eq(-1)] #WAS: #ix = df.index.to_series() # convert so we can use .diff() #df[ (ix.diff() == 1) | (ix.diff(-1) == -1) ] A 0 50 1 51 5 53 6 54 12 57 13 58 17 59 18 60 24 63 25 64 26 65 ``` Notes: * thanks to @Alexander for the slight improvement * in this case we don't need to worry about the first entry in `ix.diff()` being NaN, or the last entry in `ix.diff(-1)`, since at least one of the forward- and backward- diffs will match, when consecutive. So we don't need to `.fillna(...)` as we normally would when using `diff(...)`.
4,726,220
When executing the command *shell-command*, the output shown in the associated buffer is not colorized. This is particularly annoying when calling a testing framework (outputting yellow/green/red...) from within emacs. How can I configure, or extend, emacs in order to have *shell-command* allowing colorized output in the shell and preserving the colors while representing that output? Thanks! ps. I'm using the Bash shell, on a UN\*X system.
2011/01/18
[ "https://Stackoverflow.com/questions/4726220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/479711/" ]
You can implement your own shell-execute, something like ``` (defun my-shell-execute(cmd) (interactive "sShell command: ") (shell (get-buffer-create "my-shell-buf")) (process-send-string (get-buffer-process "my-shell-buf") (concat cmd "\n"))) ```
This is probably what you want : ``` (add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on) ```
4,726,220
When executing the command *shell-command*, the output shown in the associated buffer is not colorized. This is particularly annoying when calling a testing framework (outputting yellow/green/red...) from within emacs. How can I configure, or extend, emacs in order to have *shell-command* allowing colorized output in the shell and preserving the colors while representing that output? Thanks! ps. I'm using the Bash shell, on a UN\*X system.
2011/01/18
[ "https://Stackoverflow.com/questions/4726220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/479711/" ]
This is probably what you want : ``` (add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on) ```
This adds an advice to run `ansi-color-apply-on-region` on the minibuffer after shell-command finishes: ``` (require 'ansi-color) (defun ansi-color-apply-on-buffer () (ansi-color-apply-on-region (point-min) (point-max))) (defun ansi-color-apply-on-minibuffer () (let ((bufs (remove-if-not (lambda (x) (string-starts-with (buffer-name x) " *Echo Area")) (buffer-list)))) (dolist (buf bufs) (with-current-buffer buf (ansi-color-apply-on-buffer))))) (defun ansi-color-apply-on-minibuffer-advice (proc &rest rest) (ansi-color-apply-on-minibuffer)) (advice-add 'shell-command :after #'ansi-color-apply-on-minibuffer-advice) ;; (advice-remove 'shell-command #'ansi-color-apply-on-minibuffer-advice) ``` It does not rely on shell-mode or comint. I accompany it with something like the following to get nice test output (a green smiley with the count of successful doctests. ``` (defun add-test-function (cmd) (interactive "sCommand to run: ") (setq my-testall-test-function cmd) (defun my-testall () (interactive) (shell-command my-testall-test-function)) (local-set-key [f9] 'my-testall)) ```
4,726,220
When executing the command *shell-command*, the output shown in the associated buffer is not colorized. This is particularly annoying when calling a testing framework (outputting yellow/green/red...) from within emacs. How can I configure, or extend, emacs in order to have *shell-command* allowing colorized output in the shell and preserving the colors while representing that output? Thanks! ps. I'm using the Bash shell, on a UN\*X system.
2011/01/18
[ "https://Stackoverflow.com/questions/4726220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/479711/" ]
This is probably what you want : ``` (add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on) ```
This solution is inspired by [@ArneBabenhauserheide](https://stackoverflow.com/a/42666026/2974621)'s but uses [`xterm-color`](https://github.com/atomontage/xterm-color) instead of `ansi-color`. It also colorizes the `*Shell Command Output*` buffer as well as the mini ``` (defun xterm-color-colorize-shell-command-output () "Colorize `shell-command' output." (let ((bufs (seq-remove (lambda (x) (not (or (string-prefix-p " *Echo Area" (buffer-name x)) (string-prefix-p "*Shell Command" (buffer-name x))))) (buffer-list)))) (dolist (buf bufs) (with-current-buffer buf (xterm-color-colorize-buffer))))) (defun xterm-color-colorize-shell-command-output-advice (proc &rest rest) (xterm-color-colorize-shell-command-output)) (advice-add 'shell-command :after #'xterm-color-colorize-shell-command-output-advice) ;; (advice-remove 'shell-command #'xterm-color-colorize-shell-command-output-advice) ```
4,726,220
When executing the command *shell-command*, the output shown in the associated buffer is not colorized. This is particularly annoying when calling a testing framework (outputting yellow/green/red...) from within emacs. How can I configure, or extend, emacs in order to have *shell-command* allowing colorized output in the shell and preserving the colors while representing that output? Thanks! ps. I'm using the Bash shell, on a UN\*X system.
2011/01/18
[ "https://Stackoverflow.com/questions/4726220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/479711/" ]
You can implement your own shell-execute, something like ``` (defun my-shell-execute(cmd) (interactive "sShell command: ") (shell (get-buffer-create "my-shell-buf")) (process-send-string (get-buffer-process "my-shell-buf") (concat cmd "\n"))) ```
This adds an advice to run `ansi-color-apply-on-region` on the minibuffer after shell-command finishes: ``` (require 'ansi-color) (defun ansi-color-apply-on-buffer () (ansi-color-apply-on-region (point-min) (point-max))) (defun ansi-color-apply-on-minibuffer () (let ((bufs (remove-if-not (lambda (x) (string-starts-with (buffer-name x) " *Echo Area")) (buffer-list)))) (dolist (buf bufs) (with-current-buffer buf (ansi-color-apply-on-buffer))))) (defun ansi-color-apply-on-minibuffer-advice (proc &rest rest) (ansi-color-apply-on-minibuffer)) (advice-add 'shell-command :after #'ansi-color-apply-on-minibuffer-advice) ;; (advice-remove 'shell-command #'ansi-color-apply-on-minibuffer-advice) ``` It does not rely on shell-mode or comint. I accompany it with something like the following to get nice test output (a green smiley with the count of successful doctests. ``` (defun add-test-function (cmd) (interactive "sCommand to run: ") (setq my-testall-test-function cmd) (defun my-testall () (interactive) (shell-command my-testall-test-function)) (local-set-key [f9] 'my-testall)) ```
4,726,220
When executing the command *shell-command*, the output shown in the associated buffer is not colorized. This is particularly annoying when calling a testing framework (outputting yellow/green/red...) from within emacs. How can I configure, or extend, emacs in order to have *shell-command* allowing colorized output in the shell and preserving the colors while representing that output? Thanks! ps. I'm using the Bash shell, on a UN\*X system.
2011/01/18
[ "https://Stackoverflow.com/questions/4726220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/479711/" ]
You can implement your own shell-execute, something like ``` (defun my-shell-execute(cmd) (interactive "sShell command: ") (shell (get-buffer-create "my-shell-buf")) (process-send-string (get-buffer-process "my-shell-buf") (concat cmd "\n"))) ```
This solution is inspired by [@ArneBabenhauserheide](https://stackoverflow.com/a/42666026/2974621)'s but uses [`xterm-color`](https://github.com/atomontage/xterm-color) instead of `ansi-color`. It also colorizes the `*Shell Command Output*` buffer as well as the mini ``` (defun xterm-color-colorize-shell-command-output () "Colorize `shell-command' output." (let ((bufs (seq-remove (lambda (x) (not (or (string-prefix-p " *Echo Area" (buffer-name x)) (string-prefix-p "*Shell Command" (buffer-name x))))) (buffer-list)))) (dolist (buf bufs) (with-current-buffer buf (xterm-color-colorize-buffer))))) (defun xterm-color-colorize-shell-command-output-advice (proc &rest rest) (xterm-color-colorize-shell-command-output)) (advice-add 'shell-command :after #'xterm-color-colorize-shell-command-output-advice) ;; (advice-remove 'shell-command #'xterm-color-colorize-shell-command-output-advice) ```
4,726,220
When executing the command *shell-command*, the output shown in the associated buffer is not colorized. This is particularly annoying when calling a testing framework (outputting yellow/green/red...) from within emacs. How can I configure, or extend, emacs in order to have *shell-command* allowing colorized output in the shell and preserving the colors while representing that output? Thanks! ps. I'm using the Bash shell, on a UN\*X system.
2011/01/18
[ "https://Stackoverflow.com/questions/4726220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/479711/" ]
This adds an advice to run `ansi-color-apply-on-region` on the minibuffer after shell-command finishes: ``` (require 'ansi-color) (defun ansi-color-apply-on-buffer () (ansi-color-apply-on-region (point-min) (point-max))) (defun ansi-color-apply-on-minibuffer () (let ((bufs (remove-if-not (lambda (x) (string-starts-with (buffer-name x) " *Echo Area")) (buffer-list)))) (dolist (buf bufs) (with-current-buffer buf (ansi-color-apply-on-buffer))))) (defun ansi-color-apply-on-minibuffer-advice (proc &rest rest) (ansi-color-apply-on-minibuffer)) (advice-add 'shell-command :after #'ansi-color-apply-on-minibuffer-advice) ;; (advice-remove 'shell-command #'ansi-color-apply-on-minibuffer-advice) ``` It does not rely on shell-mode or comint. I accompany it with something like the following to get nice test output (a green smiley with the count of successful doctests. ``` (defun add-test-function (cmd) (interactive "sCommand to run: ") (setq my-testall-test-function cmd) (defun my-testall () (interactive) (shell-command my-testall-test-function)) (local-set-key [f9] 'my-testall)) ```
This solution is inspired by [@ArneBabenhauserheide](https://stackoverflow.com/a/42666026/2974621)'s but uses [`xterm-color`](https://github.com/atomontage/xterm-color) instead of `ansi-color`. It also colorizes the `*Shell Command Output*` buffer as well as the mini ``` (defun xterm-color-colorize-shell-command-output () "Colorize `shell-command' output." (let ((bufs (seq-remove (lambda (x) (not (or (string-prefix-p " *Echo Area" (buffer-name x)) (string-prefix-p "*Shell Command" (buffer-name x))))) (buffer-list)))) (dolist (buf bufs) (with-current-buffer buf (xterm-color-colorize-buffer))))) (defun xterm-color-colorize-shell-command-output-advice (proc &rest rest) (xterm-color-colorize-shell-command-output)) (advice-add 'shell-command :after #'xterm-color-colorize-shell-command-output-advice) ;; (advice-remove 'shell-command #'xterm-color-colorize-shell-command-output-advice) ```
26,882
My asp.net page will render different controls based on which report a user has selected e.g. some reports require 5 drop downs, some two checkboxes and 6 dropdowns). They can select a report using two methods. With `SelectedReport=MyReport` in the query string, or by selecting it from a dropdown. And it's a common case for them to come to the page with SelectedReport in the query string, and then change the report selected in the drop down. My question is, is there anyway of making the dropdown modify the query string when it's selected. So I'd want `SelectedReport=MyNewReport` in the query string and the page to post back. At the moment it's just doing a normal postback, which leaves the `SelectedReport=MyReport` in the query string, even if it's not the currently selected report. **Edit:** And I also need to preserve ViewState. I've tried doing `Server.Transfer(Request.Path + "?SelectedReport=" + SelectedReport, true)` in the event handler for the Dropdown, and this works function wise, unfortunately because it's a Server.Transfer (to preserve ViewState) instead of a Response.Redirect the URL lags behind what's shown. Maybe I'm asking the impossible or going about it completely the wrong way. **@Craig** The QueryString collection is read-only and cannot be modified. **@Jason** That would be great, except I'd lose the ViewState wouldn't I? (Sorry I added that after seeing your response).
2008/08/25
[ "https://Stackoverflow.com/questions/26882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/233/" ]
You need to turn off autopostback on the dropdown - then, you need to hook up some javascript code that will take over that role - in the event handler code for the onchange event for the dropdown, you would create a URL based on the currently-selected value from the dropdown and use javascript to then request that page. EDIT: Here is some quick and dirty code that is indicative of what would do the trick: ``` <script> function changeReport(dropDownList) { var selectedReport = dropDownList.options[dropDownList.selectedIndex]; window.location = ("scratch.htm?SelectedReport=" + selectedReport.value); } </script> <select id="SelectedReport" onchange="changeReport(this)"> <option value="foo">foo</option> <option value="bar">bar</option> <option value="baz">baz</option> </select> ``` Obviously you would need to do a bit more, but this does work and would give you what it seems you are after. I would recommend using a JavaScript toolkit (I use MochiKit, but it isn't for everyone) to get some of the harder work done - use unobtrusive JavaScript techniques if at all possible (unlike what I use in this example). **@Ray:** You use ViewState?! I'm so sorry. :P Why, in this instance, do you need to preserve it. pray tell?
If it's an automatic post when the data changes then you should be able to redirect to the new query string with a server side handler of the dropdown's 'onchange' event. If it's a button, handle server side in the click event. I'd post a sample of what I'm talking about but I'm on the way out to pick up the kids.
26,882
My asp.net page will render different controls based on which report a user has selected e.g. some reports require 5 drop downs, some two checkboxes and 6 dropdowns). They can select a report using two methods. With `SelectedReport=MyReport` in the query string, or by selecting it from a dropdown. And it's a common case for them to come to the page with SelectedReport in the query string, and then change the report selected in the drop down. My question is, is there anyway of making the dropdown modify the query string when it's selected. So I'd want `SelectedReport=MyNewReport` in the query string and the page to post back. At the moment it's just doing a normal postback, which leaves the `SelectedReport=MyReport` in the query string, even if it's not the currently selected report. **Edit:** And I also need to preserve ViewState. I've tried doing `Server.Transfer(Request.Path + "?SelectedReport=" + SelectedReport, true)` in the event handler for the Dropdown, and this works function wise, unfortunately because it's a Server.Transfer (to preserve ViewState) instead of a Response.Redirect the URL lags behind what's shown. Maybe I'm asking the impossible or going about it completely the wrong way. **@Craig** The QueryString collection is read-only and cannot be modified. **@Jason** That would be great, except I'd lose the ViewState wouldn't I? (Sorry I added that after seeing your response).
2008/08/25
[ "https://Stackoverflow.com/questions/26882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/233/" ]
You need to turn off autopostback on the dropdown - then, you need to hook up some javascript code that will take over that role - in the event handler code for the onchange event for the dropdown, you would create a URL based on the currently-selected value from the dropdown and use javascript to then request that page. EDIT: Here is some quick and dirty code that is indicative of what would do the trick: ``` <script> function changeReport(dropDownList) { var selectedReport = dropDownList.options[dropDownList.selectedIndex]; window.location = ("scratch.htm?SelectedReport=" + selectedReport.value); } </script> <select id="SelectedReport" onchange="changeReport(this)"> <option value="foo">foo</option> <option value="bar">bar</option> <option value="baz">baz</option> </select> ``` Obviously you would need to do a bit more, but this does work and would give you what it seems you are after. I would recommend using a JavaScript toolkit (I use MochiKit, but it isn't for everyone) to get some of the harder work done - use unobtrusive JavaScript techniques if at all possible (unlike what I use in this example). **@Ray:** You use ViewState?! I'm so sorry. :P Why, in this instance, do you need to preserve it. pray tell?
Have you tried to modify the Request.QueryString[] on the SelectedIndexChanged for the DropDown? That should do the trick.
26,882
My asp.net page will render different controls based on which report a user has selected e.g. some reports require 5 drop downs, some two checkboxes and 6 dropdowns). They can select a report using two methods. With `SelectedReport=MyReport` in the query string, or by selecting it from a dropdown. And it's a common case for them to come to the page with SelectedReport in the query string, and then change the report selected in the drop down. My question is, is there anyway of making the dropdown modify the query string when it's selected. So I'd want `SelectedReport=MyNewReport` in the query string and the page to post back. At the moment it's just doing a normal postback, which leaves the `SelectedReport=MyReport` in the query string, even if it's not the currently selected report. **Edit:** And I also need to preserve ViewState. I've tried doing `Server.Transfer(Request.Path + "?SelectedReport=" + SelectedReport, true)` in the event handler for the Dropdown, and this works function wise, unfortunately because it's a Server.Transfer (to preserve ViewState) instead of a Response.Redirect the URL lags behind what's shown. Maybe I'm asking the impossible or going about it completely the wrong way. **@Craig** The QueryString collection is read-only and cannot be modified. **@Jason** That would be great, except I'd lose the ViewState wouldn't I? (Sorry I added that after seeing your response).
2008/08/25
[ "https://Stackoverflow.com/questions/26882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/233/" ]
You need to turn off autopostback on the dropdown - then, you need to hook up some javascript code that will take over that role - in the event handler code for the onchange event for the dropdown, you would create a URL based on the currently-selected value from the dropdown and use javascript to then request that page. EDIT: Here is some quick and dirty code that is indicative of what would do the trick: ``` <script> function changeReport(dropDownList) { var selectedReport = dropDownList.options[dropDownList.selectedIndex]; window.location = ("scratch.htm?SelectedReport=" + selectedReport.value); } </script> <select id="SelectedReport" onchange="changeReport(this)"> <option value="foo">foo</option> <option value="bar">bar</option> <option value="baz">baz</option> </select> ``` Obviously you would need to do a bit more, but this does work and would give you what it seems you are after. I would recommend using a JavaScript toolkit (I use MochiKit, but it isn't for everyone) to get some of the harder work done - use unobtrusive JavaScript techniques if at all possible (unlike what I use in this example). **@Ray:** You use ViewState?! I'm so sorry. :P Why, in this instance, do you need to preserve it. pray tell?
You could populate your dropdown based on the querystring on non-postbacks, then always use the value from the dropdown. That way the user's first visit to the page will be based on the querystring and subsequent changes they make to the dropdown will change the selected report.
26,882
My asp.net page will render different controls based on which report a user has selected e.g. some reports require 5 drop downs, some two checkboxes and 6 dropdowns). They can select a report using two methods. With `SelectedReport=MyReport` in the query string, or by selecting it from a dropdown. And it's a common case for them to come to the page with SelectedReport in the query string, and then change the report selected in the drop down. My question is, is there anyway of making the dropdown modify the query string when it's selected. So I'd want `SelectedReport=MyNewReport` in the query string and the page to post back. At the moment it's just doing a normal postback, which leaves the `SelectedReport=MyReport` in the query string, even if it's not the currently selected report. **Edit:** And I also need to preserve ViewState. I've tried doing `Server.Transfer(Request.Path + "?SelectedReport=" + SelectedReport, true)` in the event handler for the Dropdown, and this works function wise, unfortunately because it's a Server.Transfer (to preserve ViewState) instead of a Response.Redirect the URL lags behind what's shown. Maybe I'm asking the impossible or going about it completely the wrong way. **@Craig** The QueryString collection is read-only and cannot be modified. **@Jason** That would be great, except I'd lose the ViewState wouldn't I? (Sorry I added that after seeing your response).
2008/08/25
[ "https://Stackoverflow.com/questions/26882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/233/" ]
You need to turn off autopostback on the dropdown - then, you need to hook up some javascript code that will take over that role - in the event handler code for the onchange event for the dropdown, you would create a URL based on the currently-selected value from the dropdown and use javascript to then request that page. EDIT: Here is some quick and dirty code that is indicative of what would do the trick: ``` <script> function changeReport(dropDownList) { var selectedReport = dropDownList.options[dropDownList.selectedIndex]; window.location = ("scratch.htm?SelectedReport=" + selectedReport.value); } </script> <select id="SelectedReport" onchange="changeReport(this)"> <option value="foo">foo</option> <option value="bar">bar</option> <option value="baz">baz</option> </select> ``` Obviously you would need to do a bit more, but this does work and would give you what it seems you are after. I would recommend using a JavaScript toolkit (I use MochiKit, but it isn't for everyone) to get some of the harder work done - use unobtrusive JavaScript techniques if at all possible (unlike what I use in this example). **@Ray:** You use ViewState?! I'm so sorry. :P Why, in this instance, do you need to preserve it. pray tell?
The view state only lasts for [multiple requests for the same page](http://msdn.microsoft.com/en-us/library/540y83hx.aspx). Changing the query string in the URL is requesting a new page, thus clearing the view state. Is it possible to remove the reliance on the view state by adding more query string parameters? You can then build a new URL and Response.Redirect to it. Another option is to use the [Action property](http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlform.action.aspx) on the form to clear the query string so at least the query string does not contradict what's displayed on the page after the user selects a different report. ``` Form.Action = Request.Path; ```
26,882
My asp.net page will render different controls based on which report a user has selected e.g. some reports require 5 drop downs, some two checkboxes and 6 dropdowns). They can select a report using two methods. With `SelectedReport=MyReport` in the query string, or by selecting it from a dropdown. And it's a common case for them to come to the page with SelectedReport in the query string, and then change the report selected in the drop down. My question is, is there anyway of making the dropdown modify the query string when it's selected. So I'd want `SelectedReport=MyNewReport` in the query string and the page to post back. At the moment it's just doing a normal postback, which leaves the `SelectedReport=MyReport` in the query string, even if it's not the currently selected report. **Edit:** And I also need to preserve ViewState. I've tried doing `Server.Transfer(Request.Path + "?SelectedReport=" + SelectedReport, true)` in the event handler for the Dropdown, and this works function wise, unfortunately because it's a Server.Transfer (to preserve ViewState) instead of a Response.Redirect the URL lags behind what's shown. Maybe I'm asking the impossible or going about it completely the wrong way. **@Craig** The QueryString collection is read-only and cannot be modified. **@Jason** That would be great, except I'd lose the ViewState wouldn't I? (Sorry I added that after seeing your response).
2008/08/25
[ "https://Stackoverflow.com/questions/26882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/233/" ]
You need to turn off autopostback on the dropdown - then, you need to hook up some javascript code that will take over that role - in the event handler code for the onchange event for the dropdown, you would create a URL based on the currently-selected value from the dropdown and use javascript to then request that page. EDIT: Here is some quick and dirty code that is indicative of what would do the trick: ``` <script> function changeReport(dropDownList) { var selectedReport = dropDownList.options[dropDownList.selectedIndex]; window.location = ("scratch.htm?SelectedReport=" + selectedReport.value); } </script> <select id="SelectedReport" onchange="changeReport(this)"> <option value="foo">foo</option> <option value="bar">bar</option> <option value="baz">baz</option> </select> ``` Obviously you would need to do a bit more, but this does work and would give you what it seems you are after. I would recommend using a JavaScript toolkit (I use MochiKit, but it isn't for everyone) to get some of the harder work done - use unobtrusive JavaScript techniques if at all possible (unlike what I use in this example). **@Ray:** You use ViewState?! I'm so sorry. :P Why, in this instance, do you need to preserve it. pray tell?
You can use the following function to modify the querystring on postback in asp.net using the Webresource.axd script as below. ``` var url = updateQueryStringParameter(window.location.href, 'Search', document.getElementById('txtSearch').value); WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("searchbutton", "", true, "aa", url, false, true)); ```
60,525,208
I am a newbie on Kubernetes and try to generate 2 pods including front-end application and back-end mysql. First I make a yaml file which contains both application and mysql server like below, ``` apiVersion: v1 kind: Pod metadata: name: blog-system spec: containers: - name: blog-app image: blog-app:latest imagePullPolicy: Never ports: - containerPort: 8080 args: ["-t", "-i"] link: blog-mysql - name: blog-mysql image: mysql:latest env: - name: MYSQL_ROOT_PASSWORD value: password - name: MYSQL_PASSWORD value: password - name: MYSQL_DATABASE value: test ports: - containerPort: 3306 ``` The mysql jdbc url of front-end application is `jdbc:mysql://localhost:3306/test`. And pod generation is successful. The application and mysql are connected without errors. And this time I seperate application pod and mysql pod into 2 yaml files. == pod-app.yaml ``` apiVersion: v1 kind: Pod metadata: name: blog-app spec: selector: app: blog-mysql containers: - name: blog-app image: app:latest imagePullPolicy: Never ports: - containerPort: 8080 args: ["-t", "-i"] link: blog-mysql ``` == pod-db.yaml ``` apiVersion: v1 kind: Pod metadata: name: blog-mysql labels: app: blog-mysql spec: containers: - name: blog-mysql image: mysql:latest env: - name: MYSQL_ROOT_PASSWORD value: password - name: MYSQL_PASSWORD value: password - name: MYSQL_DATABASE value: test ports: - containerPort: 3306 ``` But the front-end application can not connect to mysql pod. It throws the connection exceptions. I am afraid the mysql jdbc url has some incorrect values or the yaml value has inappropriate values. I hope any advices.
2020/03/04
[ "https://Stackoverflow.com/questions/60525208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3840940/" ]
In the working case since same pod has two containers they are able to talk using localhost but in the second case since you have two pods you can not use localhost anymore. In this case you need to use the pod IP of the mysql pod in the frontend application. But problem with using POD IP is that it may change. Better is to expose mysql pod as [service](https://kubernetes.io/docs/concepts/services-networking/service/) and use service name instead of IP in the frontend application. Check this [guide](https://kubernetes.io/docs/tutorials/stateful-application/mysql-wordpress-persistent-volume/)
For this you need to write service for exposing the db pod. There are 4 types of services. 1. `ClusterIP` 2. `NodePort` 3. `LoadBalancer` 4. `ExternalName` Now you need only inside the cluster then use `ClusterIP` For reference use following yaml file. ``` kind: Service apiVersion: v1 metadata: name: mysql-svc spec: type: ClusterIP ports: - port: 3306 targetPort: 3306 selector: app: blog-mysql ``` Now you will be access this pod using `mysql-svc:3306` Refer this in blog-app yaml with ``` env: - name: MYSQL_URL value: mysql-svc - name: MYSQL_PORT value: 3306 ``` For more info use Url :<https://kubernetes.io/docs/concepts/services-networking/service/>
60,525,208
I am a newbie on Kubernetes and try to generate 2 pods including front-end application and back-end mysql. First I make a yaml file which contains both application and mysql server like below, ``` apiVersion: v1 kind: Pod metadata: name: blog-system spec: containers: - name: blog-app image: blog-app:latest imagePullPolicy: Never ports: - containerPort: 8080 args: ["-t", "-i"] link: blog-mysql - name: blog-mysql image: mysql:latest env: - name: MYSQL_ROOT_PASSWORD value: password - name: MYSQL_PASSWORD value: password - name: MYSQL_DATABASE value: test ports: - containerPort: 3306 ``` The mysql jdbc url of front-end application is `jdbc:mysql://localhost:3306/test`. And pod generation is successful. The application and mysql are connected without errors. And this time I seperate application pod and mysql pod into 2 yaml files. == pod-app.yaml ``` apiVersion: v1 kind: Pod metadata: name: blog-app spec: selector: app: blog-mysql containers: - name: blog-app image: app:latest imagePullPolicy: Never ports: - containerPort: 8080 args: ["-t", "-i"] link: blog-mysql ``` == pod-db.yaml ``` apiVersion: v1 kind: Pod metadata: name: blog-mysql labels: app: blog-mysql spec: containers: - name: blog-mysql image: mysql:latest env: - name: MYSQL_ROOT_PASSWORD value: password - name: MYSQL_PASSWORD value: password - name: MYSQL_DATABASE value: test ports: - containerPort: 3306 ``` But the front-end application can not connect to mysql pod. It throws the connection exceptions. I am afraid the mysql jdbc url has some incorrect values or the yaml value has inappropriate values. I hope any advices.
2020/03/04
[ "https://Stackoverflow.com/questions/60525208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3840940/" ]
In the working case since same pod has two containers they are able to talk using localhost but in the second case since you have two pods you can not use localhost anymore. In this case you need to use the pod IP of the mysql pod in the frontend application. But problem with using POD IP is that it may change. Better is to expose mysql pod as [service](https://kubernetes.io/docs/concepts/services-networking/service/) and use service name instead of IP in the frontend application. Check this [guide](https://kubernetes.io/docs/tutorials/stateful-application/mysql-wordpress-persistent-volume/)
Pods created will have dns configured in the following manner `pod_name.namespace.svc.cluster.local` In your case assuming these pods are in default namespace your jdbc connection string will be `jdbc:mysql://blog-mysql.default.svc.cluster.local:3306/test` Refer: <https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#pods> Like Arghya Sadhu and Sachin Arote suggested you can always create a service and deployment. Service and deployment helps you in the cases where you have more than one replicas of pods and service takes care of the load-balancing.
60,525,208
I am a newbie on Kubernetes and try to generate 2 pods including front-end application and back-end mysql. First I make a yaml file which contains both application and mysql server like below, ``` apiVersion: v1 kind: Pod metadata: name: blog-system spec: containers: - name: blog-app image: blog-app:latest imagePullPolicy: Never ports: - containerPort: 8080 args: ["-t", "-i"] link: blog-mysql - name: blog-mysql image: mysql:latest env: - name: MYSQL_ROOT_PASSWORD value: password - name: MYSQL_PASSWORD value: password - name: MYSQL_DATABASE value: test ports: - containerPort: 3306 ``` The mysql jdbc url of front-end application is `jdbc:mysql://localhost:3306/test`. And pod generation is successful. The application and mysql are connected without errors. And this time I seperate application pod and mysql pod into 2 yaml files. == pod-app.yaml ``` apiVersion: v1 kind: Pod metadata: name: blog-app spec: selector: app: blog-mysql containers: - name: blog-app image: app:latest imagePullPolicy: Never ports: - containerPort: 8080 args: ["-t", "-i"] link: blog-mysql ``` == pod-db.yaml ``` apiVersion: v1 kind: Pod metadata: name: blog-mysql labels: app: blog-mysql spec: containers: - name: blog-mysql image: mysql:latest env: - name: MYSQL_ROOT_PASSWORD value: password - name: MYSQL_PASSWORD value: password - name: MYSQL_DATABASE value: test ports: - containerPort: 3306 ``` But the front-end application can not connect to mysql pod. It throws the connection exceptions. I am afraid the mysql jdbc url has some incorrect values or the yaml value has inappropriate values. I hope any advices.
2020/03/04
[ "https://Stackoverflow.com/questions/60525208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3840940/" ]
For this you need to write service for exposing the db pod. There are 4 types of services. 1. `ClusterIP` 2. `NodePort` 3. `LoadBalancer` 4. `ExternalName` Now you need only inside the cluster then use `ClusterIP` For reference use following yaml file. ``` kind: Service apiVersion: v1 metadata: name: mysql-svc spec: type: ClusterIP ports: - port: 3306 targetPort: 3306 selector: app: blog-mysql ``` Now you will be access this pod using `mysql-svc:3306` Refer this in blog-app yaml with ``` env: - name: MYSQL_URL value: mysql-svc - name: MYSQL_PORT value: 3306 ``` For more info use Url :<https://kubernetes.io/docs/concepts/services-networking/service/>
Pods created will have dns configured in the following manner `pod_name.namespace.svc.cluster.local` In your case assuming these pods are in default namespace your jdbc connection string will be `jdbc:mysql://blog-mysql.default.svc.cluster.local:3306/test` Refer: <https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#pods> Like Arghya Sadhu and Sachin Arote suggested you can always create a service and deployment. Service and deployment helps you in the cases where you have more than one replicas of pods and service takes care of the load-balancing.
2,170,843
> > A file that is given as input to the linker is called **Object File**. > The linker produces an **Image file**, which in turn is used as input by the loader. > > > A blurb from "**Microsoft Portable Executable and Common Object File Format Specification**" > > **RVA (relative virtual address)**. In an image file, the address of an item > after it is loaded into memory, with > the base address of the image file > subtracted from it. The RVA of an item > almost always differs from its > position within the file on disk (file > pointer). > > > In an object file, an RVA is less > meaningful because memory locations > are not assigned. In this case, an RVA > would be an address within a section > (described later in this table), to > which a relocation is later applied > during linking. For simplicity, a > compiler should just set the first RVA > in each section to zero. > > > **VA (virtual address)**. Same as RVA, except that the base address of the > image file is not subtracted. The > address is called a “VA” because > Windows creates a distinct VA space > for each process, independent of > physical memory. For almost all > purposes, a VA should be considered > just an address. A VA is not as > predictable as an RVA because the > loader might not load the image at its > preferred location. > > > Even after reading this, I still don't get it. I've lot of questions. Can any one explain it in a practical way. Please stick to terminology of `Object File` & `Image File` as stated. All I know about addresses, is that * Neither in the Object File nor in the Image File, we don't know the exact memory locations so, * Assembler while generating Object File computes addresses relative to sections `.data` & `.text` (for function names). * Linker taking multiple object files as input generates one Image file. While generating, it first merges all the sections of each object file and while merging it recomputes the address offsets again relative to each section. And, there is nothing like global offsets. If there is some thing wrong in what I know, please correct me. **EDIT:** After reading answer given Francis, I'm clear about whats Physical Address, VA & RVA and what are the relation between them. RVAs of all variables&methods must be computed by the Linker during relocation. So, **(the value of RVA of a method/variable) == (its offset from the beginning of the file)**? must been true. But surprisingly, its not. Why so? I checked this by using [PEView](http://www.magma.ca/~wjr/PEview.zip) on `c:\WINDOWS\system32\kernel32.dll` and found that: 1. RVA & FileOffset are same till the beginning of Sections.(`.text` is the first section in this dll). 2. From the beginning of `.text` through `.data`,`.rsrc` till the last byte of last section (`.reloc`) RVA & FileOffset are different. & also the RVA of first byte of the first section is "always" being shown as `0x1000` 3. Interesting thing is that bytes of each section are continuous in FileOffset. I mean another section begins at the next byte of a section's last byte. But if I see the same thing in RVA, these is a huge gap in between RVAs of last byte of a section and first byte of next section. My Guess: 1. All, the bytes of data that were before the first (`.text` here) section are "not" actually loaded into VA space of the process, these bytes of data are just used to locate & describe these sections. They can be called, "meta section data". Since they are not loaded into VA space of process. the usage of the term RVA is also meaningless this is the reason why `RVA == FileOffset` for these bytes. 2. Since, * RVA term is valid for only those bytes which will be actually loaded into the VA space. * the bytes of `.text`, `.data`, `.rsrc`, `.reloc` are such bytes. * Instead of starting from RVA `0x00000` PEView software is starting it from `0x1000`. 3. I cannot understand why the 3rd observation. I cannot explain.
2010/01/31
[ "https://Stackoverflow.com/questions/2170843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193653/" ]
Most Windows process (\*.exe) are loaded in (user mode) memory address 0x00400000, that's what we call the "virtual address" (VA) - because they are visible only to each process, and will be converted to different physical addresses by the OS (visible by the kernel / driver layer). For example, a possible physical memory address (visible by the CPU): ``` 0x00300000 on physical memory has process A's main 0x00500000 on physical memory has process B's main ``` And the OS may have a mapping table: ``` process A's 0x00400000 (VA) = physical address 0x00300000 process B's 0x00400000 (VA) = physical address 0x00500000 ``` Then when you try to read 0x004000000 in process A, you'll get the content which is located on 0x00300000 of physical memory. Regarding RVA, it's simply designed to ease relocation. When loading relocable modules (eg, DLL) the system will try to slide it through process memory space. So in file layout it puts a "relative" address to help calculation. For example, a DLL C may have this address: ``` RVA 0x00001000 DLL C's main entry ``` When being loaded into process A at base address 0x10000000, C's main entry become ``` VA = 0x10000000 + 0x00001000 = 0x10001000 (if process A's VA 0x10000000 mapped to physical address was 0x30000000, then C's main entry will be 0x30001000 for physical address). ``` When being loaded into process B at base address 0x32000000, C's main entry become ``` VA = 0x32000000 + 0x00001000 = 0x32001000 (if process B's VA 0x32000000 mapped to physical address was 0x50000000, then C's main entry will be 0x50001000 for physical address). ``` Usually the RVA in image files is relative to process base address when being loaded into memory, but some RVA may be relative to the "section" starting address in image or object files (you have to check the PE format spec for detail). No matter which, RVA is relative to "some" base VA. To summarize, 1. Physical Memory Address is what CPU sees 2. Virtual Addreess (VA) is relative to Physical Address, per process (managed by OS) 3. RVA is relative to VA (file base or section base), per file (managed by linker and loader) (edit) regarding claw's new question: The value of RVA of a method/variable is NOT always its offset from the beginning of the file. They are usually relative to some VA, which may be a default loading base address or section base VA - that's why I say you must check the [PE format spec](https://en.wikipedia.org/wiki/Portable_Executable) for detail. Your tool, PEView is trying to display every byte's RVA to load base address. Since the sections start at different base, RVA may become different when crossing sections. Regarding your guesses, they are very close to the correct answers: 1. Usually we won't discuss the "RVA" before sections, but the PE header will still be loaded until the end of section headers. Gap between section header and section body (if any) won't be loaded. You can examine that by debuggers. Moreoever, when there's some gap between sections, they may be not loaded. 2. As I said, RVA is simply "relative to some VA", no matter what VA it is (although when talking about PE, the VA usually refers to the load base address). When you read thet PE format spec you may find some "RVA" which is relative to some special address like resource starting address. The PEView list RVA from 0x1000 is because that section starts at 0x1000. Why 0x1000? Because the linker left 0x1000 bytes for PE header, so the RVA starts at 0x1000. 3. What you've missed is the concept of "section" in PE loading stage. The PE may contain several "sections", each section maps to a new starting VA address. For example, this is dumped from win7 kernel32.dll: ``` # Name VirtSize RVA PhysSize Offset 1 .text 000C44C1 00001000 000C4600 00000800 2 .data 00000FEC 000C6000 00000E00 000C4E00 3 .rsrc 00000520 000C7000 00000600 000C5C00 4 .reloc 0000B098 000C8000 0000B200 000C6200 ``` There is an invisible "0 header RVA=0000, SIZE=1000" which forced .text to start at RVA 1000. The sections should be continuous when being loaded into memory (i.e., VA) so their RVA is continuous. However since the memory is allocated by pages, it'll be multiple of page size (4096=0x1000 bytes). That's why #2 section starts at 1000 + C5000 = C6000 (C5000 comes from C44C1). In order to provide memory mapping, these sections must still be aligned by some size (file alignment size - decide by linker. In my example above it's 0x200=512 bytes), which controls the PhysSize field. Offset means "offset to physical PE file beginning". So the headers occupy 0x800 bytes of file (and 0x1000 when being mapped to memory), which is the offset of section #1. Then by aligning its data (c44c1 bytes), we get physsize C4600. C4600+800 = C4E00, which is exactly the offset of second section. OK, this is related to whole PE loading stuff so it may be a little hard to understand... (edit) let me make a new simple summary again. 1. The "RVA" in DLL/EXE (PE Format) files are usually relative to the "load base address in memory" (but not always - you must read the spec) 2. The PE Format contains a "section" mapping structure to map the physical file content into memory. So the RVA is not really relative to the file offset. 3. To calculate a RVA of some byte, you have to find its offset in the section and add the section base.
A relative virtual address is an offset from the address at which the file is loaded. Probably the simplest way to get the idea is with an example. Assume you have a file (e.g., a DLL) that's loaded at address 1000h. In that file, you have a variable at RVA 200h. In that case, the VA of that variable (after the DLL is mapped to memory) is 1200h (i.e. the 1000h base address of the DLL plus the 200h RVA (offset) to the variable.
180,165
How do people define the minimum hardware requirements for software? For example: how can a software development company tell the customer that they will need 8 GB of RAM to run the program properly?
2012/12/20
[ "https://softwareengineering.stackexchange.com/questions/180165", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/75596/" ]
First off, not all requirements are hard requirements, but rather the minimum supported hardware. If someone has less than the minimum, it may run - but not optimally, or it may not run at all. In either case, its not a supported system and the problems you have are your own. The simplest way to get hardware requirements is guess. The developer looks at their machine and says "Yep, it runs on mine, that’s the requirements." In a more rigorous environment, the development company has a suite of test systems. It may not be in house (non in house apple developers occasionally use the [Apple Compatibility Lab](https://developer.apple.com/support/mac/compatibility.html)). As part of the testing process, one tests on all the hardware available and determines the minimum requirements for it to run. Another factor in hardware requirements is the base requirements for the operating system. In theory, Windows 7 requires a minimum of 1GB of ram to run. So testing against a 512 MB system running Windows 7 is nonsensical. Test the system running with 1 GB of ram. Does it work? Nope... upgrade the ram. Repeat the test and upgrades until the application works in a supportable way and list those as the minimum requirements. When performance becomes part of the promise of the software the 'supportable' includes that in addition to actually running, that the operation meets the minimum performance expectation.
For some applications the requirements may actually be hard requirements, such as when the developer has analyzed or profiled their app and knows exactly how many megaflops, MIPS, polygons per second, array working set sizes, etc. are required to meet some specified performance benchmark. For small developers, cost may be the issue. They only have one system available, and so they declare that system's specs as the minimum, as they haven't been able to test the app on anything else (slower, smaller, etc.) and have little clue on how the app would do with less resources.
180,165
How do people define the minimum hardware requirements for software? For example: how can a software development company tell the customer that they will need 8 GB of RAM to run the program properly?
2012/12/20
[ "https://softwareengineering.stackexchange.com/questions/180165", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/75596/" ]
First off, not all requirements are hard requirements, but rather the minimum supported hardware. If someone has less than the minimum, it may run - but not optimally, or it may not run at all. In either case, its not a supported system and the problems you have are your own. The simplest way to get hardware requirements is guess. The developer looks at their machine and says "Yep, it runs on mine, that’s the requirements." In a more rigorous environment, the development company has a suite of test systems. It may not be in house (non in house apple developers occasionally use the [Apple Compatibility Lab](https://developer.apple.com/support/mac/compatibility.html)). As part of the testing process, one tests on all the hardware available and determines the minimum requirements for it to run. Another factor in hardware requirements is the base requirements for the operating system. In theory, Windows 7 requires a minimum of 1GB of ram to run. So testing against a 512 MB system running Windows 7 is nonsensical. Test the system running with 1 GB of ram. Does it work? Nope... upgrade the ram. Repeat the test and upgrades until the application works in a supportable way and list those as the minimum requirements. When performance becomes part of the promise of the software the 'supportable' includes that in addition to actually running, that the operation meets the minimum performance expectation.
Hardware requirements fall into a couple of different buckets. Often you'll include requirements from a few of these buckets when determining specific hardware requirements for any software system you build. **Technical Constraints in the Architecture** These are the kinds of requirements that absolutely must be satisfied by the built system and are specifically designed into the system from the start. For example, "x86 processor is required." An easy example that comes to mind is Microsoft Office for Mac. Originally Macs used Power PC CPUs while Microsoft Windows was strictly targeted at "IBM Compatible" machines (mostly using x86 processors). Because Windows and thus Office only worked on x86, a completely new set of code (with different technical constraints) was written to support Office on Power PC for Mac OS. Once Mac moved to Intel x86 processors, the old Power PC optimized Office for Mac no longer worked -- and technical constraints once again changed for a new version of Office for Mac on Intel. Applications optimized for 32 vs. 64 bit is another easy example. **Implicit Hardware Requirements** Sometimes you don't actively choose to constrain yourself, but other decisions you make implicitly force requirements on to you. A common scenario is building on top of any kind of framework. As an example, if you are building a .Net 4.0 application, .Net 4.0 has hardware requirements vetted through Microsoft's hardware labs. Now your application requires at least the same hardware requirements that the .Net 4.0 framework requires. **Contextual Hardware Requirements** Most of the time when you're talking about hardware requirements what you are really talking about is how you support specific quality attribute scenarios. Things like performance, reliability, availability, and other -ilities. This is something I deal with often in making hardware recommendations for customers building applications on top of IBM InfoSphere Data Explorer (basically a Big Data search engine platform). Data Explorer's basic requirements are minimal (you can run it on a laptop), but hardware recommendations for any specific Big Data application (read: requirements) comes down to specific quality attribute scenarios for that application. How quickly should data be indexed? How many queries per second should be processed? How much down time is acceptable? Identifying specific quality attribute scenarios draws a line in the sand and lets me make a recommendation for minimum hardware requirements based on those scenarios -- X number of CPUs with Y amount of RAM, Z Gigabytes of hard drives, N redundant systems. In our case, we have basic formulas (determined through extensive testing in our hardware labs) that use assumptions from the quality attribute scenarios to help determine a starting point for a hardware recommendation. This recommendation becomes the requirement for that specific Big Data application. In this example, for any production system, a laptop really won't do even though it *technically* meets the "minimum" requirements. The context of that implementation -- the specific scenarios and data, whether it's running in production or not, and so on, dictate the hardware requirements. If the assumptions in the scenarios change, then so will the hardware requirements. So the phrase, "Y GB RAM is required to run the software properly," really means "Y GB of RAM is needed to crawl X million documents in Z hours or a rate of ABC docs/min." **Minimum Supported Hardware Requirements** That is, the hardware specifications expected to work correctly and that your Support group is prepared to help troubleshoot. Generally this is the set of hardware to which you have direct access, either your development machine or through a testing lab of some kind. One example of this is pretty much any Android app that has been released. As an Android developer you test your app through some software simulators, probably on at least a few physical devices. But there are 1000s of different devices running Android, many of which with little... quirks ...that could cause your app to run into problems. In most cases, you'll still offer support if a user runs into problems. And in most cases users won't run into problems even though you didn't specifically test on that hardware variation. Microsoft has this problem too with Windows -- how many different video card, motherboard, cpu, memory combinations are out there? Basically, identifying minimum supported hardware is like saying "this software works on my machine, I expect that it will work on machines similar to mine, lots of folks have used this software on lots of different machines without problems, your mileage may vary, and if you have a problem I'll do my best to help/fix but I can make no guarantees."
180,165
How do people define the minimum hardware requirements for software? For example: how can a software development company tell the customer that they will need 8 GB of RAM to run the program properly?
2012/12/20
[ "https://softwareengineering.stackexchange.com/questions/180165", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/75596/" ]
Hardware requirements fall into a couple of different buckets. Often you'll include requirements from a few of these buckets when determining specific hardware requirements for any software system you build. **Technical Constraints in the Architecture** These are the kinds of requirements that absolutely must be satisfied by the built system and are specifically designed into the system from the start. For example, "x86 processor is required." An easy example that comes to mind is Microsoft Office for Mac. Originally Macs used Power PC CPUs while Microsoft Windows was strictly targeted at "IBM Compatible" machines (mostly using x86 processors). Because Windows and thus Office only worked on x86, a completely new set of code (with different technical constraints) was written to support Office on Power PC for Mac OS. Once Mac moved to Intel x86 processors, the old Power PC optimized Office for Mac no longer worked -- and technical constraints once again changed for a new version of Office for Mac on Intel. Applications optimized for 32 vs. 64 bit is another easy example. **Implicit Hardware Requirements** Sometimes you don't actively choose to constrain yourself, but other decisions you make implicitly force requirements on to you. A common scenario is building on top of any kind of framework. As an example, if you are building a .Net 4.0 application, .Net 4.0 has hardware requirements vetted through Microsoft's hardware labs. Now your application requires at least the same hardware requirements that the .Net 4.0 framework requires. **Contextual Hardware Requirements** Most of the time when you're talking about hardware requirements what you are really talking about is how you support specific quality attribute scenarios. Things like performance, reliability, availability, and other -ilities. This is something I deal with often in making hardware recommendations for customers building applications on top of IBM InfoSphere Data Explorer (basically a Big Data search engine platform). Data Explorer's basic requirements are minimal (you can run it on a laptop), but hardware recommendations for any specific Big Data application (read: requirements) comes down to specific quality attribute scenarios for that application. How quickly should data be indexed? How many queries per second should be processed? How much down time is acceptable? Identifying specific quality attribute scenarios draws a line in the sand and lets me make a recommendation for minimum hardware requirements based on those scenarios -- X number of CPUs with Y amount of RAM, Z Gigabytes of hard drives, N redundant systems. In our case, we have basic formulas (determined through extensive testing in our hardware labs) that use assumptions from the quality attribute scenarios to help determine a starting point for a hardware recommendation. This recommendation becomes the requirement for that specific Big Data application. In this example, for any production system, a laptop really won't do even though it *technically* meets the "minimum" requirements. The context of that implementation -- the specific scenarios and data, whether it's running in production or not, and so on, dictate the hardware requirements. If the assumptions in the scenarios change, then so will the hardware requirements. So the phrase, "Y GB RAM is required to run the software properly," really means "Y GB of RAM is needed to crawl X million documents in Z hours or a rate of ABC docs/min." **Minimum Supported Hardware Requirements** That is, the hardware specifications expected to work correctly and that your Support group is prepared to help troubleshoot. Generally this is the set of hardware to which you have direct access, either your development machine or through a testing lab of some kind. One example of this is pretty much any Android app that has been released. As an Android developer you test your app through some software simulators, probably on at least a few physical devices. But there are 1000s of different devices running Android, many of which with little... quirks ...that could cause your app to run into problems. In most cases, you'll still offer support if a user runs into problems. And in most cases users won't run into problems even though you didn't specifically test on that hardware variation. Microsoft has this problem too with Windows -- how many different video card, motherboard, cpu, memory combinations are out there? Basically, identifying minimum supported hardware is like saying "this software works on my machine, I expect that it will work on machines similar to mine, lots of folks have used this software on lots of different machines without problems, your mileage may vary, and if you have a problem I'll do my best to help/fix but I can make no guarantees."
For some applications the requirements may actually be hard requirements, such as when the developer has analyzed or profiled their app and knows exactly how many megaflops, MIPS, polygons per second, array working set sizes, etc. are required to meet some specified performance benchmark. For small developers, cost may be the issue. They only have one system available, and so they declare that system's specs as the minimum, as they haven't been able to test the app on anything else (slower, smaller, etc.) and have little clue on how the app would do with less resources.
67,081,389
All of tags are changed to the below type of string on outlook web browser ``` [www.frimetime.com/verify/9026151fe8ddd0db4a9cb84e2ac0e7ce1a07ccd1be100896b2772e620b74ac16]Verify Now ``` It has to be. ``` <a href="www.frimetime.com/verify/9026151fe8ddd0db4a9cb84e2ac0e7ce1a07ccd1be100896b2772e620b74ac16">Verify Now</a> ``` \*\* The thing is it is working on Google(web browser) or mailbox as well \*\* The email server is using AWS smtp service. --- [![enter image description here](https://i.stack.imgur.com/LRqkD.png)](https://i.stack.imgur.com/LRqkD.png)
2021/04/13
[ "https://Stackoverflow.com/questions/67081389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14979586/" ]
Do you mean something like this? I hope I understood the question well. You can write a recursive function: ```js let string = "Lion, Unicorn, Unicorn"; let array1 = ["Lion", "Unicorn"]; let array2 = ["Fox", "Hound"]; function myCustomReplace(str, a1, a2) { let wordToReplace=a1.shift(); // a1[0] - if array change matters let replacementWord=a2.shift(); // a2[0] - if array change matters if (!wordToReplace || !replacementWord) return str; str=str.replaceAll(wordToReplace, replacementWord ); return myCustomReplace(str,a1,a2); // rturn myCustomReplace(str,a1.slice(1),a2.slice(1)) - if array change matters } console.log( myCustomReplace(string,array1,array2) ) ```
It's sometimes worthwhile to first transform the inputs into a shape that is easier to work on. For this problem, the input sentence is better thought of as an array of words, and the two arrays used for replacement are better represented as a single object mapping input words to output words... ```js let string = "Lion, Unicorn, Unicorn"; let array1 = ["Lion", "Unicorn"]; let array2 = ["Fox", "Hound"]; // transform the inputs let input = string.split(", "); let translator = array1.reduce((acc, key, i) => { acc[key] = array2[i]; return acc; }, {}); // now input is ['Lion', 'Unicorn', ...] // and transator is { 'Lion' : 'Fox', ... } // now the problem is just a two-liner, mapping the input over the translator let output = input.map(e => translator[e] || e) console.log(output.join(", ")) ```
67,081,389
All of tags are changed to the below type of string on outlook web browser ``` [www.frimetime.com/verify/9026151fe8ddd0db4a9cb84e2ac0e7ce1a07ccd1be100896b2772e620b74ac16]Verify Now ``` It has to be. ``` <a href="www.frimetime.com/verify/9026151fe8ddd0db4a9cb84e2ac0e7ce1a07ccd1be100896b2772e620b74ac16">Verify Now</a> ``` \*\* The thing is it is working on Google(web browser) or mailbox as well \*\* The email server is using AWS smtp service. --- [![enter image description here](https://i.stack.imgur.com/LRqkD.png)](https://i.stack.imgur.com/LRqkD.png)
2021/04/13
[ "https://Stackoverflow.com/questions/67081389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14979586/" ]
Do you mean something like this? I hope I understood the question well. You can write a recursive function: ```js let string = "Lion, Unicorn, Unicorn"; let array1 = ["Lion", "Unicorn"]; let array2 = ["Fox", "Hound"]; function myCustomReplace(str, a1, a2) { let wordToReplace=a1.shift(); // a1[0] - if array change matters let replacementWord=a2.shift(); // a2[0] - if array change matters if (!wordToReplace || !replacementWord) return str; str=str.replaceAll(wordToReplace, replacementWord ); return myCustomReplace(str,a1,a2); // rturn myCustomReplace(str,a1.slice(1),a2.slice(1)) - if array change matters } console.log( myCustomReplace(string,array1,array2) ) ```
If we use [`split(', ')`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) to convert the string to an array of single words, we can use [`map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) to replace them by searching for a pair with [`indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf): Please see comments in the code. A **one-liner** can be found at the end. ```js const string = "Lion, Unicorn, Unicorn"; const array1 = ["Lion", "Unicorn"]; const array2 = ["Fox", "Hound"]; // Split on ', ' let splitted = string.split(', '); // Map let result = splitted.map(w => { // Get position in array1 const i = array1.indexOf(w); // If we've found something if (i !== -1) { // Return replacement return array2[i]; } else { // Return original return w; } }); // Create string result = result.join(', '); // Show console.log(result); // Or, as a one-liner let result2 = string.split(', ').map(w => (array1.indexOf(w) !== -1) ? array2[array1.indexOf(w)] : w).join(', '); console.log(result2); ```
113,446
I am using ArcView (ArcGIS Desktop Basic) 10.1 and I need to perform a point distance analysis. What are the steps to determine the distance from A to B-Z, B to A-Z, C to A-Z, etc?
2014/09/11
[ "https://gis.stackexchange.com/questions/113446", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/36861/" ]
The following code is not polished but should work to create the same output table as the Point Distance tool but requires ArcGIS 10.1 (or later) for Desktop and only a Basic level license: ```py import arcpy,math # Set variables for input point feature classes and output table ptFC1 = "C:/temp/test.gdb/PointFC1" ptFC2 = "C:/temp/test.gdb/PointFC2" outGDB = "C:/temp/test.gdb" outTableName = "outTable" outTable = outGDB + "/" + outTableName arcpy.env.overwriteOutput = True # Create empty output table arcpy.CreateTable_management(outGDB,outTableName) arcpy.AddField_management(outTable,"INPUT_FID","LONG") arcpy.AddField_management(outTable,"NEAR_FID","LONG") arcpy.AddField_management(outTable,"DISTANCE","DOUBLE") # Create and populate two dictionaries with X and Y coordinates for each # OBJECTID in second feature class using a SearchCursor ptFC2XCoordDict = {} ptFC2YCoordDict = {} with arcpy.da.SearchCursor(ptFC2,["OBJECTID","SHAPE@XY"]) as cursor: for row in cursor: ptFC2XCoordDict[row[0]] = row[1][0] ptFC2YCoordDict[row[0]] = row[1][1] # Open an InsertCursor ready to have rows written for each pair of OBJECTIDs iCursor = arcpy.da.InsertCursor(outTable,["INPUT_FID","NEAR_FID","DISTANCE"]) # Use a SearchCursor to read the rows (and X,Y coordinates) of the first # feature class with arcpy.da.SearchCursor(ptFC1,["OBJECTID","SHAPE@XY"]) as cursor: for row in cursor: x1 = row[1][0] y1 = row[1][1] for i in range(len(ptFC2XCoordDict)): x2 = ptFC2XCoordDict[i+1] y2 = ptFC2YCoordDict[i+1] # Prepare and insert the InsertCursor row iRow = [row[0],i+1,math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1))] iCursor.insertRow(iRow) del iCursor print "Done!" ```
Using arcpy geometry objects is a good way to determine distances between features. Use data access cursors to access a feature's geometry and the method `angleAndDistanceTo` to determine distances. From my [blog](http://emilsarcpython.blogspot.com/2017/08/arcgis-point-distance-without-advanced.html): ``` import os import arcpy #inFeat is the path to your input feature class #nearFeat is the path to your near feature class #outTable is the path to the table that will be created by the function def PointDistance (inFeat, nearFeat, outTable): #create table tabPath, tabName = os.path.split (outTable) arcpy.CreateTable_management (tabPath, tabName) #add fields fldDi = {"INPUT_FID" : "LONG", "NEAR_FID" : "LONG", "DISTANCE" : "DOUBLE"} for fld in ["INPUT_FID", "NEAR_FID", "DISTANCE"]: arcpy.AddField_management (outTable, fld, fldDi [fld]) with arcpy.da.InsertCursor (outTable, ["INPUT_FID", "NEAR_FID", "DISTANCE" ]) as iCurs: with arcpy.da.SearchCursor (inFeat, ["OID@", "SHAPE@" ]) as inCurs: with arcpy.da.SearchCursor (nearFeat, ["OID@", "SHAPE@"] ) as nearCurs: for inOid, inGeom in inCurs: for nearOid, nearGeom in nearCurs: row = (inOid, nearOid, inGeom.distanceTo (nearGeom)) iCurs.insertRow (row) ```
48,301,533
I have the following code: ``` let fetcher = DiagnosticFetcher(commandSender: sender) fetcher.fetch() .observeOn(MainScheduler.instance) .subscribe( onNext: { self.store.save(content: $0) }, onError: { self.view.showError("Error") }, onCompleted: { log.verbose("Diagnostic fetched") }) ``` It does not compile: `Extra argument 'onError' in call`. I get the same error if I use `onSuccess` or `onDoesNotExistButShowTheBug` instead of `onNext`. The `fetch()` method returns a `Observable<String>` (whose last operator is a `reduce`). It seems that the `subscribe()` call expects only one lambda: ``` fetcher.fetch() .observeOn(MainScheduler.instance) .subscribe(onNext: { self.store.save(content: $0) }) ``` Results in: `Extraneous argument label 'onNext:' in call`. And: ``` fetcher.fetch() .observeOn(MainScheduler.instance) .subscribe({ self.store.save(content: $0) }) ``` compiles fine. I feel like I get the wrong `subscribe()` implementation. I want that one: ``` public func subscribe(onNext: ((ElementType) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil) -> Disposable { ``` but obviously, the compiler doesn't. I'm using XCode 9.2 with Swift 4 and RxSwift 4.1.1. I have other parts in my app that use the `onNext:onError:` on an observable where it works. I can't put my finger on what is different for this call. Any thought on how I can identify the root of the issue?
2018/01/17
[ "https://Stackoverflow.com/questions/48301533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15361/" ]
I got it to compile by specifying the first parameter in the `onError` lambda: ``` fetcher.fetch() .observeOn(MainScheduler.instance) .subscribe( onNext: { self.store.save(content: $0) }, onError: { _ in self.view.showError("Error")}) ```
Adding my contribution. I had the same issue but, in my case: ``` recordHeader.albumArray.asObservable() .subscribe(onNext: { [weak self] value in self?.populateView(recordHeader: value) }) .disposed(by: disposeBag) ``` The value type of the function "populateView" didn't match to value type of value
73,367,277
I tried to install turtle on my VS Code and got this error message, could you guys tell me what's going on with this module, please? ![error](https://i.stack.imgur.com/Tb370.png)
2022/08/15
[ "https://Stackoverflow.com/questions/73367277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19399657/" ]
Turtle is already included in the Python standard library. I am assuming that pip is trying to install a different package than you are looking for and your geting an error [Turtle](https://docs.python.org/3.7/library/turtle.html)
Which turtle do you want to install? If you mean this package, then you don't need to do any installation. [![enter image description here](https://i.stack.imgur.com/s55VY.png)](https://i.stack.imgur.com/s55VY.png) It already exists when you install Python.
42,548
On behalf of my advisor, I recently wrote a grant to obtain some specialized and expensive hardware. Is it ok to mention this on my CV, even though the grant is in my advisor's name and if yes, what would be a good way to word it ?
2015/03/29
[ "https://academia.stackexchange.com/questions/42548", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/27265/" ]
You can list on your CV whatever you think is useful information for the reader. In your case, whether something is useful depends on what your position in life is. If you're a full professor with a long history of funded research, what you describe is likely not useful to list on a CV. If you're a graduate student with an otherwise relatively short CV, then that's a different story. I would suggest wording such as > > Co-authored the proposal for grant XY-1234-5678 (PI: Professor Z). > > > Now, whether an entry such as this has any impact is a different issue, but it is certainly not going to hurt.
I wouldn't put this on a CV, but it is something that you should bring up during an interview as an example of your experience with the grant writing process. To elaborate on this: An individual is either a PI/Co-PI on a grant or they aren't. Some readers might read your CV and think that you're claiming undue credit. In recent months I've interviewed many candidates for a faculty position. Some of them had helped to write grant proposals in this way (and we would discuss this in an interview), but they didn't put those grants on their CV. Other candidates had submitted proposals as a PI/Co-PI, and they appropriately included this information on their CV's along with whether or not the grant was pending or had actually been funded. Listing proposals that were not funded is not something that I've seen on CV's that I've reviewed.
42,548
On behalf of my advisor, I recently wrote a grant to obtain some specialized and expensive hardware. Is it ok to mention this on my CV, even though the grant is in my advisor's name and if yes, what would be a good way to word it ?
2015/03/29
[ "https://academia.stackexchange.com/questions/42548", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/27265/" ]
**I would list all relevant grant activity on your CV.** Grant activity is something that many departments consider when considered people for academic appointments and it's often missing or hard to see. It is completely normal for graduate students to apply for grants with their advisors listed as PIs. Be honest about your role and about your advisors leadership role (I like [Wolfgan Bangerth's suggestion for wording](https://academia.stackexchange.com/a/42551/5962)) but do go ahead and include it. Bangerth is right that this kind of thing will be less useful for individuals further on in their career but I think it should still be included because it is relevant and it makes your CV a more complete record of your academic activity.
I wouldn't put this on a CV, but it is something that you should bring up during an interview as an example of your experience with the grant writing process. To elaborate on this: An individual is either a PI/Co-PI on a grant or they aren't. Some readers might read your CV and think that you're claiming undue credit. In recent months I've interviewed many candidates for a faculty position. Some of them had helped to write grant proposals in this way (and we would discuss this in an interview), but they didn't put those grants on their CV. Other candidates had submitted proposals as a PI/Co-PI, and they appropriately included this information on their CV's along with whether or not the grant was pending or had actually been funded. Listing proposals that were not funded is not something that I've seen on CV's that I've reviewed.
42,548
On behalf of my advisor, I recently wrote a grant to obtain some specialized and expensive hardware. Is it ok to mention this on my CV, even though the grant is in my advisor's name and if yes, what would be a good way to word it ?
2015/03/29
[ "https://academia.stackexchange.com/questions/42548", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/27265/" ]
You can list on your CV whatever you think is useful information for the reader. In your case, whether something is useful depends on what your position in life is. If you're a full professor with a long history of funded research, what you describe is likely not useful to list on a CV. If you're a graduate student with an otherwise relatively short CV, then that's a different story. I would suggest wording such as > > Co-authored the proposal for grant XY-1234-5678 (PI: Professor Z). > > > Now, whether an entry such as this has any impact is a different issue, but it is certainly not going to hurt.
**I would list all relevant grant activity on your CV.** Grant activity is something that many departments consider when considered people for academic appointments and it's often missing or hard to see. It is completely normal for graduate students to apply for grants with their advisors listed as PIs. Be honest about your role and about your advisors leadership role (I like [Wolfgan Bangerth's suggestion for wording](https://academia.stackexchange.com/a/42551/5962)) but do go ahead and include it. Bangerth is right that this kind of thing will be less useful for individuals further on in their career but I think it should still be included because it is relevant and it makes your CV a more complete record of your academic activity.
4,339,013
I have a javascript function that has been driving me nuts. This is the latest variation on the problem. If I put the code in line after the end of the form (i.e. after the tag, the code works just fine; but if I put a script reference to the code, it loads but doesn't execute. This works: ``` <script type="text/javascript"> var matchFieldName = 'dotmatch'; var resultFieldName = 'dotnumber'; var lookupURL = "/AutoSuggestJSTest/AutoSuggest.asmx/DOTFind"; var labelFieldName = "JobTitle"; var valueFieldName = "DOTNumber"; $('#' + matchFieldName).autocomplete({ source: function(request, response) { $.ajax({ type: "POST", url: lookupURL, contentType: 'application/json', dataType: "json", data: JSON.stringify({ prefixText: request.term, count: 20 }), success: function(data) { var output = jQuery.parseJSON(data.d); // var output = eval(data.d); response($.map(output, function(item) { var lbl = "item." + labelFieldName + " (item." + valueFieldName + ")"; var val = "item." + valueFieldName; return { // label: lbl, // value: val // label: eval('item.' + lableFieldName + '(item.' + valueFieldName + ')'), // value: eval('item.' + valueFieldName) label: item.JobTitle + "( " + item.DOTNumber + ")", value: item.DOTNumber } })); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); } }); }, minLength: 2, select: function(event, ui) { $('#' + resultFieldName).val(ui.item.value); return ui.item.label; } }); </script> </div> ``` But this doesn't: ``` </form> <div> <script type="text/javascript" src="js/DOTAutocomplete.js" /> </div> </body> ``` The only contents of the .js file are the lines that work. ARGH!!!
2010/12/02
[ "https://Stackoverflow.com/questions/4339013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95306/" ]
Self-closing `<script>` tags aren't valid, this: ``` <script type="text/javascript" src="js/DOTAutocomplete.js" /> ``` should be: ``` <script type="text/javascript" src="js/DOTAutocomplete.js"></script> ``` Also note that since you're using a selector `$('#' + matchFieldName)`, the file should either be included after that element is present, or wrap your code in a `document.ready` handler, for example: ``` $(function() { //your code... }); ```
Chances are that you're not targeting the file correctly. You're using type="text/javascript", right? If it works inline but not with a src reference, it's almost certainly that you're not nailing the path to the file.
4,339,013
I have a javascript function that has been driving me nuts. This is the latest variation on the problem. If I put the code in line after the end of the form (i.e. after the tag, the code works just fine; but if I put a script reference to the code, it loads but doesn't execute. This works: ``` <script type="text/javascript"> var matchFieldName = 'dotmatch'; var resultFieldName = 'dotnumber'; var lookupURL = "/AutoSuggestJSTest/AutoSuggest.asmx/DOTFind"; var labelFieldName = "JobTitle"; var valueFieldName = "DOTNumber"; $('#' + matchFieldName).autocomplete({ source: function(request, response) { $.ajax({ type: "POST", url: lookupURL, contentType: 'application/json', dataType: "json", data: JSON.stringify({ prefixText: request.term, count: 20 }), success: function(data) { var output = jQuery.parseJSON(data.d); // var output = eval(data.d); response($.map(output, function(item) { var lbl = "item." + labelFieldName + " (item." + valueFieldName + ")"; var val = "item." + valueFieldName; return { // label: lbl, // value: val // label: eval('item.' + lableFieldName + '(item.' + valueFieldName + ')'), // value: eval('item.' + valueFieldName) label: item.JobTitle + "( " + item.DOTNumber + ")", value: item.DOTNumber } })); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); } }); }, minLength: 2, select: function(event, ui) { $('#' + resultFieldName).val(ui.item.value); return ui.item.label; } }); </script> </div> ``` But this doesn't: ``` </form> <div> <script type="text/javascript" src="js/DOTAutocomplete.js" /> </div> </body> ``` The only contents of the .js file are the lines that work. ARGH!!!
2010/12/02
[ "https://Stackoverflow.com/questions/4339013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95306/" ]
Self-closing `<script>` tags aren't valid, this: ``` <script type="text/javascript" src="js/DOTAutocomplete.js" /> ``` should be: ``` <script type="text/javascript" src="js/DOTAutocomplete.js"></script> ``` Also note that since you're using a selector `$('#' + matchFieldName)`, the file should either be included after that element is present, or wrap your code in a `document.ready` handler, for example: ``` $(function() { //your code... }); ```
Try this, put this code back into an external file, make sure you have a valid script include tag, per Nick's post. ``` $(function(){ var matchFieldName = 'dotmatch'; var resultFieldName = 'dotnumber'; var lookupURL = "/AutoSuggestJSTest/AutoSuggest.asmx/DOTFind"; var labelFieldName = "JobTitle"; var valueFieldName = "DOTNumber"; $('#' + matchFieldName).autocomplete({ source: function(request, response) { $.ajax({ type: "POST", url: lookupURL, contentType: 'application/json', dataType: "json", data: JSON.stringify({ prefixText: request.term, count: 20 }), success: function(data) { var output = jQuery.parseJSON(data.d); // var output = eval(data.d); response($.map(output, function(item) { var lbl = "item." + labelFieldName + " (item." + valueFieldName + ")"; var val = "item." + valueFieldName; return { // label: lbl, // value: val // label: eval('item.' + lableFieldName + '(item.' + valueFieldName + ')'), // value: eval('item.' + valueFieldName) label: item.JobTitle + "( " + item.DOTNumber + ")", value: item.DOTNumber } })); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); } }); }, minLength: 2, select: function(event, ui) { $('#' + resultFieldName).val(ui.item.value); return ui.item.label; } }); }); ```
4,339,013
I have a javascript function that has been driving me nuts. This is the latest variation on the problem. If I put the code in line after the end of the form (i.e. after the tag, the code works just fine; but if I put a script reference to the code, it loads but doesn't execute. This works: ``` <script type="text/javascript"> var matchFieldName = 'dotmatch'; var resultFieldName = 'dotnumber'; var lookupURL = "/AutoSuggestJSTest/AutoSuggest.asmx/DOTFind"; var labelFieldName = "JobTitle"; var valueFieldName = "DOTNumber"; $('#' + matchFieldName).autocomplete({ source: function(request, response) { $.ajax({ type: "POST", url: lookupURL, contentType: 'application/json', dataType: "json", data: JSON.stringify({ prefixText: request.term, count: 20 }), success: function(data) { var output = jQuery.parseJSON(data.d); // var output = eval(data.d); response($.map(output, function(item) { var lbl = "item." + labelFieldName + " (item." + valueFieldName + ")"; var val = "item." + valueFieldName; return { // label: lbl, // value: val // label: eval('item.' + lableFieldName + '(item.' + valueFieldName + ')'), // value: eval('item.' + valueFieldName) label: item.JobTitle + "( " + item.DOTNumber + ")", value: item.DOTNumber } })); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); } }); }, minLength: 2, select: function(event, ui) { $('#' + resultFieldName).val(ui.item.value); return ui.item.label; } }); </script> </div> ``` But this doesn't: ``` </form> <div> <script type="text/javascript" src="js/DOTAutocomplete.js" /> </div> </body> ``` The only contents of the .js file are the lines that work. ARGH!!!
2010/12/02
[ "https://Stackoverflow.com/questions/4339013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95306/" ]
Self-closing `<script>` tags aren't valid, this: ``` <script type="text/javascript" src="js/DOTAutocomplete.js" /> ``` should be: ``` <script type="text/javascript" src="js/DOTAutocomplete.js"></script> ``` Also note that since you're using a selector `$('#' + matchFieldName)`, the file should either be included after that element is present, or wrap your code in a `document.ready` handler, for example: ``` $(function() { //your code... }); ```
As noted above by Mr. Craver, self-closing Javascript tags are no good. Here's a discussion on why: [Why don't self-closing script tags work?](https://stackoverflow.com/questions/69913/why-dont-self-closing-script-tags-work) There's no satisfying reason why - it's just that the SCRIPT tag isn't marked as having a content model of EMPTY in the spec - probably because the src attribute was added later.
4,339,013
I have a javascript function that has been driving me nuts. This is the latest variation on the problem. If I put the code in line after the end of the form (i.e. after the tag, the code works just fine; but if I put a script reference to the code, it loads but doesn't execute. This works: ``` <script type="text/javascript"> var matchFieldName = 'dotmatch'; var resultFieldName = 'dotnumber'; var lookupURL = "/AutoSuggestJSTest/AutoSuggest.asmx/DOTFind"; var labelFieldName = "JobTitle"; var valueFieldName = "DOTNumber"; $('#' + matchFieldName).autocomplete({ source: function(request, response) { $.ajax({ type: "POST", url: lookupURL, contentType: 'application/json', dataType: "json", data: JSON.stringify({ prefixText: request.term, count: 20 }), success: function(data) { var output = jQuery.parseJSON(data.d); // var output = eval(data.d); response($.map(output, function(item) { var lbl = "item." + labelFieldName + " (item." + valueFieldName + ")"; var val = "item." + valueFieldName; return { // label: lbl, // value: val // label: eval('item.' + lableFieldName + '(item.' + valueFieldName + ')'), // value: eval('item.' + valueFieldName) label: item.JobTitle + "( " + item.DOTNumber + ")", value: item.DOTNumber } })); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); } }); }, minLength: 2, select: function(event, ui) { $('#' + resultFieldName).val(ui.item.value); return ui.item.label; } }); </script> </div> ``` But this doesn't: ``` </form> <div> <script type="text/javascript" src="js/DOTAutocomplete.js" /> </div> </body> ``` The only contents of the .js file are the lines that work. ARGH!!!
2010/12/02
[ "https://Stackoverflow.com/questions/4339013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95306/" ]
Chances are that you're not targeting the file correctly. You're using type="text/javascript", right? If it works inline but not with a src reference, it's almost certainly that you're not nailing the path to the file.
As noted above by Mr. Craver, self-closing Javascript tags are no good. Here's a discussion on why: [Why don't self-closing script tags work?](https://stackoverflow.com/questions/69913/why-dont-self-closing-script-tags-work) There's no satisfying reason why - it's just that the SCRIPT tag isn't marked as having a content model of EMPTY in the spec - probably because the src attribute was added later.
4,339,013
I have a javascript function that has been driving me nuts. This is the latest variation on the problem. If I put the code in line after the end of the form (i.e. after the tag, the code works just fine; but if I put a script reference to the code, it loads but doesn't execute. This works: ``` <script type="text/javascript"> var matchFieldName = 'dotmatch'; var resultFieldName = 'dotnumber'; var lookupURL = "/AutoSuggestJSTest/AutoSuggest.asmx/DOTFind"; var labelFieldName = "JobTitle"; var valueFieldName = "DOTNumber"; $('#' + matchFieldName).autocomplete({ source: function(request, response) { $.ajax({ type: "POST", url: lookupURL, contentType: 'application/json', dataType: "json", data: JSON.stringify({ prefixText: request.term, count: 20 }), success: function(data) { var output = jQuery.parseJSON(data.d); // var output = eval(data.d); response($.map(output, function(item) { var lbl = "item." + labelFieldName + " (item." + valueFieldName + ")"; var val = "item." + valueFieldName; return { // label: lbl, // value: val // label: eval('item.' + lableFieldName + '(item.' + valueFieldName + ')'), // value: eval('item.' + valueFieldName) label: item.JobTitle + "( " + item.DOTNumber + ")", value: item.DOTNumber } })); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); } }); }, minLength: 2, select: function(event, ui) { $('#' + resultFieldName).val(ui.item.value); return ui.item.label; } }); </script> </div> ``` But this doesn't: ``` </form> <div> <script type="text/javascript" src="js/DOTAutocomplete.js" /> </div> </body> ``` The only contents of the .js file are the lines that work. ARGH!!!
2010/12/02
[ "https://Stackoverflow.com/questions/4339013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95306/" ]
Try this, put this code back into an external file, make sure you have a valid script include tag, per Nick's post. ``` $(function(){ var matchFieldName = 'dotmatch'; var resultFieldName = 'dotnumber'; var lookupURL = "/AutoSuggestJSTest/AutoSuggest.asmx/DOTFind"; var labelFieldName = "JobTitle"; var valueFieldName = "DOTNumber"; $('#' + matchFieldName).autocomplete({ source: function(request, response) { $.ajax({ type: "POST", url: lookupURL, contentType: 'application/json', dataType: "json", data: JSON.stringify({ prefixText: request.term, count: 20 }), success: function(data) { var output = jQuery.parseJSON(data.d); // var output = eval(data.d); response($.map(output, function(item) { var lbl = "item." + labelFieldName + " (item." + valueFieldName + ")"; var val = "item." + valueFieldName; return { // label: lbl, // value: val // label: eval('item.' + lableFieldName + '(item.' + valueFieldName + ')'), // value: eval('item.' + valueFieldName) label: item.JobTitle + "( " + item.DOTNumber + ")", value: item.DOTNumber } })); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); } }); }, minLength: 2, select: function(event, ui) { $('#' + resultFieldName).val(ui.item.value); return ui.item.label; } }); }); ```
As noted above by Mr. Craver, self-closing Javascript tags are no good. Here's a discussion on why: [Why don't self-closing script tags work?](https://stackoverflow.com/questions/69913/why-dont-self-closing-script-tags-work) There's no satisfying reason why - it's just that the SCRIPT tag isn't marked as having a content model of EMPTY in the spec - probably because the src attribute was added later.
48,968,873
I am writing a recursive function to find the index of a node in a linked list. It looks like this: ``` function indexAt(node, collection, linkedList) { let index = 0; if (node === nodeAt(index, linkedList,collection)) { return index } else { index ++ return indexAt(node, collection, linkedList) } } ``` It calls on the nodeAt function, which looks like this: ``` function nodeAt(index, linkedList, collection) { let node = collection[linkedList]; for (let i=0; i < index; i++) { node = next(node, collection) } return node } ``` This works fine when the index is 0, but when it is anything else, it increments the index, then sets it back to 0, entering an infinite loop. How can I fix this without fundamentally altering the code?
2018/02/24
[ "https://Stackoverflow.com/questions/48968873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8833196/" ]
Do you minimize it because you are busy with other things? You can use headless mode once your code is doing what you want visually and avoid this problem.
By the way you should try PhantomJs as the driver if minimizing the window is a big concern. It basically works the same way as the chrome driver but it uses no browser so all your code will run in the backgroud, it worked for me. It may work for you, happy coding! <http://phantomjs.org>
48,968,873
I am writing a recursive function to find the index of a node in a linked list. It looks like this: ``` function indexAt(node, collection, linkedList) { let index = 0; if (node === nodeAt(index, linkedList,collection)) { return index } else { index ++ return indexAt(node, collection, linkedList) } } ``` It calls on the nodeAt function, which looks like this: ``` function nodeAt(index, linkedList, collection) { let node = collection[linkedList]; for (let i=0; i < index; i++) { node = next(node, collection) } return node } ``` This works fine when the index is 0, but when it is anything else, it increments the index, then sets it back to 0, entering an infinite loop. How can I fix this without fundamentally altering the code?
2018/02/24
[ "https://Stackoverflow.com/questions/48968873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8833196/" ]
Do you minimize it because you are busy with other things? You can use headless mode once your code is doing what you want visually and avoid this problem.
As you mentioned *the test browser minimized, the new content does not load* is pretty much expected as *Selenium needs **focus** on the **Browsing Window** to interact with the DOM elements.* Reason ------ At this point it is worth to mention that *a webpage could **change its content** when the **focus is lost*** . You need to consider the fact *Selenium was mainly designed for testing*. Solution -------- Ideally, ***Automated Test Execution*** or ***Web Scraping*** must be performed within an isolated ***Test Environment*** preferably in a ***Test Lab*** configured with the required *Hardware* and *Software* configuration which must be free from ***Manual Intervention***.
102,605
Hi guys currently i am using Tooling Api to integrate a java app to Salesforce using Soap Api.I am making a callout for runtest() It's working fine with rest api but it doesn't work with soap i don't no how to make request for soap. Here is code for rest Api which i am able to implement. ``` /runTestsAsynchronous/ Body: {"tests":<tests array>} where tests array is [{ "classId" : "yourClassId", "testMethods" : ["testMethod1","testMethod2","testMethod3"] },{ "classId" : "yourOtherClassId", "testMethods" : ["testMethod1","testMethod2"] }]. ``` same request for Soap is not working
2015/12/16
[ "https://salesforce.stackexchange.com/questions/102605", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/26908/" ]
The SOAP version on the Tooling API doesn't currently have an equivalent web method that allows you to specify the testMethods to run in each apex class. See [RunTestsRequest](https://developer.salesforce.com/docs/atlas.en-us.200.0.apexcode.meta/apexcode/sforce_api_calls_runtests_request.htm), which is the parameter accepted by [`runTests()`](https://developer.salesforce.com/docs/atlas.en-us.200.0.apexcode.meta/apexcode/sforce_api_calls_runtests.htm). There is [`runTestsAsynchronous()`](https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/intro_soap_overview.htm#runTestsAsynchronous_example) in the Tooling API. It doesn't allow you to specify the methods to test (as at Spring '16). You can however defined the Apex class Ids or test Suite Ids. There is also an option to set the maxFailedTests. See the example code in [ApexTestQueueItem](https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/tooling_api_objects_apextestqueueitem.htm).
Did you try this example? This will give you the necessary Java class you need to call runtestAsynchronous() soap method whil also setting up the class and suite Ids. Unlike REST API you can not use a Test Array ID List, You can only pass in either suite Ids and/or class Ids. I hope this helps <https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/tooling_api_objects_apextestqueueitem.htm>
58,670,133
I have this functionality where user can add product to cart. e.g so user can add one product in cart after sometime the product gets deleted by the seller but still it is in the users cart, so if he checks out one product which has been deleted it will redirect him back to cart saying the product was deleted(one product works fine) but if he has two products in the cart one has been deleted and the other has not, and tries to check out he gets an error `trying to get property of non object`. So I'm looping over the product ids and checking if the product still exists in the database, but if that check fails for one, but not another I want the user to be redirected to the cart, so it should only checkout if no product fails. How can I do this ? **Controller** ```php public function store(Request $request) { foreach (session('cart') as $productId => $item) ; $product = product::find($productId); if (!$product) { return redirect()->route('cart') } //Insert into orders table $order = Order::create([ 'shipping_email' => $request->email, 'shipping_name' => $request->name, 'shipping_city' => $request->city, 'user_id' => auth()->user()->id, ]); //Insert into order product table if ($order) { $total = 0; foreach (session('cart') as $productId => $item) { if (empty($item)) { continue; } $product = product::find($productId); OrderProduct::create([ 'order_id' => $order->id ?? null, 'product_id' => $productId, // $products=DB::table('products')->where('id',$id)->get(); 'quantity' => $item['quantity'], 'Subtotal' => $item['price'] * $item['quantity'], 'total' => $total += $item['price'] * $item['quantity'], 'price' => $product->price, 'name' => $product->name, 'info' => $product->info, ]); } } } ```
2019/11/02
[ "https://Stackoverflow.com/questions/58670133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11710915/" ]
One approach, using `preg_match` with a capture group: ``` $input = "fishPrice/1572268723Career Portal.pdf"; preg_match("/.*\d{10}(.*)\.\w+$/", $input, $matches); echo $matches[1]; ``` This prints `Career Portal`. The regex logic here is to capture everything after the final 10 digit number sequence, but before the file extension.
Okay I worked on a little example for you. ``` $string = "fishPrice/1572268723Career Portal.pdf"; //Echo 1572268723Career Portal.pdf $string = substr($string, strpos($string, "/")+1); while(is_numeric($string[0])) { $string = substr($string, 1); } //Career Portal.pdf echo $string; ``` First of all, I substring to the / with should be always there as you said. Thereafter I will cut the numbers until I get a valid character, which will be the beginn of the name. Hope that helps!
58,670,133
I have this functionality where user can add product to cart. e.g so user can add one product in cart after sometime the product gets deleted by the seller but still it is in the users cart, so if he checks out one product which has been deleted it will redirect him back to cart saying the product was deleted(one product works fine) but if he has two products in the cart one has been deleted and the other has not, and tries to check out he gets an error `trying to get property of non object`. So I'm looping over the product ids and checking if the product still exists in the database, but if that check fails for one, but not another I want the user to be redirected to the cart, so it should only checkout if no product fails. How can I do this ? **Controller** ```php public function store(Request $request) { foreach (session('cart') as $productId => $item) ; $product = product::find($productId); if (!$product) { return redirect()->route('cart') } //Insert into orders table $order = Order::create([ 'shipping_email' => $request->email, 'shipping_name' => $request->name, 'shipping_city' => $request->city, 'user_id' => auth()->user()->id, ]); //Insert into order product table if ($order) { $total = 0; foreach (session('cart') as $productId => $item) { if (empty($item)) { continue; } $product = product::find($productId); OrderProduct::create([ 'order_id' => $order->id ?? null, 'product_id' => $productId, // $products=DB::table('products')->where('id',$id)->get(); 'quantity' => $item['quantity'], 'Subtotal' => $item['price'] * $item['quantity'], 'total' => $total += $item['price'] * $item['quantity'], 'price' => $product->price, 'name' => $product->name, 'info' => $product->info, ]); } } } ```
2019/11/02
[ "https://Stackoverflow.com/questions/58670133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11710915/" ]
With only one sample string, the pattern accuracy is speculative. My best guess is: ([Demo](https://3v4l.org/7af5v)) ``` $input = "fishPrice/1572268723Career Portal.pdf"; echo preg_match("~\d{10}\K[^.]+~", $input, $out) ? $out[0] : 'fail'; ``` Output: ``` Career Portal ``` Just match the non-dot characters after 10 digits. The `\K` means: forget the previously matched characters or "keep" the characters from this point. This spares the need to use a capture group. --- Alternatively, you could use a *potentially* more reliable non-regex technique. Here are two: ([Demo2](https://3v4l.org/KtPdT)) ``` echo ltrim(basename($input, '.pdf'), '0..9'); echo "\n---\n"; echo ltrim(pathinfo($input, PATHINFO_FILENAME), '0..9'); ``` Output: ``` Career Portal --- Career Portal ``` Isolate the filename, then left trim all digits.
Okay I worked on a little example for you. ``` $string = "fishPrice/1572268723Career Portal.pdf"; //Echo 1572268723Career Portal.pdf $string = substr($string, strpos($string, "/")+1); while(is_numeric($string[0])) { $string = substr($string, 1); } //Career Portal.pdf echo $string; ``` First of all, I substring to the / with should be always there as you said. Thereafter I will cut the numbers until I get a valid character, which will be the beginn of the name. Hope that helps!
46,377,720
I have an activity that consists of a tablayout of 3 tabs. Each tab is a fragment and all of them contains a pdf view to view different pdf files. I have written a class for Pdf Viewer. I need to call that class in numerous fragments to open pdf file in that fragment. But I'm not being able to pass the context properly and access that fragmet's PDFview. I'm using C.pdfviewer.PDFView as my PDFviewer. Here is my code: MyFragment.class ``` public class MyFragment extends Fragment { PDFView pdfView; String url = "mysite.pdf"; public MyFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_myfragment, container, false); pdfView = (PDFView)view.findViewById(R.id.pdfViewer); new RetrievePDFStream(this).execute(url); return view; } } ``` RetrievePDFStream.class ``` public class RetrievePDFStream extends AsyncTask<String, Void, byte[]> { public Fragment fContext; PDFView pdfView; public RetrievePDFStream(Fragment fContext) { this.fContext = fContext; } @Override protected byte[] doInBackground(String... strings) { InputStream inputStream = null; try { URL url = new URL(strings[0]); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); if (urlConnection.getResponseCode() == 200) { inputStream = new BufferedInputStream(urlConnection.getInputStream()); } } catch (IOException ex) { return null; } try { return IOUtils.toByteArray(inputStream); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(byte[] inputStream) { View view = fContext.getView(); pdfView = (PDFView)view.findViewById(R.id.pdfViewer); pdfView.fromBytes(inputStream).load(); } } ``` MyFragment.xml ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="app.nvest.helpinsure.Fragment.MyFragment" android:orientation="vertical" android:background="#000000"> <com.github.barteksc.pdfviewer.PDFView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/pdfViewer"/> </LinearLayout> ```
2017/09/23
[ "https://Stackoverflow.com/questions/46377720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6719239/" ]
You are trying to use a query object, but it seems you didn't create a mapped class to instantiate it. [Query documentation](http://docs.sqlalchemy.org/en/latest/orm/query.html?highlight=filter_by#the-query-object) [Mapping documentation](http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#declare-a-mapping) You should declare a class `Page` like the following to use this tool : ``` from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String Base = declarative_base() class Page(Base): __tablename__ = 'pages' uuid = Column(String, primary_key=True) ``` It doesn't need all columns defined in your table, at least the primary key and the columns you will use after in the filter, or in the output you want to create. Then you can use it to build the `session.query` : ``` pages = session.query(Page) test = pages.filter_by(uuid="1234").first() ``` --- Maybe it can be easier to create a simple `SELECT` query statement ? ``` session.execute("""SELECT * from pages WHERE uuid = '1234'""").first() ```
You are not using the uuid correctly. Please follow the declaration below. ``` from sqlalchemy.dialects.postgresql import UUID ... uuid = db.Column( UUID(as_uuid=True), nullable=False, index=True, unique=True, server_default=text("uuid_generate_v4()") ) ```
167,559
I currently have a error in my 1.9.3.2 store. When a customer wants to reset their password, the Magento Report error page is displayed. When check the report, I get the following error: ``` a:5:{i:0;s:156:"SQLSTATE[42S02]: Base table or view not found: 1146 Table 'customer_flowpassword' doesn't exist, query was: DESCRIBE `customer_flowpassword`";i:1;s:2832:"#0 /lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array) ``` Problem is related to the update to 1.9.3.2, where the table was not created. Should this solve the issue? ``` CREATE TABLE `customer_flowpassword` ( `flowpassword_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Flow password Id', `ip` varchar(50) NOT NULL COMMENT 'User IP', `email` varchar(255) NOT NULL COMMENT 'Requested email for change', `requested_date` varchar(255) NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Requested date for change', PRIMARY KEY (`flowpassword_id`), KEY `IDX_CUSTOMER_FLOWPASSWORD_EMAIL` (`email`), KEY `IDX_CUSTOMER_FLOWPASSWORD_IP` (`ip`), KEY `IDX_CUSTOMER_FLOWPASSWORD_REQUESTED_DATE` (`requested_date`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Customer flow password' AUTO_INCREMENT=9 ; ``` How can I solve that?
2017/04/04
[ "https://magento.stackexchange.com/questions/167559", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/16894/" ]
From Magento DevDocs: The sections that follow discuss requirements for one or two Magento file system owners. That means: **One user**: Typically necessary on shared hosting providers, which allow you to access only one user on the server This user can log in, transfer files using FTP, and this user also runs the web server. ``` find app/code var/view_preprocessed vendor pub/static app/etc generated/code generated/metadata \( -type f -or -type d \) -exec chmod u-w {} + && chmod o-rwx app/etc/env.php && chmod u+x bin/magento ``` **Two users**: We recommend two users if you run your own Magento server: one to transfer files and run command-line utilities, and a separate user for the web server software. When possible, this is preferable because it’s more secure. ``` find var generated pub/static pub/media app/etc -type f -exec chmod g+w {} + && find var generated pub/static pub/media app/etc -type d -exec chmod g+ws {} + ``` Check this DevDocs page for more info: <https://devdocs.magento.com/guides/v2.3/config-guide/prod/prod_file-sys-perms.html>
Run this command : ``` chmod -R 777 var/ pub/ ```