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
18,265
**TL;DR:** I drive to work at my own expense. My friend gets a free ride from me, saving her money and time. I say "don't be late" sometimes, and she freaks out. --- So I live in a metropolitan area and have a vehicle. I have a friend/coworker who ditched her car when she moved here so she takes the metro by default. She has been late before but I have too, and I have a history of oversleeping as I am a heavy sleeper. Sometimes, and infrequently, I will simply say when I will plan on picking her up from the metro (as she takes a much shorter metro ride to my place to get carpool ride vs taking the metro all the way to work) so will say something like "I'm leaving at 600. Don't be late!". For whatever reason, she freaks out that I have the audacity to say "don't be late" when I have overslept before, which I said last night and overslept today. I tried to explain that I'm not being a hypocrite and only say it as a friendly reminder, as we are not infallible but she's not having it. Some details: * I have a car, she does not * My commute is 20-30 min in my vehicle, her commute on metro is about an hour, her commute when carpooling is about 25-35 min (short metro ride and then carpool) * I spend a minimum of $70 in gas a month just commuting, she would spent at most $160 a month ($8 round trip per day x ~20 work days in a month) BUT she's part of a subsidy program for mass transit users which has a max allowance of $245/mo but I don't know how much she's receiving. * She does not pay me anything, ever. I don't ask but she never offers anything more than a "thanks". * Half the time, she doesn't even ride home with me because she decides to stay later to build credit hours at work or will make me wait for her * I was a GS-07 and she is a GS-09 (roughly $45k/year and $55k/year respectively, but I am a 09 now and she is becoming an 11 ($55 and $65 respectively). This is only relevant because she complains about money and not being able to afford the metro (despite the subsidy). * She also has another coworker that gives her rides (same situation but he lives close enough that he picks her up directly and she doesn't need the short metro ride over). It's not my fault she **GAVE** her car to her sister back at home. Just an example of how she acts, this one time she asked to stay 15 min later to build 15 min of credit hours, which is ridiculous if you ask me. I said I didn't want to but she insisted so I said okay and said I'll work on my project. I needed 15 min more than she did and when the first 15 min passed and she said she was done, I said I need 15 min more and she acted like that was ridiculous and she didn't want to have to wait for me, so we ended up staying 30 min past the work day. **How do I let her know that she's the one benefitting at my expense for something that is completely voluntary by myself and only serves to help her?** I refuse to stop asking her not to be late or to take back what I said before because I think I'm being perfectly reasonable. She thinks me saying that is "disrespectful and dictatorish". I'd prefer for this to not be the reason to end a friendship but I won't stand for disrespect. I don't mind this arrangement but I do mind her attitude. I think I'm only doing her a favor. Sure I oversleep sometimes but I literally have 35+ alarms set over a 60 min period between my phone and 5 different clocks. I know, ridiculous. So it's not like I try to oversleep. I have a half-hearted apology which I could do better but the reason I don't drop the subject is because she demands respect and acts like only she's in the right (mind you I don't have to give her rides at all and they're free for her).
2018/09/06
[ "https://interpersonal.stackexchange.com/questions/18265", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/21520/" ]
I have been in a similar situation with carpooling but we were always 3-4 people going together. The system that we used was quite simple. If you were not where you are supposed to be on time you got left behind as it is not fair for 3 other people to be late if you can't make it. At the end of the day you are the one doing a favour to that person. You set the rules. If she is not happy she doesn't have to carpool with you. Just stick to your schedule and offer rides if she wants them. You are under no obligation to stay late and wait for her or leave the moment she wants you to leave. I can tell you that nobody was late more than once as we were carpooling to a nearby town and it was generally a pain to get there if you missed the car.
If you want your colleague to be on time ---------------------------------------- First off, **try to always be on time yourself**. It's much easier to demand other people to be on time if you set an example. Second, stop calling it "carpooling". What you do is not really a case of car sharing, instead **you give her a ride**. Use this exact wording, e.g. "sorry I can't give you a ride tomorrow" or "I can give you a ride at 6:30". That should serve as a reminder that your colleague is the one to benefit from the arrangement. Finally, **announce the hours which suit you** often and make her agree: "I'm driving to work at 6:30 and plan to drive back at 5:00, is that OK?". If she says "no" you simply tell her she'll have to use the subway. If she agrees, that gives you a fresh argument against her being late in the morning or wanting to stay late in the evening. Alternatively ------------- Consider asking her to contribute to the rides. If you split gas expenses 50/50, perhaps it wouldn't be so much of a problem for you to occasionally wait for her 5-7 minutes in the morning when she's late, and stay 15 extra minutes in the evening when she has something urgent to finish.
54,672,959
I have the following data structure: ``` this.state = { active_menu: 2018, info: [ { key: 11, title: 'A', opened: false, content: [] }, { key: 10, title: 'B', opened: false, content: [] }, { key: 9, title: 'C', opened: false, content: [] }, { key: 1, title: 'D', opened: false, content: [] }], display: true } ``` Tell me, please, how is it possible with the value of `display:false` to remove (perhaps it can assign style display:none) elements with keys `11`, `10` and `9`? At `display:true` elements `11`, `10` and `9`should be visible, and the element with key `1` is hidden. Honestly I sit for the third day and can not decide. I ask for your help and would be grateful for any help...
2019/02/13
[ "https://Stackoverflow.com/questions/54672959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10825834/" ]
Maybe try appending a key and add the rest of the elements to the object before returning from the map. ```js var myObject = {"Timer13":{"Arm":0,"Mode":0},"Timer14":{"Arm":1,"Mode":1}} var result = Object.keys(myObject).map(elem => { return {timer: elem, ...myObject[elem]} }) console.log(result) ```
You can use [reduce](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/reduce) to achieve that playing with Current Value `(curr)` an Accumulator `(all)` also destructing your array can be helpful for a cleaner code. `[timer,obj]` timer : `curr[0]` and the obj is `curr[1]` ```js obj = { "Timer13": { "Arm": 0, "Mode": 0 }, "Timer14": { "Arm": 1, "Mode": 1 } } const res = Object.entries(obj).reduce((all, [timer, obj]) => { all.push({ timer, ...obj }) return all; }, []) console.log(res) ```
54,672,959
I have the following data structure: ``` this.state = { active_menu: 2018, info: [ { key: 11, title: 'A', opened: false, content: [] }, { key: 10, title: 'B', opened: false, content: [] }, { key: 9, title: 'C', opened: false, content: [] }, { key: 1, title: 'D', opened: false, content: [] }], display: true } ``` Tell me, please, how is it possible with the value of `display:false` to remove (perhaps it can assign style display:none) elements with keys `11`, `10` and `9`? At `display:true` elements `11`, `10` and `9`should be visible, and the element with key `1` is hidden. Honestly I sit for the third day and can not decide. I ask for your help and would be grateful for any help...
2019/02/13
[ "https://Stackoverflow.com/questions/54672959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10825834/" ]
You could get the entries and map new objects by assigning the parts. ```js var object = { Timer13: { Arm: 0, Mode: 0 }, Timer14: { Arm: 1, Mode: 1 } }, array = Object .entries(object) .map(([timer, values]) => Object.assign({ timer }, values)); console.log(array); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ```
You can use [reduce](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/reduce) to achieve that playing with Current Value `(curr)` an Accumulator `(all)` also destructing your array can be helpful for a cleaner code. `[timer,obj]` timer : `curr[0]` and the obj is `curr[1]` ```js obj = { "Timer13": { "Arm": 0, "Mode": 0 }, "Timer14": { "Arm": 1, "Mode": 1 } } const res = Object.entries(obj).reduce((all, [timer, obj]) => { all.push({ timer, ...obj }) return all; }, []) console.log(res) ```
54,672,959
I have the following data structure: ``` this.state = { active_menu: 2018, info: [ { key: 11, title: 'A', opened: false, content: [] }, { key: 10, title: 'B', opened: false, content: [] }, { key: 9, title: 'C', opened: false, content: [] }, { key: 1, title: 'D', opened: false, content: [] }], display: true } ``` Tell me, please, how is it possible with the value of `display:false` to remove (perhaps it can assign style display:none) elements with keys `11`, `10` and `9`? At `display:true` elements `11`, `10` and `9`should be visible, and the element with key `1` is hidden. Honestly I sit for the third day and can not decide. I ask for your help and would be grateful for any help...
2019/02/13
[ "https://Stackoverflow.com/questions/54672959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10825834/" ]
Maybe try appending a key and add the rest of the elements to the object before returning from the map. ```js var myObject = {"Timer13":{"Arm":0,"Mode":0},"Timer14":{"Arm":1,"Mode":1}} var result = Object.keys(myObject).map(elem => { return {timer: elem, ...myObject[elem]} }) console.log(result) ```
You could get the entries and map new objects by assigning the parts. ```js var object = { Timer13: { Arm: 0, Mode: 0 }, Timer14: { Arm: 1, Mode: 1 } }, array = Object .entries(object) .map(([timer, values]) => Object.assign({ timer }, values)); console.log(array); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ```
26,713,354
I got a problem.I have multiple callback functions . Function within function within a loop I want to execute very first function fully first . Then I want to move further. Currenlty no function is working fine: ``` function recurring_end() { var diffbot = new Diffbot('ddddd'); var sql= "SELECT `bookmarks`.`id`,`bookmarks`.`bookmark_url` as url FROM bookmarks LIMIT 0, 10"; connection.query(sql, function(err,bookmarks) { console.log(JSON.parse(JSON.stringify(bookmarks))); for(var i = 0; i< bookmarks.length; i++){ (function(i) { bookmark_id = bookmarks[i].id; bookmark_url = bookmarks[i].url; parseArticle(i,bookmark_id,bookmark_url,function(err,result){ bookamrk_title= result.bookmark_title; bookmark_body= result.body; bookmark_file_name= result.file_name; preview_image = result.preview_image; local_image_name = result.local_image_name; mainPreviewImage = result.mainPreviewImage; viewImage=result.viewImage; var mediaExist =result.mediaExist; if(mediaExist == 1) { console.log("Entered in Media Exist"); download(preview_image, "images/" + local_image_name, function() { console.log("Entered in download"); fs.exists("images/" + local_image_name, function(exists) { console.log("Before Sending " +mainPreviewImage); console.log("Before Sending Local " +local_image_name); ImageMagic(local_image_name,mainPreviewImage,223,147,function(err,result) { if(result != 0){ mainPreviewImage= result; console.log("Image Magic Done" +mainPreviewImage); AmazonUpload(mainPreviewImage,function(err,result) { console.log("Amazon error "+err); if(result != 0){ mainPreviewImage = result; console.log("First Image Uploading is Sucessfully"); /* Now Lets Pass View Image FROM Graphic Magic */ ImageMagic(mainPreviewImage,viewImage,152,100,function(err,result) { if(result != 0){ viewImage= result; /* Upload New View File to Amazon */ AmazonUpload(viewImage,function(err,result) { if(result != 0){ viewImage = result; console.log("Second Image Upload to Amazon"); /*Finally here we need to write update logic here check it out */ console.log("Serious id is "+i); console.log("Book Mark id " +bookmark_id); console.log("bookamrk_title" +bookamrk_title); console.log("preview_image"+mainPreviewImage); console.log("viewImage"+viewImage); console.log("End " +ddd); }else { /* need to write update Query here */ var viewImage="thumbnail_default_bookmark1.png"; } }); }else{ /* need to write update Query here */ var viewImage="thumbnail_default_bookmark1.png"; } }); }else { /* need to writeUpdate Query Here */ var mainPreviewImage= 'default_bookmark.png'; var viewImage="thumbnail_default_bookmark1.png"; } }); }else{ /* need to write Update Query here */ var mainPreviewImage= 'default_bookmark.png'; var viewImage="thumbnail_default_bookmark1.png"; } }); }); });/* download function closed */ } }); })(i); } console.log("Every Thing is done "); }); } function AmazonUpload(uploadImage,callback) { knox.putFile('images/'+uploadImage,'BookmarkPreviewImages/'+uploadImage, {"Content-Type": "image/jpeg",'x-amz-acl': 'public-read'}, function (err, result) { if(!err){ if(result.statusCode==200){ callback(err,uploadImage); }else{ callback(err,0); } }else{ callback(err,0); } }); } function download(uri, filename, callback) { request.head(uri, function(err, res, body) { //request(uri).pipe(fs.createWriteStream(filename),{end:true}).on('close', callback); var r = request(uri); r.pause() r.on('response', function (resp) { if(resp.statusCode === 200){ r.pipe(fs.createWriteStream(filename),{end:true}).on('close', callback); //pipe to where you want it to go r.resume() } }); }); }; function ImageMagic(local_image_name,display_image,width,height,callback){ console.log("local_image_name is"+local_image_name); gm('images/'+local_image_name).resize(width, height, '^').gravity('Center').crop(width, height).write('images/'+display_image, function (err) { if(!err){ console.log("Sucessfully Image converted is "+display_image); console.log("Sucessfully image which is converted "+ local_image_name); callback(null,display_image); }else{ console.log("Graphic Magic Error "+err); callback(err,0); } }); } function parseArticle(i,bookmark_id,bookmark_url,callback) { diffbot.article({uri: bookmark_url}, function(err, response) { var callBackString= {}; console.log("Diffbot Parsing URL with id " +bookmark_id+"and loop id is"+i); var bookmark_title = response.title; var body = response.html; var timestamp = new Date().getTime().toString(); var file_name = common_function.generateRandomString() + timestamp + '.txt'; var timestamp0 = new Date().getTime().toString(); var local_image_name = common_function.generateRandomString() + timestamp0 + i + '.jpg'; var preview_image = response.media[0]['link']; if(response.media[0].primary=='true'){ mainPreviewImage = "thumb_" + local_image_name; viewImage = "thumbnail_" + local_image_name; mediaExist=1; }else{ mainPreviewImage="default_bookmark.png"; viewImage="thumbnail_default_bookmark1.png"; mediaExist=0; } callBackString .bookmark_title=bookmark_title; callBackString.body = body; callBackString.file_name = file_name; callBackString.preview_image = preview_image; callBackString.local_image_name = local_image_name; callBackString.mainPreviewImage = mainPreviewImage; callBackString.viewImage=viewImage; callBackString.mediaExist =mediaExist; callback(null,callBackString); }); }; ``` I understand the code is too long. I want to get an idea, I want to execute `i=0` first completely, then I want to proceed further. Any Idea how we can do in Nodejs. Any Help Will be appreicated Thanks
2014/11/03
[ "https://Stackoverflow.com/questions/26713354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2904107/" ]
Try replacing the loop with a recursive code like this.. ``` function recurring_end() { var diffbot = new Diffbot('ddddd'); var sql= "SELECT `bookmarks`.`id`,`bookmarks`.`bookmark_url` as url FROM bookmarks LIMIT 0, 10"; connection.query(sql, function(err,bookmarks) { console.log(JSON.parse(JSON.stringify(bookmarks))); var i = 0; var callbackForParseArticle = function(err,result){ bookamrk_title= result.bookmark_title; bookmark_body= result.body; bookmark_file_name= result.file_name; preview_image = result.preview_image; local_image_name = result.local_image_name; mainPreviewImage = result.mainPreviewImage; viewImage=result.viewImage; var mediaExist =result.mediaExist; if(mediaExist == 1) { console.log("Entered in Media Exist"); download(preview_image, "images/" + local_image_name, function() { console.log("Entered in download"); fs.exists("images/" + local_image_name, function(exists) { console.log("Before Sending " +mainPreviewImage); console.log("Before Sending Local " +local_image_name); ImageMagic(local_image_name,mainPreviewImage,223,147,function(err,result) { if(result != 0){ mainPreviewImage= result; console.log("Image Magic Done" +mainPreviewImage); AmazonUpload(mainPreviewImage,function(err,result) { console.log("Amazon error "+err); if(result != 0){ mainPreviewImage = result; console.log("First Image Uploading is Sucessfully"); /* Now Lets Pass View Image FROM Graphic Magic */ ImageMagic(mainPreviewImage,viewImage,152,100,function(err,result) { if(result != 0){ viewImage= result; /* Upload New View File to Amazon */ AmazonUpload(viewImage,function(err,result) { if(result != 0){ viewImage = result; console.log("Second Image Upload to Amazon"); /*Finally here we need to write update logic here check it out */ console.log("Serious id is "+i); console.log("Book Mark id " +bookmark_id); console.log("bookamrk_title" +bookamrk_title); console.log("preview_image"+mainPreviewImage); console.log("viewImage"+viewImage); console.log("End " +ddd); }else { /* need to write update Query here */ var viewImage="thumbnail_default_bookmark1.png"; } //additional lines to the end of the function i++; if (i<bookmarks.length){ bookmark_id = bookmarks[i].id; bookmark_url = bookmarks[i].url; parseArticle(i,bookmark_id,bookmark_url,callbackForParseArticle); } else { console.log("Every Thing is done "); } }); }else{ /* need to write update Query here */ var viewImage="thumbnail_default_bookmark1.png"; } }); }else { /* need to writeUpdate Query Here */ var mainPreviewImage= 'default_bookmark.png'; var viewImage="thumbnail_default_bookmark1.png"; } }); }else{ /* need to write Update Query here */ var mainPreviewImage= 'default_bookmark.png'; var viewImage="thumbnail_default_bookmark1.png"; } }); }); });/* download function closed */ } }; if (bookmarks.length > 0){ parseArticle(i,bookmarks[i].id,bookmarks[i].url,callbackForParseArticle); } }); } function AmazonUpload(uploadImage,callback) { knox.putFile('images/'+uploadImage,'BookmarkPreviewImages/'+uploadImage, {"Content-Type": "image/jpeg",'x-amz-acl': 'public-read'}, function (err, result) { if(!err){ if(result.statusCode==200){ callback(err,uploadImage); }else{ callback(err,0); } }else{ callback(err,0); } }); } function download(uri, filename, callback) { request.head(uri, function(err, res, body) { //request(uri).pipe(fs.createWriteStream(filename),{end:true}).on('close', callback); var r = request(uri); r.pause() r.on('response', function (resp) { if(resp.statusCode === 200){ r.pipe(fs.createWriteStream(filename),{end:true}).on('close', callback); //pipe to where you want it to go r.resume() } }); }); }; function ImageMagic(local_image_name,display_image,width,height,callback){ console.log("local_image_name is"+local_image_name); gm('images/'+local_image_name).resize(width, height, '^').gravity('Center').crop(width, height).write('images/'+display_image, function (err) { if(!err){ console.log("Sucessfully Image converted is "+display_image); console.log("Sucessfully image which is converted "+ local_image_name); callback(null,display_image); }else{ console.log("Graphic Magic Error "+err); callback(err,0); } }); } function parseArticle(i,bookmark_id,bookmark_url,callback) { diffbot.article({uri: bookmark_url}, function(err, response) { var callBackString= {}; console.log("Diffbot Parsing URL with id " +bookmark_id+"and loop id is"+i); var bookmark_title = response.title; var body = response.html; var timestamp = new Date().getTime().toString(); var file_name = common_function.generateRandomString() + timestamp + '.txt'; var timestamp0 = new Date().getTime().toString(); var local_image_name = common_function.generateRandomString() + timestamp0 + i + '.jpg'; var preview_image = response.media[0]['link']; if(response.media[0].primary=='true'){ mainPreviewImage = "thumb_" + local_image_name; viewImage = "thumbnail_" + local_image_name; mediaExist=1; }else{ mainPreviewImage="default_bookmark.png"; viewImage="thumbnail_default_bookmark1.png"; mediaExist=0; } callBackString .bookmark_title=bookmark_title; callBackString.body = body; callBackString.file_name = file_name; callBackString.preview_image = preview_image; callBackString.local_image_name = local_image_name; callBackString.mainPreviewImage = mainPreviewImage; callBackString.viewImage=viewImage; callBackString.mediaExist =mediaExist; callback(null,callBackString); }); }; ```
Use [async.js](https://github.com/caolan/async) to manage your code flow If you have multiple functions, func\_1, func\_2, func\_3, that need to run in sequence, the code is ``` var async = require('async'); var functionList = [func_1, func_2, func_3]; async.series(functionList, function(err, result){ // results of func_1, func_2 and func_3 }); ```
7,366,287
I have a block of code: ``` passwordEditText.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { launch.performClick(); return true; } else { return false; } } }); ``` What I want is that when the enter key is pressed it performs the log in command (launch is the button that executes the log in). However, after executing the true block, it continues on to execute the else block as well, returning false and causing (only on some devices) the log in to occur a second time. So my question is in two parts: How can a if else statement evaluate as both true and false, and how can I make it so it doesn't do that. I have thought of a couple of tricks to make that happen but this seems to be a problem that is better understood then quickly patched.
2011/09/09
[ "https://Stackoverflow.com/questions/7366287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/706836/" ]
What you are seeing is the OnKey is fired twice, the first time for key down, and the second time for key up, so you have to filter it with ``` if (event.getAction()!=KeyEvent.ACTION_DOWN) { return true; } switch (keyCode) { case KeyEvent.KEYCODE_1 : //do something break; case KeyEvent.KEYCODE_2 : //do something break; case KeyEvent.KEYCODE_3 : //do something break; } return true; ```
What you describe is not possible. The code you posted looks correct, so I wonder if there's an error that's not in the snippet you posted. That said, some coding mistakes could lead a programmer to believe that both "if" and "else" blocks are being executed. E.g. ``` if(condition) { // do something } else; // note the semicolon here { // do something else // this gets executed regardless of whether the condition is true! } ``` But even then, if you have a "return" in your "if" block, there's no way you could get to the 2nd block :)
7,366,287
I have a block of code: ``` passwordEditText.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { launch.performClick(); return true; } else { return false; } } }); ``` What I want is that when the enter key is pressed it performs the log in command (launch is the button that executes the log in). However, after executing the true block, it continues on to execute the else block as well, returning false and causing (only on some devices) the log in to occur a second time. So my question is in two parts: How can a if else statement evaluate as both true and false, and how can I make it so it doesn't do that. I have thought of a couple of tricks to make that happen but this seems to be a problem that is better understood then quickly patched.
2011/09/09
[ "https://Stackoverflow.com/questions/7366287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/706836/" ]
The debugger can be misleading when a conditional outcome just leads to a return statement. Put in a useless 'int x variable' and have it assign x = 2 (say) before the return true and x = 3 (say) before the return false. Step through again in the debugger, I'll bet you see it entering only one of the blocks
What you describe is not possible. The code you posted looks correct, so I wonder if there's an error that's not in the snippet you posted. That said, some coding mistakes could lead a programmer to believe that both "if" and "else" blocks are being executed. E.g. ``` if(condition) { // do something } else; // note the semicolon here { // do something else // this gets executed regardless of whether the condition is true! } ``` But even then, if you have a "return" in your "if" block, there's no way you could get to the 2nd block :)
7,366,287
I have a block of code: ``` passwordEditText.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { launch.performClick(); return true; } else { return false; } } }); ``` What I want is that when the enter key is pressed it performs the log in command (launch is the button that executes the log in). However, after executing the true block, it continues on to execute the else block as well, returning false and causing (only on some devices) the log in to occur a second time. So my question is in two parts: How can a if else statement evaluate as both true and false, and how can I make it so it doesn't do that. I have thought of a couple of tricks to make that happen but this seems to be a problem that is better understood then quickly patched.
2011/09/09
[ "https://Stackoverflow.com/questions/7366287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/706836/" ]
try with this code... passwordEditText.setOnKeyListener(new OnKeyListener() { ``` public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { launch.performClick(); return true; } return false; } }); ```
What you describe is not possible. The code you posted looks correct, so I wonder if there's an error that's not in the snippet you posted. That said, some coding mistakes could lead a programmer to believe that both "if" and "else" blocks are being executed. E.g. ``` if(condition) { // do something } else; // note the semicolon here { // do something else // this gets executed regardless of whether the condition is true! } ``` But even then, if you have a "return" in your "if" block, there's no way you could get to the 2nd block :)
7,366,287
I have a block of code: ``` passwordEditText.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { launch.performClick(); return true; } else { return false; } } }); ``` What I want is that when the enter key is pressed it performs the log in command (launch is the button that executes the log in). However, after executing the true block, it continues on to execute the else block as well, returning false and causing (only on some devices) the log in to occur a second time. So my question is in two parts: How can a if else statement evaluate as both true and false, and how can I make it so it doesn't do that. I have thought of a couple of tricks to make that happen but this seems to be a problem that is better understood then quickly patched.
2011/09/09
[ "https://Stackoverflow.com/questions/7366287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/706836/" ]
What you are seeing is the OnKey is fired twice, the first time for key down, and the second time for key up, so you have to filter it with ``` if (event.getAction()!=KeyEvent.ACTION_DOWN) { return true; } switch (keyCode) { case KeyEvent.KEYCODE_1 : //do something break; case KeyEvent.KEYCODE_2 : //do something break; case KeyEvent.KEYCODE_3 : //do something break; } return true; ```
Multiple events are fired when a key is pressed (or held, or released). Specifically for a press and release the following are fired: ACTION\_DOWN ACTION\_DOWN (if held, with non-zero repeatCount, event possibly repeated multiple times) ACTION\_UP (possibly with the FLAG\_CANCELED set if the event was canceled) Your code does not check the action property and thus will be run every time an event is sent that involves the enter key. Replace ``` if (keyCode == KeyEvent.KEYCODE_ENTER) ``` with ``` if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) ``` if you only want this to fire once, when the key is released. Checking for the ACTION\_DOWN requires additional filtering to avoid multiple fires due to key repeating. You probably also want to check the status of the FLAG\_CANCELED when the ACTION\_UP occurs.
7,366,287
I have a block of code: ``` passwordEditText.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { launch.performClick(); return true; } else { return false; } } }); ``` What I want is that when the enter key is pressed it performs the log in command (launch is the button that executes the log in). However, after executing the true block, it continues on to execute the else block as well, returning false and causing (only on some devices) the log in to occur a second time. So my question is in two parts: How can a if else statement evaluate as both true and false, and how can I make it so it doesn't do that. I have thought of a couple of tricks to make that happen but this seems to be a problem that is better understood then quickly patched.
2011/09/09
[ "https://Stackoverflow.com/questions/7366287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/706836/" ]
What you are seeing is the OnKey is fired twice, the first time for key down, and the second time for key up, so you have to filter it with ``` if (event.getAction()!=KeyEvent.ACTION_DOWN) { return true; } switch (keyCode) { case KeyEvent.KEYCODE_1 : //do something break; case KeyEvent.KEYCODE_2 : //do something break; case KeyEvent.KEYCODE_3 : //do something break; } return true; ```
The debugger can be misleading when a conditional outcome just leads to a return statement. Put in a useless 'int x variable' and have it assign x = 2 (say) before the return true and x = 3 (say) before the return false. Step through again in the debugger, I'll bet you see it entering only one of the blocks
7,366,287
I have a block of code: ``` passwordEditText.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { launch.performClick(); return true; } else { return false; } } }); ``` What I want is that when the enter key is pressed it performs the log in command (launch is the button that executes the log in). However, after executing the true block, it continues on to execute the else block as well, returning false and causing (only on some devices) the log in to occur a second time. So my question is in two parts: How can a if else statement evaluate as both true and false, and how can I make it so it doesn't do that. I have thought of a couple of tricks to make that happen but this seems to be a problem that is better understood then quickly patched.
2011/09/09
[ "https://Stackoverflow.com/questions/7366287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/706836/" ]
What you are seeing is the OnKey is fired twice, the first time for key down, and the second time for key up, so you have to filter it with ``` if (event.getAction()!=KeyEvent.ACTION_DOWN) { return true; } switch (keyCode) { case KeyEvent.KEYCODE_1 : //do something break; case KeyEvent.KEYCODE_2 : //do something break; case KeyEvent.KEYCODE_3 : //do something break; } return true; ```
try with this code... passwordEditText.setOnKeyListener(new OnKeyListener() { ``` public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { launch.performClick(); return true; } return false; } }); ```
7,366,287
I have a block of code: ``` passwordEditText.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { launch.performClick(); return true; } else { return false; } } }); ``` What I want is that when the enter key is pressed it performs the log in command (launch is the button that executes the log in). However, after executing the true block, it continues on to execute the else block as well, returning false and causing (only on some devices) the log in to occur a second time. So my question is in two parts: How can a if else statement evaluate as both true and false, and how can I make it so it doesn't do that. I have thought of a couple of tricks to make that happen but this seems to be a problem that is better understood then quickly patched.
2011/09/09
[ "https://Stackoverflow.com/questions/7366287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/706836/" ]
The debugger can be misleading when a conditional outcome just leads to a return statement. Put in a useless 'int x variable' and have it assign x = 2 (say) before the return true and x = 3 (say) before the return false. Step through again in the debugger, I'll bet you see it entering only one of the blocks
Multiple events are fired when a key is pressed (or held, or released). Specifically for a press and release the following are fired: ACTION\_DOWN ACTION\_DOWN (if held, with non-zero repeatCount, event possibly repeated multiple times) ACTION\_UP (possibly with the FLAG\_CANCELED set if the event was canceled) Your code does not check the action property and thus will be run every time an event is sent that involves the enter key. Replace ``` if (keyCode == KeyEvent.KEYCODE_ENTER) ``` with ``` if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) ``` if you only want this to fire once, when the key is released. Checking for the ACTION\_DOWN requires additional filtering to avoid multiple fires due to key repeating. You probably also want to check the status of the FLAG\_CANCELED when the ACTION\_UP occurs.
7,366,287
I have a block of code: ``` passwordEditText.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { launch.performClick(); return true; } else { return false; } } }); ``` What I want is that when the enter key is pressed it performs the log in command (launch is the button that executes the log in). However, after executing the true block, it continues on to execute the else block as well, returning false and causing (only on some devices) the log in to occur a second time. So my question is in two parts: How can a if else statement evaluate as both true and false, and how can I make it so it doesn't do that. I have thought of a couple of tricks to make that happen but this seems to be a problem that is better understood then quickly patched.
2011/09/09
[ "https://Stackoverflow.com/questions/7366287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/706836/" ]
try with this code... passwordEditText.setOnKeyListener(new OnKeyListener() { ``` public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { launch.performClick(); return true; } return false; } }); ```
Multiple events are fired when a key is pressed (or held, or released). Specifically for a press and release the following are fired: ACTION\_DOWN ACTION\_DOWN (if held, with non-zero repeatCount, event possibly repeated multiple times) ACTION\_UP (possibly with the FLAG\_CANCELED set if the event was canceled) Your code does not check the action property and thus will be run every time an event is sent that involves the enter key. Replace ``` if (keyCode == KeyEvent.KEYCODE_ENTER) ``` with ``` if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) ``` if you only want this to fire once, when the key is released. Checking for the ACTION\_DOWN requires additional filtering to avoid multiple fires due to key repeating. You probably also want to check the status of the FLAG\_CANCELED when the ACTION\_UP occurs.
728,710
How would I go about replacing a defective hard drive in a RAID 5 array while keeping the data intact? I have a Highpoint Rocketraid 2720SGL RAID card.
2014/03/13
[ "https://superuser.com/questions/728710", "https://superuser.com", "https://superuser.com/users/307532/" ]
General answer: Normally, in RAID 5, you pull the broken drive. Then you insert a new drive in its place. Sometimes you have to tell the software to resync after that, but most hardware RAID cards do that just fine on their own. For your specific card: see page 12 [of the manual](http://www.highpoint-tech.com/PDF/rr2700/RR2720C2/RocketRAID%202720C2%20User%20Manual_v1.00.pdf) in how to add spare drives. Also read the part which says *"Spare Disks are used to automatically rebuild Redundant RAID arrays"*
I have not used that particular model, but other RAID controller cards from Highpoint. It should be as simple as removing the bad drive and inserting the new one and from the Rocketraid software telling the array to rebuild. If you do not have the software installed, or is incompatible with your OS (I know there were some issues with Linux a while back), you can boot to the RAID BIOS and tell it to rebuild from there.
43,699,936
Created an AWS AMI instance. I can telnet from the instance itself telnet [Pv4 Public IP] 9200 But not from my pc. This is my security group [![enter image description here](https://i.stack.imgur.com/MT6Z1.png)](https://i.stack.imgur.com/MT6Z1.png) What am I doing wrong?
2017/04/29
[ "https://Stackoverflow.com/questions/43699936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450602/" ]
You can check your Network ACL configurations. It looks like there is some other firewall in between your PC and server which is blocking you on 9200.
You said: "This is my SG", but...which way? Inbound or outbound? It can simply be that your host can't reply to your PC. Try to add a rule which adds **outbound** TCP ranging from ports 32768 to 65535 (ephemeral ports), so that the telnet server response packets can travel back to your PC. Otherwise, like the others said, look at one level up, VPC-level (network ACL).
43,699,936
Created an AWS AMI instance. I can telnet from the instance itself telnet [Pv4 Public IP] 9200 But not from my pc. This is my security group [![enter image description here](https://i.stack.imgur.com/MT6Z1.png)](https://i.stack.imgur.com/MT6Z1.png) What am I doing wrong?
2017/04/29
[ "https://Stackoverflow.com/questions/43699936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450602/" ]
You might have your acceptor process running on `127.0.0.1:9000` which means only local clients can connect. This is not related to your Security Group which could be wide open. Run `lsof -i:9000` if on unix. If you see something like this under `NAME` then host IP used to start your acceptor will needs to change from 127.0.0.1 to 0.0.0.0 (and secure via SG/FW). ``` COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME java 2777 ubuntu 148u IPv6 26856 0t0 TCP localhost:afs3-callback (LISTEN) ```
Need to ensure your SSH key you generated via IAM and attached to the EC2 at launch is added to the login: ``` ssh-add -K <yourkeyname>.pem ssh ubuntu@<yourdns or ip>.com == or == ssh ec2-user@<yourdns or ip> ```
43,699,936
Created an AWS AMI instance. I can telnet from the instance itself telnet [Pv4 Public IP] 9200 But not from my pc. This is my security group [![enter image description here](https://i.stack.imgur.com/MT6Z1.png)](https://i.stack.imgur.com/MT6Z1.png) What am I doing wrong?
2017/04/29
[ "https://Stackoverflow.com/questions/43699936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450602/" ]
You can check your Network ACL configurations. It looks like there is some other firewall in between your PC and server which is blocking you on 9200.
You can have a look at this [telnet-to a cloud instance from outside](https://stackoverflow.com/questions/15022448/telnet-to-a-cloud-instance-from-outside) The solution to problem was "Open the services and make the telnet manual and right click on it and chose start" As well make sure that the instance is residing in a public VPC
43,699,936
Created an AWS AMI instance. I can telnet from the instance itself telnet [Pv4 Public IP] 9200 But not from my pc. This is my security group [![enter image description here](https://i.stack.imgur.com/MT6Z1.png)](https://i.stack.imgur.com/MT6Z1.png) What am I doing wrong?
2017/04/29
[ "https://Stackoverflow.com/questions/43699936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450602/" ]
You might have your acceptor process running on `127.0.0.1:9000` which means only local clients can connect. This is not related to your Security Group which could be wide open. Run `lsof -i:9000` if on unix. If you see something like this under `NAME` then host IP used to start your acceptor will needs to change from 127.0.0.1 to 0.0.0.0 (and secure via SG/FW). ``` COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME java 2777 ubuntu 148u IPv6 26856 0t0 TCP localhost:afs3-callback (LISTEN) ```
A Telnet service is not installed by default on an Amazon Linux AMI. If you wish to use it, you will need to install it yourself, eg: [Install and Setup Telnet on EC2 Amazon Linux or CentOS](http://codingsteps.com/install-and-setup-telnet-on-ec2-amazon-linux-or-centos/). However, these days it is recommended to use `ssh` instead of `telnet` because it is more secure. See: [Telnet on wikipedia](https://en.wikipedia.org/wiki/Telnet)
43,699,936
Created an AWS AMI instance. I can telnet from the instance itself telnet [Pv4 Public IP] 9200 But not from my pc. This is my security group [![enter image description here](https://i.stack.imgur.com/MT6Z1.png)](https://i.stack.imgur.com/MT6Z1.png) What am I doing wrong?
2017/04/29
[ "https://Stackoverflow.com/questions/43699936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450602/" ]
If you can access port 80 via telnet or you're able to SSH in it's likely you have a [network ACL](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_ACLs.html) in place. If you can not access port 80 via telnet but you can via a browser it's like a local config - maybe AV or a firewall. EC2 instances use security groups for their [firewall](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/authorizing-access-to-an-instance.html) Another test to narrow down the the issue would to see if you could telnet from another instances in the same subenet in the same AZ. Being in the same subnet you should not be affected by a network ACL.
A Telnet service is not installed by default on an Amazon Linux AMI. If you wish to use it, you will need to install it yourself, eg: [Install and Setup Telnet on EC2 Amazon Linux or CentOS](http://codingsteps.com/install-and-setup-telnet-on-ec2-amazon-linux-or-centos/). However, these days it is recommended to use `ssh` instead of `telnet` because it is more secure. See: [Telnet on wikipedia](https://en.wikipedia.org/wiki/Telnet)
43,699,936
Created an AWS AMI instance. I can telnet from the instance itself telnet [Pv4 Public IP] 9200 But not from my pc. This is my security group [![enter image description here](https://i.stack.imgur.com/MT6Z1.png)](https://i.stack.imgur.com/MT6Z1.png) What am I doing wrong?
2017/04/29
[ "https://Stackoverflow.com/questions/43699936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450602/" ]
You can check your Network ACL configurations. It looks like there is some other firewall in between your PC and server which is blocking you on 9200.
Based on what you've described, there isn't really much else to work with. Your ability to telnet the public IP from the instance implies the server is listening on the external interface and your security group is already set to have the port open to all incoming connections. Aside from the trivial overlooking of not actually having the instance under the listed security group, the only possibility I can think of now is an active firewall on the instance. In the case of `iptables` or `ufw` (which is an interface to iptables), it's trivial to verify whether they are indeed getting in the way: ``` // List iptables access rules sudo iptables -L -v // List access rules via ufw sudo ufw status ```
43,699,936
Created an AWS AMI instance. I can telnet from the instance itself telnet [Pv4 Public IP] 9200 But not from my pc. This is my security group [![enter image description here](https://i.stack.imgur.com/MT6Z1.png)](https://i.stack.imgur.com/MT6Z1.png) What am I doing wrong?
2017/04/29
[ "https://Stackoverflow.com/questions/43699936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450602/" ]
You can have a look at this [telnet-to a cloud instance from outside](https://stackoverflow.com/questions/15022448/telnet-to-a-cloud-instance-from-outside) The solution to problem was "Open the services and make the telnet manual and right click on it and chose start" As well make sure that the instance is residing in a public VPC
You might have your acceptor process running on `127.0.0.1:9000` which means only local clients can connect. This is not related to your Security Group which could be wide open. Run `lsof -i:9000` if on unix. If you see something like this under `NAME` then host IP used to start your acceptor will needs to change from 127.0.0.1 to 0.0.0.0 (and secure via SG/FW). ``` COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME java 2777 ubuntu 148u IPv6 26856 0t0 TCP localhost:afs3-callback (LISTEN) ```
43,699,936
Created an AWS AMI instance. I can telnet from the instance itself telnet [Pv4 Public IP] 9200 But not from my pc. This is my security group [![enter image description here](https://i.stack.imgur.com/MT6Z1.png)](https://i.stack.imgur.com/MT6Z1.png) What am I doing wrong?
2017/04/29
[ "https://Stackoverflow.com/questions/43699936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450602/" ]
If you can access port 80 via telnet or you're able to SSH in it's likely you have a [network ACL](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_ACLs.html) in place. If you can not access port 80 via telnet but you can via a browser it's like a local config - maybe AV or a firewall. EC2 instances use security groups for their [firewall](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/authorizing-access-to-an-instance.html) Another test to narrow down the the issue would to see if you could telnet from another instances in the same subenet in the same AZ. Being in the same subnet you should not be affected by a network ACL.
You can have a look at this [telnet-to a cloud instance from outside](https://stackoverflow.com/questions/15022448/telnet-to-a-cloud-instance-from-outside) The solution to problem was "Open the services and make the telnet manual and right click on it and chose start" As well make sure that the instance is residing in a public VPC
43,699,936
Created an AWS AMI instance. I can telnet from the instance itself telnet [Pv4 Public IP] 9200 But not from my pc. This is my security group [![enter image description here](https://i.stack.imgur.com/MT6Z1.png)](https://i.stack.imgur.com/MT6Z1.png) What am I doing wrong?
2017/04/29
[ "https://Stackoverflow.com/questions/43699936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450602/" ]
You can check your Network ACL configurations. It looks like there is some other firewall in between your PC and server which is blocking you on 9200.
A Telnet service is not installed by default on an Amazon Linux AMI. If you wish to use it, you will need to install it yourself, eg: [Install and Setup Telnet on EC2 Amazon Linux or CentOS](http://codingsteps.com/install-and-setup-telnet-on-ec2-amazon-linux-or-centos/). However, these days it is recommended to use `ssh` instead of `telnet` because it is more secure. See: [Telnet on wikipedia](https://en.wikipedia.org/wiki/Telnet)
43,699,936
Created an AWS AMI instance. I can telnet from the instance itself telnet [Pv4 Public IP] 9200 But not from my pc. This is my security group [![enter image description here](https://i.stack.imgur.com/MT6Z1.png)](https://i.stack.imgur.com/MT6Z1.png) What am I doing wrong?
2017/04/29
[ "https://Stackoverflow.com/questions/43699936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450602/" ]
You can have a look at this [telnet-to a cloud instance from outside](https://stackoverflow.com/questions/15022448/telnet-to-a-cloud-instance-from-outside) The solution to problem was "Open the services and make the telnet manual and right click on it and chose start" As well make sure that the instance is residing in a public VPC
Need to ensure your SSH key you generated via IAM and attached to the EC2 at launch is added to the login: ``` ssh-add -K <yourkeyname>.pem ssh ubuntu@<yourdns or ip>.com == or == ssh ec2-user@<yourdns or ip> ```
211,885
When a script runs under Apache, I insert `$_SERVER['SERVER_NAME']` value into an error reporting e-mail message. However, if a Web script forks a "worker" job with `nohup php ...`, `$_SERVER['SERVER_NAME']` appears to be empty there. Thus, if an error occurs, it's reported without a host name. Can I reliably get the host name by means of PHP, without calling Unix `hostname` command?
2008/10/17
[ "https://Stackoverflow.com/questions/211885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6430/" ]
[php\_uname("n")](http://uk.php.net/manual/en/function.php-uname.php) > > (PHP 4 >= 4.0.2, PHP 5) > > php\_uname — Returns information about the > operating system PHP is running on > > > php\_uname() returns a description of the operating system PHP is > running on. This is the same string you see at the very top of the > phpinfo() output. For the name of just the operating system, consider > using the PHP\_OS constant, but keep in mind this constant will contain > the operating system PHP was built on. > > > On some older UNIX platforms, it may not be able to determine the > current OS information in which case it will revert to displaying the > OS PHP was built on. This will only happen if your uname() library > call either doesn't exist or doesn't work. > > >
You can use `_GLOBALS['MACHINENAME']` to obtain the information straight from the `globals` `array`.
211,885
When a script runs under Apache, I insert `$_SERVER['SERVER_NAME']` value into an error reporting e-mail message. However, if a Web script forks a "worker" job with `nohup php ...`, `$_SERVER['SERVER_NAME']` appears to be empty there. Thus, if an error occurs, it's reported without a host name. Can I reliably get the host name by means of PHP, without calling Unix `hostname` command?
2008/10/17
[ "https://Stackoverflow.com/questions/211885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6430/" ]
[php\_uname("n")](http://uk.php.net/manual/en/function.php-uname.php) > > (PHP 4 >= 4.0.2, PHP 5) > > php\_uname — Returns information about the > operating system PHP is running on > > > php\_uname() returns a description of the operating system PHP is > running on. This is the same string you see at the very top of the > phpinfo() output. For the name of just the operating system, consider > using the PHP\_OS constant, but keep in mind this constant will contain > the operating system PHP was built on. > > > On some older UNIX platforms, it may not be able to determine the > current OS information in which case it will revert to displaying the > OS PHP was built on. This will only happen if your uname() library > call either doesn't exist or doesn't work. > > >
For [PHP >= 5.3.0 use this](http://www.php.net/manual/en/function.gethostname.php): `$hostname = gethostname();` For [PHP < 5.3.0 but >= 4.2.0 use this](http://www.php.net/manual/en/function.php-uname.php): `$hostname = php_uname('n');` For PHP < 4.2.0 you can try one of these: ``` $hostname = getenv('HOSTNAME'); $hostname = trim(`hostname`); $hostname = preg_replace('#^\w+\s+(\w+).*$#', '$1', exec('uname -a')); ```
211,885
When a script runs under Apache, I insert `$_SERVER['SERVER_NAME']` value into an error reporting e-mail message. However, if a Web script forks a "worker" job with `nohup php ...`, `$_SERVER['SERVER_NAME']` appears to be empty there. Thus, if an error occurs, it's reported without a host name. Can I reliably get the host name by means of PHP, without calling Unix `hostname` command?
2008/10/17
[ "https://Stackoverflow.com/questions/211885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6430/" ]
For [PHP >= 5.3.0 use this](http://www.php.net/manual/en/function.gethostname.php): `$hostname = gethostname();` For [PHP < 5.3.0 but >= 4.2.0 use this](http://www.php.net/manual/en/function.php-uname.php): `$hostname = php_uname('n');` For PHP < 4.2.0 you can try one of these: ``` $hostname = getenv('HOSTNAME'); $hostname = trim(`hostname`); $hostname = preg_replace('#^\w+\s+(\w+).*$#', '$1', exec('uname -a')); ```
You can use `_GLOBALS['MACHINENAME']` to obtain the information straight from the `globals` `array`.
19,626,238
I am trying to create a data visualisation for some student related data (sample record below) but when d3 renders it, it goes through the data twice and overwrites it, leaving only the results for the second time through only on the screen. I am using a row counter here to so I have a way to set the y coord of each rectangle based how many rectangles there are. And I think this has somehow messed things up a little. Any help on how to make it so the data does not get iterated through twice would be greatly appreciated. Also, just in case it matters, this code is living within an angular.js directive. Apologies if I am just doing something really silly here ``` // student records sample... var studentData = [ { "studentID" : 1001, "firstName" : "jill", "lastName" : "smith", "workLoadDifficulty" : 16, "smileStartAngle" : -90, "smileEndAngle" : 90, }, { "studentID" : 1008, "firstName" : "bob", "lastName" : "smith", "workLoadDifficulty" : 99, "smileStartAngle" : 90, "smileEndAngle" : -90, } ]; (function () { 'use strict'; angular.module('learnerApp.directives') .directive('d3Bars', ['d3', function(d3) { return { restrict: 'EA', scope: { data: "=", label: "@", onClick: "&" }, link: function(scope, iElement, iAttrs) { var paddingForShape = 10; var rowCounter = -1; var height = 400; var width = 300; var svgContainer = d3.select(iElement[0]) .append("svg") .attr("width", width) .attr('height', height); // on window resize, re-render d3 canvas window.onresize = function() { return scope.$apply(); }; scope.$watch(function(){ return angular.element(window)[0].innerWidth; }, function(){ return scope.render(scope.data); } ); // watch for data changes and re-render scope.$watch('studentData', function(newVals, oldVals) { return scope.render(newVals); }, true); // define render function scope.render = function(data){ // remove all previous items before render svgContainer.selectAll("*").remove(); var workLoadColor = d3.scale.category10() .domain([0,100]) .range(['#02FA28', '#73FA87', '#C0FAC9','#FAE4C0', '#FAC775', '#FAA823','#FA9A00','#FA8288', '#FC4750', '#FA0511' ]) var studentRects = svgContainer.selectAll('rect') .data(studentData, function(d) { console.log(d.studentID); console.log('hello'); return "keyVal" + d.studentID; }) .enter() .append("rect"); var studentRectAttributes = studentRects .attr("x", function(d,i) { return ((i * 50) % width) + paddingForShape; }) .attr("y", function(d,i) { var value = ((i * 50) % width) if (value === 0) { rowCounter = rowCounter + 1; } var value = (rowCounter * 50); console.log('Y Val: ', i); console.log(value); return value; }) .attr("height", 30) .attr("width", 40) .style("fill", function(d) { return workLoadColor(d.workLoadDifficulty) }); }; } }; }]); }()); ```
2013/10/28
[ "https://Stackoverflow.com/questions/19626238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2926478/" ]
Change ``` System.out.print(i); ``` to ``` System.out.print(list.get(i)); ```
it is because you are print the int not the contents of the list, try changing the 3 line of the function printList to: ``` System.out.print(list.get(i)); ```
508,530
Have you seen or heard of the groups $\mathcal{A}(n)$ or $A(n)$ (for any integer $n$) described below? *This is the well-known construction*: Let $A$ be an abelian group. Then $A(p)$ is a subgroup which is the set of all elements $x\in A$ such that $ord(x) = p^k \ $ for some $k\in \mathbb{N}$. This, for prime $p$ that is, is a known construction talked about in Lang's Algebra. And if $A$ is torsion it's isomorphic to a direct sum of its nonzero $A(p)$ subgroups. Knowing that, what about $A(n)$ for any integer $n$? Let's see... *Here's the new construction that I'm wondering about:* Define $\mathcal{A}(n)$ to be the set of all elements that have an order that is a divisor of $n$. Then $\mathcal{A}(n)$ is a group. Proof: If $x \in \mathcal{A}(n)$, then $dx = 0 \implies 0 = d(-x). \ $ But $\forall m : mx = 0, ord(x) \mid m$, so $ord(-x) \mid d \mid n$, so $ord(-x) \mid n$. If $x, y \in \mathcal{A}(n)$, let $ord(x) = e, ord(y) = e$; let $c = lcm(d,e)$. Then $c(x+y) = 0$. But notice that any divisor of $lcd(d,e)$ divides $n$. So $x+y \in \mathcal{A}(n)$. QED. Then the $A(p) = \lim\_{k\rightarrow \infty}\mathcal{A}(p^k) = \cup\_k \mathcal{A}(p^k). \ $ That works for prime $p$, but also for any integer $n$. I.o.w. $A(n)$ is also a group. What do you guys think?
2013/09/29
[ "https://math.stackexchange.com/questions/508530", "https://math.stackexchange.com", "https://math.stackexchange.com/users/26327/" ]
Answer in not just $ -xe^{-\lambda x} $. Correct answer with limits is $ [-xe^{-\lambda x}]^{\infty} \_0$ + ${\int^{\infty}\_0e^{-\lambda x}dx}$ which turns out to be $1/\lambda.$ Explanation:Applying integration by parts (the correct way) $${\int{x\lambda}e^{-\lambda x}dx} = {}\lambda x {\int e^{-\lambda x}dx} - {\lambda}{\int}[{d(x)/dx}. {\int e^{-\lambda x}}]dx$$ Now apply limit and calculate $$ = [-xe^{-\lambda x}]^{\infty} \_0 + {\int^{\infty}\_0e^{-\lambda x}dx} $$ $$=1/\lambda$$
How to integrate: $$\int\_0^\infty x \, \lambda e^{-\lambda x} \, dx \Longrightarrow -\frac{1}{\lambda}\int\_0^\infty u\, e^{u} \, \Longrightarrow (-\frac{1}{\lambda})e^u(u + 1) + C \Longrightarrow -\frac{1}{\lambda}(e^{-\lambda x}(\lambda x - 1) + C)$$ 1) Choose $u = -\lambda x$. $-du = \lambda dx$. No need for integration by parts so early.
508,530
Have you seen or heard of the groups $\mathcal{A}(n)$ or $A(n)$ (for any integer $n$) described below? *This is the well-known construction*: Let $A$ be an abelian group. Then $A(p)$ is a subgroup which is the set of all elements $x\in A$ such that $ord(x) = p^k \ $ for some $k\in \mathbb{N}$. This, for prime $p$ that is, is a known construction talked about in Lang's Algebra. And if $A$ is torsion it's isomorphic to a direct sum of its nonzero $A(p)$ subgroups. Knowing that, what about $A(n)$ for any integer $n$? Let's see... *Here's the new construction that I'm wondering about:* Define $\mathcal{A}(n)$ to be the set of all elements that have an order that is a divisor of $n$. Then $\mathcal{A}(n)$ is a group. Proof: If $x \in \mathcal{A}(n)$, then $dx = 0 \implies 0 = d(-x). \ $ But $\forall m : mx = 0, ord(x) \mid m$, so $ord(-x) \mid d \mid n$, so $ord(-x) \mid n$. If $x, y \in \mathcal{A}(n)$, let $ord(x) = e, ord(y) = e$; let $c = lcm(d,e)$. Then $c(x+y) = 0$. But notice that any divisor of $lcd(d,e)$ divides $n$. So $x+y \in \mathcal{A}(n)$. QED. Then the $A(p) = \lim\_{k\rightarrow \infty}\mathcal{A}(p^k) = \cup\_k \mathcal{A}(p^k). \ $ That works for prime $p$, but also for any integer $n$. I.o.w. $A(n)$ is also a group. What do you guys think?
2013/09/29
[ "https://math.stackexchange.com/questions/508530", "https://math.stackexchange.com", "https://math.stackexchange.com/users/26327/" ]
How to integrate: $$\int\_0^\infty x \, \lambda e^{-\lambda x} \, dx \Longrightarrow -\frac{1}{\lambda}\int\_0^\infty u\, e^{u} \, \Longrightarrow (-\frac{1}{\lambda})e^u(u + 1) + C \Longrightarrow -\frac{1}{\lambda}(e^{-\lambda x}(\lambda x - 1) + C)$$ 1) Choose $u = -\lambda x$. $-du = \lambda dx$. No need for integration by parts so early.
Of course, $\lambda > 0$ must be assumed. Another way: $$ \lambda x e^{-\lambda x} = - \lambda \dfrac{\partial}{\partial\lambda} e^{-\lambda x}$$ $$ \eqalign{\int\_0^R \lambda x e^{-\lambda x} \; dx &= - \lambda \dfrac{d}{d\lambda} \int\_0^R e^{-\lambda x}\; dx = -\lambda \dfrac{d}{d\lambda} \left(\dfrac{1}{\lambda} - \dfrac{e^{-\lambda R}}{\lambda}\right) = \dfrac{1}{\lambda} + (\ldots) e^{-\lambda R}\cr &\to \dfrac{1}{\lambda} \text{ as } R \to \infty\cr} $$ And yet another, and more general: The Maclaurin series for $g(s) = \int\_0^\infty e^{(s-1) \lambda x}\; dx$ is $$ g(s) = \int\_0^\infty \sum\_{n=0}^\infty \dfrac{s^n \lambda^n x^n}{n!} e^{-\lambda x}\; dx = \sum\_{n=0}^\infty \dfrac{s^n}{n!} \int\_0^\infty \lambda^n x^n e^{-\lambda x}\; dx$$ But $$g(s) = \dfrac{1}{(1-s)\lambda} = \frac{1}{\lambda} \sum\_{n=0}^\infty s^n$$ so for nonnegative integers $n$ $$\int\_0^\infty \lambda^n x^n e^{-\lambda x}\; dx = \dfrac{n!}{\lambda}$$
508,530
Have you seen or heard of the groups $\mathcal{A}(n)$ or $A(n)$ (for any integer $n$) described below? *This is the well-known construction*: Let $A$ be an abelian group. Then $A(p)$ is a subgroup which is the set of all elements $x\in A$ such that $ord(x) = p^k \ $ for some $k\in \mathbb{N}$. This, for prime $p$ that is, is a known construction talked about in Lang's Algebra. And if $A$ is torsion it's isomorphic to a direct sum of its nonzero $A(p)$ subgroups. Knowing that, what about $A(n)$ for any integer $n$? Let's see... *Here's the new construction that I'm wondering about:* Define $\mathcal{A}(n)$ to be the set of all elements that have an order that is a divisor of $n$. Then $\mathcal{A}(n)$ is a group. Proof: If $x \in \mathcal{A}(n)$, then $dx = 0 \implies 0 = d(-x). \ $ But $\forall m : mx = 0, ord(x) \mid m$, so $ord(-x) \mid d \mid n$, so $ord(-x) \mid n$. If $x, y \in \mathcal{A}(n)$, let $ord(x) = e, ord(y) = e$; let $c = lcm(d,e)$. Then $c(x+y) = 0$. But notice that any divisor of $lcd(d,e)$ divides $n$. So $x+y \in \mathcal{A}(n)$. QED. Then the $A(p) = \lim\_{k\rightarrow \infty}\mathcal{A}(p^k) = \cup\_k \mathcal{A}(p^k). \ $ That works for prime $p$, but also for any integer $n$. I.o.w. $A(n)$ is also a group. What do you guys think?
2013/09/29
[ "https://math.stackexchange.com/questions/508530", "https://math.stackexchange.com", "https://math.stackexchange.com/users/26327/" ]
Answer in not just $ -xe^{-\lambda x} $. Correct answer with limits is $ [-xe^{-\lambda x}]^{\infty} \_0$ + ${\int^{\infty}\_0e^{-\lambda x}dx}$ which turns out to be $1/\lambda.$ Explanation:Applying integration by parts (the correct way) $${\int{x\lambda}e^{-\lambda x}dx} = {}\lambda x {\int e^{-\lambda x}dx} - {\lambda}{\int}[{d(x)/dx}. {\int e^{-\lambda x}}]dx$$ Now apply limit and calculate $$ = [-xe^{-\lambda x}]^{\infty} \_0 + {\int^{\infty}\_0e^{-\lambda x}dx} $$ $$=1/\lambda$$
Of course, $\lambda > 0$ must be assumed. Another way: $$ \lambda x e^{-\lambda x} = - \lambda \dfrac{\partial}{\partial\lambda} e^{-\lambda x}$$ $$ \eqalign{\int\_0^R \lambda x e^{-\lambda x} \; dx &= - \lambda \dfrac{d}{d\lambda} \int\_0^R e^{-\lambda x}\; dx = -\lambda \dfrac{d}{d\lambda} \left(\dfrac{1}{\lambda} - \dfrac{e^{-\lambda R}}{\lambda}\right) = \dfrac{1}{\lambda} + (\ldots) e^{-\lambda R}\cr &\to \dfrac{1}{\lambda} \text{ as } R \to \infty\cr} $$ And yet another, and more general: The Maclaurin series for $g(s) = \int\_0^\infty e^{(s-1) \lambda x}\; dx$ is $$ g(s) = \int\_0^\infty \sum\_{n=0}^\infty \dfrac{s^n \lambda^n x^n}{n!} e^{-\lambda x}\; dx = \sum\_{n=0}^\infty \dfrac{s^n}{n!} \int\_0^\infty \lambda^n x^n e^{-\lambda x}\; dx$$ But $$g(s) = \dfrac{1}{(1-s)\lambda} = \frac{1}{\lambda} \sum\_{n=0}^\infty s^n$$ so for nonnegative integers $n$ $$\int\_0^\infty \lambda^n x^n e^{-\lambda x}\; dx = \dfrac{n!}{\lambda}$$
30,051,455
I am producing a report of a subset of our products. Each of these products has an A4 page of details presented in a dashboard using excel. I have a number of stored procedures that excel uses to connect to my database and return the data. This data is then read by the dashboard which automatically updates. I need to produce this dashboard for each of over 100 products and combine them into one document. However, to update the data I currently have to go into each stored procedure connection and update the product ID manually. This is a slow task. Is there a way to use either SQL, Excel or VBA to improve this process? Perhaps a piece of VBA that reads a list of product IDs, updates each stored procedure in turn, saves the dashboard sheet as a PDF and repeats? EDIT: Excel connects to the data using the stored procedures through the built in connections tool under the data tab.
2015/05/05
[ "https://Stackoverflow.com/questions/30051455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4741952/" ]
There is no 'a' or 'h' in the input, so it will always call `return str.substring(0, 1) + FN(str.substring(1));` until the length is 0 : ``` FN("ello") = "e" + FN("llo") = "e" + "l" + FN("lo") = .... = "ello" ```
Your recursion each time takes the first letter of the remaining string: ``` "e" + FN("llo") = "e" + "l" + FN("lo") = "e" + "l" + "l" + FN("o") = "ello" ```
30,051,455
I am producing a report of a subset of our products. Each of these products has an A4 page of details presented in a dashboard using excel. I have a number of stored procedures that excel uses to connect to my database and return the data. This data is then read by the dashboard which automatically updates. I need to produce this dashboard for each of over 100 products and combine them into one document. However, to update the data I currently have to go into each stored procedure connection and update the product ID manually. This is a slow task. Is there a way to use either SQL, Excel or VBA to improve this process? Perhaps a piece of VBA that reads a list of product IDs, updates each stored procedure in turn, saves the dashboard sheet as a PDF and repeats? EDIT: Excel connects to the data using the stored procedures through the built in connections tool under the data tab.
2015/05/05
[ "https://Stackoverflow.com/questions/30051455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4741952/" ]
There is no 'a' or 'h' in the input, so it will always call `return str.substring(0, 1) + FN(str.substring(1));` until the length is 0 : ``` FN("ello") = "e" + FN("llo") = "e" + "l" + FN("lo") = .... = "ello" ```
Use ``` str.substring(0, 2)// instead of str.substring(0, 1) ```
73,450,293
I have this question on a form that needs to be validated, which I'm trying to do below: ``` <div class="question"> <div class="row"> <h5>1. Requestors Name (Your name or JHED ID)</h5><p class="required">*</p> </div> <input type="text" class="form-control" id="requestorName" name="requestorName" required minlength="2" [(ngModel)]="model.requestorName" #requestorName="ngModel"/> </div> <div *ngIf="requestorName.invalid && (requestorName.dirty || requestorName.touched)" class="alert"> <div *ngIf="requestorName.errors?.['required']"> Requester name is required. </div> <div *ngIf="requestorName.errors?.['minlength']"> Requester name must be at least 2 characters long. </div> </div> ``` I made this using the examples here: <https://angular.io/guide/form-validation> However, when I try to load the page I get this error: ``` NG5002: Parser Error: Expected identifier for property access at the end of the expression [requesterName.errors?.['minlength']] ``` If I remove the min length div I still get the same exact error but for expression `[requesterName.errors?.['required']]` What am I missing or what have I done wrong here? There are a lot of similar questions on this, but they all have solutions that say something like "use `*ngIf="email.errors?.['required']"`" as in this question: [Angular validation error: Property Required, and Parser Error](https://stackoverflow.com/questions/71264334/angular-validation-error-property-required-and-parser-error) but I'm already doing that. What is different in mine?
2022/08/22
[ "https://Stackoverflow.com/questions/73450293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14108804/" ]
Try `requesterName?.errors?.required`
You're using two different variables: **requesterName** and **requestorName** ``` <input type="text" class="form-control" id="requestorName" name="requestorName" required minlength="2" [(ngModel)]="model.requestorName" #requesterName="ngModel"/> ```
69,230
Under Natty I had a lovely .icc calibration file for my laptop's screen. It's awful without it. Under Oneiric, when I go to 'Color' in the settings manager only my webcam is listed in the devices that can be colour managed. So I can't install my .icc profile. I've installed all the gcm/argyl stuff but that hasn't got me anywhere either. How can I (re)install my colour profile? (I now consider this a bug. Report [filed on launchpad](https://bugs.launchpad.net/ubuntu/+source/gnome-color-manager/+bug/881396), please mark it as affecting you if it does)
2011/10/19
[ "https://askubuntu.com/questions/69230", "https://askubuntu.com", "https://askubuntu.com/users/28930/" ]
Until this bug is fixed, you can load your colour profile manually with ``` dispwin your_colour_profile.icc ``` (so you can put that in a script in your your autostart folder)
Go to System Settings > Color Select your monitor click add profile use the drop down list to select other navigate to a compatible .icc profile and then click import then click add
69,230
Under Natty I had a lovely .icc calibration file for my laptop's screen. It's awful without it. Under Oneiric, when I go to 'Color' in the settings manager only my webcam is listed in the devices that can be colour managed. So I can't install my .icc profile. I've installed all the gcm/argyl stuff but that hasn't got me anywhere either. How can I (re)install my colour profile? (I now consider this a bug. Report [filed on launchpad](https://bugs.launchpad.net/ubuntu/+source/gnome-color-manager/+bug/881396), please mark it as affecting you if it does)
2011/10/19
[ "https://askubuntu.com/questions/69230", "https://askubuntu.com", "https://askubuntu.com/users/28930/" ]
I am having a similar issue in Ubuntu Gnome 15.10 (Gnome 3.18). NOTE: I already had an .icc file for my display. I was able to manually apply it to my unlisted display with the following command: ``` # dispwin -d 2 ./Dell_3007WFP-5000.icm ``` -d 2 specified the 2nd display (1st was my laptop built-in display) Hope this helps somebody!
Go to System Settings > Color Select your monitor click add profile use the drop down list to select other navigate to a compatible .icc profile and then click import then click add
69,230
Under Natty I had a lovely .icc calibration file for my laptop's screen. It's awful without it. Under Oneiric, when I go to 'Color' in the settings manager only my webcam is listed in the devices that can be colour managed. So I can't install my .icc profile. I've installed all the gcm/argyl stuff but that hasn't got me anywhere either. How can I (re)install my colour profile? (I now consider this a bug. Report [filed on launchpad](https://bugs.launchpad.net/ubuntu/+source/gnome-color-manager/+bug/881396), please mark it as affecting you if it does)
2011/10/19
[ "https://askubuntu.com/questions/69230", "https://askubuntu.com", "https://askubuntu.com/users/28930/" ]
Until this bug is fixed, you can load your colour profile manually with ``` dispwin your_colour_profile.icc ``` (so you can put that in a script in your your autostart folder)
I am having a similar issue in Ubuntu Gnome 15.10 (Gnome 3.18). NOTE: I already had an .icc file for my display. I was able to manually apply it to my unlisted display with the following command: ``` # dispwin -d 2 ./Dell_3007WFP-5000.icm ``` -d 2 specified the 2nd display (1st was my laptop built-in display) Hope this helps somebody!
573,071
I am looking to see if there is an application for reading kindle books on this system.
2015/01/13
[ "https://askubuntu.com/questions/573071", "https://askubuntu.com", "https://askubuntu.com/users/368161/" ]
You can use the [Kindle Cloud Reader for Chrome](https://chrome.google.com/webstore/detail/kindle-cloud-reader/icdipabjmbhpdkjaihfjoikhjjeneebd?utm_source=chrome-app-launcher-info-dialog).
[Calibre](https://apps.ubuntu.com/cat/applications/calibre) [![Install Calibre](https://hostmar.co/software-small)](https://apps.ubuntu.com/cat/applications/calibre) has a reader in it and can also convert between formats.
24,909,466
How can i assign the javascript variable in to php. ``` $("button").click(function() { var val = (this.id); $.ajax ({ url: "date.php", //data: { val : val }, data:'q=' + val, type: "GET", success: function(result) { if(result==1) { page = "<?php echo $today;?>"; } else if(result==2) { page = "<?php echo $this_week;?>"; } else if(result==3) { page="<?php echo $this_month;?>"; } else if(result==4) { page="<?php echo $previous_month;?>"; } else { "<?php echo $today;?>"; } } }); }); ``` Here i want to pass the variable 'page' to php,for to assign the export excel filename.I done like this in php ``` <?php $page = ('<script type="text/javascript">page</script>'); ?> ``` $page variable i want to assign here. ``` <script> saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), "<?php echo $name[0] ?>- Report-<?php echo $page?>.xlsx"); }; </script> ``` But am getting error,otherwise any other method to assign the variable. my date.php ``` <?php $var=$_GET['q']; if($var == 'getToday') { echo "1"; } elseif($var =='getWeek') { echo "2"; } else if($var =='getMonth') { echo "3"; } else if($var =='getpremon') { echo "4"; } else { echo "5"; } ?> ```
2014/07/23
[ "https://Stackoverflow.com/questions/24909466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3864156/" ]
Yes it does, all you have to do is add this line on your config.xml file : ``` <access origin="http://example.com" /> ``` You can also do this : ``` <access origin="*" /> ``` But it's safer to specify the domain you're sending requests to. If you need more information check this [page](http://docs.phonegap.com/en/1.8.0rc1/guide_whitelist_index.md.html#Domain%20Whitelist%20Guide) on the PhoneGap doc.
I changed the tomcat filter in my server. I modified the Origin header of the request inside my custom filter and it works. I dont know wether this is the right way to do things but I this is the only thing to get it working.
24,909,466
How can i assign the javascript variable in to php. ``` $("button").click(function() { var val = (this.id); $.ajax ({ url: "date.php", //data: { val : val }, data:'q=' + val, type: "GET", success: function(result) { if(result==1) { page = "<?php echo $today;?>"; } else if(result==2) { page = "<?php echo $this_week;?>"; } else if(result==3) { page="<?php echo $this_month;?>"; } else if(result==4) { page="<?php echo $previous_month;?>"; } else { "<?php echo $today;?>"; } } }); }); ``` Here i want to pass the variable 'page' to php,for to assign the export excel filename.I done like this in php ``` <?php $page = ('<script type="text/javascript">page</script>'); ?> ``` $page variable i want to assign here. ``` <script> saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), "<?php echo $name[0] ?>- Report-<?php echo $page?>.xlsx"); }; </script> ``` But am getting error,otherwise any other method to assign the variable. my date.php ``` <?php $var=$_GET['q']; if($var == 'getToday') { echo "1"; } elseif($var =='getWeek') { echo "2"; } else if($var =='getMonth') { echo "3"; } else if($var =='getpremon') { echo "4"; } else { echo "5"; } ?> ```
2014/07/23
[ "https://Stackoverflow.com/questions/24909466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3864156/" ]
Yes it does, all you have to do is add this line on your config.xml file : ``` <access origin="http://example.com" /> ``` You can also do this : ``` <access origin="*" /> ``` But it's safer to specify the domain you're sending requests to. If you need more information check this [page](http://docs.phonegap.com/en/1.8.0rc1/guide_whitelist_index.md.html#Domain%20Whitelist%20Guide) on the PhoneGap doc.
Given below is the code in Tomcat CORS filter, so new URI with Origin as "file://" throws `URISyntaxException` which results in 403 `protected static boolean isValidOrigin(String origin) { URI originURI; try { originURI = new URI(origin); } catch (URISyntaxException e) { return false; } return originURI.getScheme() != null; }` Someone has tried to override this filter in the below link. <https://github.com/sebastienblanc/cors-filter/blob/master/src/main/java/org/ebaysf/web/cors/CORSFilter.java#L825>
24,909,466
How can i assign the javascript variable in to php. ``` $("button").click(function() { var val = (this.id); $.ajax ({ url: "date.php", //data: { val : val }, data:'q=' + val, type: "GET", success: function(result) { if(result==1) { page = "<?php echo $today;?>"; } else if(result==2) { page = "<?php echo $this_week;?>"; } else if(result==3) { page="<?php echo $this_month;?>"; } else if(result==4) { page="<?php echo $previous_month;?>"; } else { "<?php echo $today;?>"; } } }); }); ``` Here i want to pass the variable 'page' to php,for to assign the export excel filename.I done like this in php ``` <?php $page = ('<script type="text/javascript">page</script>'); ?> ``` $page variable i want to assign here. ``` <script> saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), "<?php echo $name[0] ?>- Report-<?php echo $page?>.xlsx"); }; </script> ``` But am getting error,otherwise any other method to assign the variable. my date.php ``` <?php $var=$_GET['q']; if($var == 'getToday') { echo "1"; } elseif($var =='getWeek') { echo "2"; } else if($var =='getMonth') { echo "3"; } else if($var =='getpremon') { echo "4"; } else { echo "5"; } ?> ```
2014/07/23
[ "https://Stackoverflow.com/questions/24909466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3864156/" ]
Yes it does, all you have to do is add this line on your config.xml file : ``` <access origin="http://example.com" /> ``` You can also do this : ``` <access origin="*" /> ``` But it's safer to specify the domain you're sending requests to. If you need more information check this [page](http://docs.phonegap.com/en/1.8.0rc1/guide_whitelist_index.md.html#Domain%20Whitelist%20Guide) on the PhoneGap doc.
The solution of Taher solved my problem with PhoneGap+jQuery accessing a tomcat web-service. Just included the referenced java code (<https://github.com/sebastienblanc/cors-filter/blob/master/src/main/java/org/ebaysf/web/cors/CORSFilter.java#L825>) in my project and added the next lines to the web.xml of the project. Redeployed it and that's it. (No corsFilter needed in Tomcat's web.xml.) Now it works both for PhoneGap requests and browser request. This definitively is some TomCat (or PhoneGap?) bug. ``` <filter> <filter-name>CorsFilter</filter-name> <filter-class>myDeploymentName.CORSFilter</filter-class> <init-param> <param-name>cors.allowed.origins</param-name> <param-value>*</param-value> </init-param> <init-param> <param-name>cors.allowed.methods</param-name> <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value> </init-param> <init-param> <param-name>cors.allowed.headers</param-name> <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value> </init-param> <init-param> <param-name>cors.exposed.headers</param-name> <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value> </init-param> <init-param> <param-name>cors.support.credentials</param-name> <param-value>false</param-value> </init-param> </filter> <filter-mapping> <filter-name>CorsFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ```
24,909,466
How can i assign the javascript variable in to php. ``` $("button").click(function() { var val = (this.id); $.ajax ({ url: "date.php", //data: { val : val }, data:'q=' + val, type: "GET", success: function(result) { if(result==1) { page = "<?php echo $today;?>"; } else if(result==2) { page = "<?php echo $this_week;?>"; } else if(result==3) { page="<?php echo $this_month;?>"; } else if(result==4) { page="<?php echo $previous_month;?>"; } else { "<?php echo $today;?>"; } } }); }); ``` Here i want to pass the variable 'page' to php,for to assign the export excel filename.I done like this in php ``` <?php $page = ('<script type="text/javascript">page</script>'); ?> ``` $page variable i want to assign here. ``` <script> saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), "<?php echo $name[0] ?>- Report-<?php echo $page?>.xlsx"); }; </script> ``` But am getting error,otherwise any other method to assign the variable. my date.php ``` <?php $var=$_GET['q']; if($var == 'getToday') { echo "1"; } elseif($var =='getWeek') { echo "2"; } else if($var =='getMonth') { echo "3"; } else if($var =='getpremon') { echo "4"; } else { echo "5"; } ?> ```
2014/07/23
[ "https://Stackoverflow.com/questions/24909466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3864156/" ]
The solution of Taher solved my problem with PhoneGap+jQuery accessing a tomcat web-service. Just included the referenced java code (<https://github.com/sebastienblanc/cors-filter/blob/master/src/main/java/org/ebaysf/web/cors/CORSFilter.java#L825>) in my project and added the next lines to the web.xml of the project. Redeployed it and that's it. (No corsFilter needed in Tomcat's web.xml.) Now it works both for PhoneGap requests and browser request. This definitively is some TomCat (or PhoneGap?) bug. ``` <filter> <filter-name>CorsFilter</filter-name> <filter-class>myDeploymentName.CORSFilter</filter-class> <init-param> <param-name>cors.allowed.origins</param-name> <param-value>*</param-value> </init-param> <init-param> <param-name>cors.allowed.methods</param-name> <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value> </init-param> <init-param> <param-name>cors.allowed.headers</param-name> <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value> </init-param> <init-param> <param-name>cors.exposed.headers</param-name> <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value> </init-param> <init-param> <param-name>cors.support.credentials</param-name> <param-value>false</param-value> </init-param> </filter> <filter-mapping> <filter-name>CorsFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ```
I changed the tomcat filter in my server. I modified the Origin header of the request inside my custom filter and it works. I dont know wether this is the right way to do things but I this is the only thing to get it working.
24,909,466
How can i assign the javascript variable in to php. ``` $("button").click(function() { var val = (this.id); $.ajax ({ url: "date.php", //data: { val : val }, data:'q=' + val, type: "GET", success: function(result) { if(result==1) { page = "<?php echo $today;?>"; } else if(result==2) { page = "<?php echo $this_week;?>"; } else if(result==3) { page="<?php echo $this_month;?>"; } else if(result==4) { page="<?php echo $previous_month;?>"; } else { "<?php echo $today;?>"; } } }); }); ``` Here i want to pass the variable 'page' to php,for to assign the export excel filename.I done like this in php ``` <?php $page = ('<script type="text/javascript">page</script>'); ?> ``` $page variable i want to assign here. ``` <script> saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), "<?php echo $name[0] ?>- Report-<?php echo $page?>.xlsx"); }; </script> ``` But am getting error,otherwise any other method to assign the variable. my date.php ``` <?php $var=$_GET['q']; if($var == 'getToday') { echo "1"; } elseif($var =='getWeek') { echo "2"; } else if($var =='getMonth') { echo "3"; } else if($var =='getpremon') { echo "4"; } else { echo "5"; } ?> ```
2014/07/23
[ "https://Stackoverflow.com/questions/24909466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3864156/" ]
The solution of Taher solved my problem with PhoneGap+jQuery accessing a tomcat web-service. Just included the referenced java code (<https://github.com/sebastienblanc/cors-filter/blob/master/src/main/java/org/ebaysf/web/cors/CORSFilter.java#L825>) in my project and added the next lines to the web.xml of the project. Redeployed it and that's it. (No corsFilter needed in Tomcat's web.xml.) Now it works both for PhoneGap requests and browser request. This definitively is some TomCat (or PhoneGap?) bug. ``` <filter> <filter-name>CorsFilter</filter-name> <filter-class>myDeploymentName.CORSFilter</filter-class> <init-param> <param-name>cors.allowed.origins</param-name> <param-value>*</param-value> </init-param> <init-param> <param-name>cors.allowed.methods</param-name> <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value> </init-param> <init-param> <param-name>cors.allowed.headers</param-name> <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value> </init-param> <init-param> <param-name>cors.exposed.headers</param-name> <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value> </init-param> <init-param> <param-name>cors.support.credentials</param-name> <param-value>false</param-value> </init-param> </filter> <filter-mapping> <filter-name>CorsFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ```
Given below is the code in Tomcat CORS filter, so new URI with Origin as "file://" throws `URISyntaxException` which results in 403 `protected static boolean isValidOrigin(String origin) { URI originURI; try { originURI = new URI(origin); } catch (URISyntaxException e) { return false; } return originURI.getScheme() != null; }` Someone has tried to override this filter in the below link. <https://github.com/sebastienblanc/cors-filter/blob/master/src/main/java/org/ebaysf/web/cors/CORSFilter.java#L825>
453,116
If $\eta$ is a Grassmann variable, due to invariance under translations we get that, $$\int d\eta\ \eta = 1 \tag1$$ Nevertheless, for being Grassmann's, $\eta$ satisfies $\eta^2 = 0$. Differentiating this condition you get, $$d(\eta^2) = 2\eta d\eta \equiv 0 \Rightarrow \int d\eta\ \eta = 0 \tag2$$ So, Eq. (2) obtained just via definition of Grassmann variable goes against Eq. (1) that comes out from translation invariance. But I've seen the use of Eq. (1) in all books about fermions' path integral, so what is the thing that I'm misunderstanding?
2019/01/09
[ "https://physics.stackexchange.com/questions/453116", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/195138/" ]
I am not sure that $d(\eta^2)$ is defined at all. But if it is, then, in my opinion, you should write it in this way $$ d(\eta^2) = d(\eta\eta) = d\eta\ \eta + \eta\ d\eta $$ So you get not $\eta\ d\eta = 0$, but natural anticommutation of $\eta$ and $d\eta$: $d\eta\ \eta + \eta\ d\eta = 0$. I think the latter equality is usual for Grassmann integrals.
1. For Grassmann-odd [Berezin integration](https://en.wikipedia.org/wiki/Berezin_integral), the integration measure $d\theta$ (called an *integration form* in Ref. 1) is *not$^1$* a [1-form/differential form](https://en.wikipedia.org/wiki/Exterior_derivative) $\mathrm{d}\theta$! 2. For Grassmann-odd Berezin integration there is no naive analogue of [Stokes' theorem](https://en.wikipedia.org/wiki/Stokes%27_theorem). 3. Also note the curious fact that there is no top-form in the Grassmann-odd sector. E.g. the 2-form $\mathrm{d}\theta\wedge\mathrm{d}\theta\neq 0$, because there is a minus sign associated with permuting the exterior derivative $\mathrm{d}$ ("the wedge") and there is a minus sign associated with permuting the Grassmann-odd variable $\theta$. Similarly, the 3-form $\mathrm{d}\theta\wedge\mathrm{d}\theta\wedge\mathrm{d}\theta\neq 0$, and so forth. 4. Instead the Berezin integration $\int\! d\theta=\frac{\partial}{\partial \theta}$ is the same as differentiation! For motivation of eq. (1), see e.g. [this](https://physics.stackexchange.com/q/15786/2451) Phys.SE post. References: 1. Th. Voronov. *Geometric integration theory on supermanifolds,* Sov. Sci. Rev. C. Math. Phys., Vol. 9, pp.1–138. Harwood Academic Publ. (1992). 2. Th. Voronov, *Supermanifold Forms and Integration. A Dual Theory,* [arXiv:dg-ga/9603009](https://arxiv.org/abs/dg-ga/9603009). -- $^1$ Quoting from the introduction of Ref. 2: *The naive definition of differential forms in super case has nothing to do with the Berezin integration!*
38,488,295
I recently bought [Moltran](http://moltran.coderthemes.com/green/index.html) which is fine but has a big disadvantage: The notification menu disappears on mobile devices, which is not suiteable for me. So I learned that that this can be done removing the *hidden-xs* class of the li notification element. This will turn `<li class="dropdown hidden-xs open">` to `<li class="dropdown open">`, which works fine. Now I stretched the small menu on the full width of the screen If the user has a smaller device for better usability: ``` @media (max-width: 767px) { .nav > li.dropdown:not(.hidden-xs).open .dropdown-menu { width: 100vw; } } ``` Everything works fine, until one thing: I'm not able to scroll in the menu. Using a modern 5" smartphone horizontal, 3 elements at the end are hidden. Instead the scrolling will affect the background caused by the absolute position. A simple demonstration on the [online demo](http://moltran.coderthemes.com/green/index.html) to make it more clear: I only removed the class *hidden-xs* because otherwise the menu would not appear on small windows in the line `<li class="dropdown hidden-xs open">` as I said before. When the window is very small, its not able to see the full notification menu and the user isn't able to scroll there: [![enter image description here](https://i.stack.imgur.com/WChxw.png)](https://i.stack.imgur.com/WChxw.png) As you can see, the scroll bar on the right is at the bottom, but you can't full see the notifications because the scroll bar doesn't affect this menu. I tried a few things, mainly switching to other position types because the absolute position seems to cause the issue. But nothing worked, seems like I'm in a blind end. **So my question is: What changes are necessary to keep the functionality as it is, but provide a way to scroll in the notifications on smaller devices?**
2016/07/20
[ "https://Stackoverflow.com/questions/38488295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3276634/" ]
Well. If I understand correctly you should set overflow to your navigation bar. And it should do the trick. ``` .topbar{ height: 100%; background: transparent; overflow-y: auto; } ``` EDIT: This will set height of your topbar to 100%. Because of this it will overlap all elements on the screen. As an alternative you can add a separate class when notification button is clicked and style this element only in such case. For example: ``` .topbar.notification-open{ height: 100%; background: transparent; overflow-y: auto; } ``` And toggle class with jQuery: ``` $('.dropdown-toggle').click(function(){ $(this).closest('.topbar').toggleClass('notification-open'); }); ```
Just give a fixed height to ur notification area with media query on small device and set overflow-y:auto. Height should be in px only. For example let notification\_area is your div class.. ``` @media (max-width:600px){ .notification_area{ overflow-y:auto; height:300px; } } ```
38,488,295
I recently bought [Moltran](http://moltran.coderthemes.com/green/index.html) which is fine but has a big disadvantage: The notification menu disappears on mobile devices, which is not suiteable for me. So I learned that that this can be done removing the *hidden-xs* class of the li notification element. This will turn `<li class="dropdown hidden-xs open">` to `<li class="dropdown open">`, which works fine. Now I stretched the small menu on the full width of the screen If the user has a smaller device for better usability: ``` @media (max-width: 767px) { .nav > li.dropdown:not(.hidden-xs).open .dropdown-menu { width: 100vw; } } ``` Everything works fine, until one thing: I'm not able to scroll in the menu. Using a modern 5" smartphone horizontal, 3 elements at the end are hidden. Instead the scrolling will affect the background caused by the absolute position. A simple demonstration on the [online demo](http://moltran.coderthemes.com/green/index.html) to make it more clear: I only removed the class *hidden-xs* because otherwise the menu would not appear on small windows in the line `<li class="dropdown hidden-xs open">` as I said before. When the window is very small, its not able to see the full notification menu and the user isn't able to scroll there: [![enter image description here](https://i.stack.imgur.com/WChxw.png)](https://i.stack.imgur.com/WChxw.png) As you can see, the scroll bar on the right is at the bottom, but you can't full see the notifications because the scroll bar doesn't affect this menu. I tried a few things, mainly switching to other position types because the absolute position seems to cause the issue. But nothing worked, seems like I'm in a blind end. **So my question is: What changes are necessary to keep the functionality as it is, but provide a way to scroll in the notifications on smaller devices?**
2016/07/20
[ "https://Stackoverflow.com/questions/38488295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3276634/" ]
Well. If I understand correctly you should set overflow to your navigation bar. And it should do the trick. ``` .topbar{ height: 100%; background: transparent; overflow-y: auto; } ``` EDIT: This will set height of your topbar to 100%. Because of this it will overlap all elements on the screen. As an alternative you can add a separate class when notification button is clicked and style this element only in such case. For example: ``` .topbar.notification-open{ height: 100%; background: transparent; overflow-y: auto; } ``` And toggle class with jQuery: ``` $('.dropdown-toggle').click(function(){ $(this).closest('.topbar').toggleClass('notification-open'); }); ```
You can make the notification panel scrollable: ``` .navbar-nav .open .dropdown-menu { background-color: #ffffff; box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26); left: auto; position: absolute; right: 0; z-index: 100; // Extra code required overflow-y: auto; -webkit-overflow-scrolling: touch; /* lets it scroll lazy */ max-height: 500px; //or whatever. Could be 90vh } ``` This should work just fine. Hope it helps.
38,488,295
I recently bought [Moltran](http://moltran.coderthemes.com/green/index.html) which is fine but has a big disadvantage: The notification menu disappears on mobile devices, which is not suiteable for me. So I learned that that this can be done removing the *hidden-xs* class of the li notification element. This will turn `<li class="dropdown hidden-xs open">` to `<li class="dropdown open">`, which works fine. Now I stretched the small menu on the full width of the screen If the user has a smaller device for better usability: ``` @media (max-width: 767px) { .nav > li.dropdown:not(.hidden-xs).open .dropdown-menu { width: 100vw; } } ``` Everything works fine, until one thing: I'm not able to scroll in the menu. Using a modern 5" smartphone horizontal, 3 elements at the end are hidden. Instead the scrolling will affect the background caused by the absolute position. A simple demonstration on the [online demo](http://moltran.coderthemes.com/green/index.html) to make it more clear: I only removed the class *hidden-xs* because otherwise the menu would not appear on small windows in the line `<li class="dropdown hidden-xs open">` as I said before. When the window is very small, its not able to see the full notification menu and the user isn't able to scroll there: [![enter image description here](https://i.stack.imgur.com/WChxw.png)](https://i.stack.imgur.com/WChxw.png) As you can see, the scroll bar on the right is at the bottom, but you can't full see the notifications because the scroll bar doesn't affect this menu. I tried a few things, mainly switching to other position types because the absolute position seems to cause the issue. But nothing worked, seems like I'm in a blind end. **So my question is: What changes are necessary to keep the functionality as it is, but provide a way to scroll in the notifications on smaller devices?**
2016/07/20
[ "https://Stackoverflow.com/questions/38488295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3276634/" ]
You can make the notification panel scrollable: ``` .navbar-nav .open .dropdown-menu { background-color: #ffffff; box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26); left: auto; position: absolute; right: 0; z-index: 100; // Extra code required overflow-y: auto; -webkit-overflow-scrolling: touch; /* lets it scroll lazy */ max-height: 500px; //or whatever. Could be 90vh } ``` This should work just fine. Hope it helps.
Just give a fixed height to ur notification area with media query on small device and set overflow-y:auto. Height should be in px only. For example let notification\_area is your div class.. ``` @media (max-width:600px){ .notification_area{ overflow-y:auto; height:300px; } } ```
18,719,799
I am trying to write a backup script for cloudfiles (using Rackspace) , which will only copy the files that are modified since the last backup time. Is there a way to query for a list files that are modified since a specific time ? (Using PHP ) Note: using [php-opencloud](https://github.com/rackspace/php-opencloud) library.
2013/09/10
[ "https://Stackoverflow.com/questions/18719799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/378737/" ]
Currently, I haven't found a way to query/filter based on the last modified date. What you can do is look at the metadata for each object in a container. At a low level, this requires just a HEAD operation on each object. While this probably requires you to check each object, you're only grabbing the headers and not downloading each one. The [last modified date is in the HTTP headers](http://docs.rackspace.com/files/api/v1/cf-devguide/content/Retrieve_Object_Metadata-d1e2301.html) when making a HEAD operation on an object: ``` HEAD /<api version>/<account>/<container>/<object> HTTP/1.1 Host: storage.clouddrive.com X-Auth-Token: eaaafd18-0fed-4b3a-81b4-663c99ec1cbb ``` No response body is returned, but the HTTP headers have juicy details: ``` HTTP/1.1 200 OK Date: Thu, 07 Jun 2007 20:59:39 GMT Last-Modified: Fri, 12 Jun 2007 13:40:18 GMT ETag: 8a964ee2a5e88be344f36c22562a6486 Content-Length: 512000 Content-Type: text/plain; charset=UTF-8 X-Object-Meta-Meat: Bacon ``` There is a method in the PHP library called `fetch` that can get [just the headers](https://github.com/rackspace/php-opencloud/blob/master/lib/OpenCloud/ObjectStore/Resource/DataObject.php#L796-L825) of the object, but it's private and I don't see it being used [anywhere](https://github.com/rackspace/php-opencloud/search?l=php&q=fetch&ref=cmdform&type=Code). This looks like the type of thing to raise an issue on GitHub or make a PR of your own for. Right now you can get each object and pull the headers out yourself: ``` $obj = $container->DataObject(); $headers = $obj->metadataHeaders(); $headers["Last-Modified"] ``` Sorry that doesn't help completely. I pinged one of the PHP devs directly and hopefully we'll find another option if this doesn't work out.
Try using [glob()](http://php.net/manual/en/function.glob.php) and [filemtime()](http://php.net/manual/en/function.filemtime.php). Example: ``` $lastBackupTime = 1234567890; //You'll have to figure out how to store and retrieve this $modified = array(); // Change the input of glob() to use the directory and file extension you're looking for foreach (glob('/some/directory/*.txt') as $file) { if (filemtime($file) > $lastBackupTime) { $modified[] = $file; } } foreach ($modified as $file) { //do something } ```
1,817,044
I have the following task: "Determine the homomorphism between two cyclic groups. Which are injective, surjective or bijective?" I already found this for the cyclic group of integers: <http://users.math.yale.edu/~auel/courses/370f06/docs/solutions3.pdf> page 2, 4.4. But what about the cyclic groups of Integers modulo n?
2016/06/07
[ "https://math.stackexchange.com/questions/1817044", "https://math.stackexchange.com", "https://math.stackexchange.com/users/346222/" ]
We can suppose the cyclic groups are $\mathbf Z/m\mathbf Z$ and $\mathbf Z/n\mathbf Z$ respectively. A homomorphism from the first to the second is determined by the choice of the image $\bar x$ of $\bar 1$, subject to the condition $m \bar x=0$, i.e. $$\DeclareMathOperator\Hom{Hom}\Hom(\mathbf Z/m\mathbf Z,\mathbf Z/n\mathbf Z) ≃ \operatorname{Ann}\_{\mathbf Z/n\mathbf Z}(m).$$ Let $d=\gcd(m,n)$, $m'=\dfrac md$, $n'=\dfrac nd$. Since $m'$ and $n'$ are coprime, $$\operatorname{Ann}\_{\mathbf Z/n\mathbf Z}(m)=n'\mathbf Z/n\mathbf Z ≃ \mathbf Z/d\mathbf Z.$$ Furthermore, * the surjectivity of such a homomorphism means its image, which is contained in $n'\mathbf Z/n\mathbf Z$, is equal to $\mathbf Z/n\mathbf Z$ . This can happen only if $n'=1$, i.e. $n∣m$. * If $\gcd(m,n)=1$, the only homomorphism is the zero homomorphism. * Injectivity means the image of the homomorphism is isomorphic to $\mathbf Z/m\mathbf Z$. Hence, by *Lagrange’s theorem*, $ m $ has to be a divisor of $ n $. We’ll suppose this is indeed the case. Then the image $ \bar x $ of $\bar 1$ in $ \mathbf Z/n\mathbf Z $ has to be or order $ m $. As the order of $ \bar x$ is $ \dfrac n{\gcd(n, x)} $, this means $ \gcd(n, x) = \dfrac nm$. * Finally, if a homomorphism is an isomorphism, the above considerations show it implies $ m = n $. The image of $\bar 1 $ is another generator of $\mathbf Z/m\mathbf Z$, i. e. an element $\bar x,\; x < m$, coprime to $ m $.
Property: let $f: G \rightarrow H$ a finite group morphism then for all $ x\in G$ the order of $f(x)$ divides both, order of $ x$ and order of $H$. So, if $n$ and $m$ are coprime, then there is no nonzero morphism groups from $\Bbb{Z}/n\Bbb{Z}$ to $\Bbb{Z}/m\Bbb{Z}$. else $n=1$ or $m=1$ this last three cases are evidente If $n$ divides $m$, the number of choosing the injection from $\Bbb{Z}/n\Bbb{Z}$ into $\Bbb{Z}/m\Bbb{Z}$ is the number of pairs $(i, j)$ where $order (i) = oorder(j) = n$. so in total there are $\phi(n)^2$; these injections are surjections therefore bijections if and only if $n = m$. If $d = gcd (n, m)$ with $n \neq d \neq m$, there is no injections, no surjections, no bijections.
35,413,139
we want to load css and javascript files dynamically for the pages in our magento system. By reason of growing js and css file we want to split them in seperate files and load them for the current page. We use the CMS [Advanced content manager](http://www.advancedcontentmanager.com/) for managing our page content. Cause we have something like contenttypes in the CMS, we thought to figure out which contenttype the current page has. Referring of the type we thought to load the css and js file by the name of the type (cause the typename is an alias and unique in the system). Cause i am not to deep in magento coding i have no clue where i should start. But maybe there is another solution or a known solution to achieve what we want.
2016/02/15
[ "https://Stackoverflow.com/questions/35413139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1648661/" ]
Have you tried using XML to load JS or CSS on particular content pages? Here is an example of loading CSS & JS file. *Content Page => Design Tab => Custom Layout Update XML.* ``` <reference name="head"> <action method="addItem"><type>skin_css</type><name>css/your_css.css</name></action> <action method="addItem"><type>skin_js</type><name>js/your_js.js</name></action> </reference> ```
You could create an extension that observes the 'layout load before' event. With some request params you could identify the pages where you want to include some css or js. For Example: `app/code/local/Foo/Bar/etc/config.xml` ``` <?xml version="1.0" encoding="UTF-8"?> <config> <modules> <Foo_Bar> <version>0.1.0</version> </Foo_Bar> </modules> <global> <models> <foo_bar> <class>Foo_Bar_Model</class> </foo_bar> </models> </global> <frontend> <events> <controller_action_layout_load_before> <observers> <customer_is_logged_in_observer> <class>foo_bar/observer</class> <method>beforeLoadLayout</method> </customer_is_logged_in_observer> </observers> </controller_action_layout_load_before> </events> </frontend> </config> ``` `app/code/local/Foo/Bar/Model/Observer.php` ``` class Foo_Bar_Model_Observer { public function beforeLoadLayout($observer) { if(Mage::app()->getRequest()->getControllerName()=='page' && Mage::app()->getRequest()->getRouteName()='cms') { $head=$observer->getEvent()->getLayout()->getBlock('head'); $head->addItem('skin_js', 'js/foo.js'); $head->addItem('skin_css', 'css/foo.css'); } } } ```
35,413,139
we want to load css and javascript files dynamically for the pages in our magento system. By reason of growing js and css file we want to split them in seperate files and load them for the current page. We use the CMS [Advanced content manager](http://www.advancedcontentmanager.com/) for managing our page content. Cause we have something like contenttypes in the CMS, we thought to figure out which contenttype the current page has. Referring of the type we thought to load the css and js file by the name of the type (cause the typename is an alias and unique in the system). Cause i am not to deep in magento coding i have no clue where i should start. But maybe there is another solution or a known solution to achieve what we want.
2016/02/15
[ "https://Stackoverflow.com/questions/35413139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1648661/" ]
Have you tried using XML to load JS or CSS on particular content pages? Here is an example of loading CSS & JS file. *Content Page => Design Tab => Custom Layout Update XML.* ``` <reference name="head"> <action method="addItem"><type>skin_css</type><name>css/your_css.css</name></action> <action method="addItem"><type>skin_js</type><name>js/your_js.js</name></action> </reference> ```
Just check out the module documentation, a dynamic layout is implemented. So you can add a specific layout for a certain content type: acm for magento 1.x: (end of page) <https://www.advancedcontentmanager.com/documentation/content/php-helper-methods-render-methods> acm for magento 2.x: <https://www.advancedcontentmanager.com/documentation/m2/developers/dynamic-layout-handle>
39,601,787
I'm unable to find method to close path open in windows explorer. Lets say I would like to close opened window, "c:\program files". Code should look like ``` #::j close window "c:\program files" return ``` Thank you.
2016/09/20
[ "https://Stackoverflow.com/questions/39601787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1926221/" ]
You will want to look here: <https://autohotkey.com/docs/commands/WinClose.htm> which specifies: `WinClose [, WinTitle, WinText, SecondsToWait, ExcludeTitle, ExcludeText]` and then: ``` #j:: ; Win Key + j WinClose, C:\Program Files ; close Program Files window return ``` Alternatively, to close any explorer window, use: ``` #j:: ; Win Key + j WinClose, ahk_class CabinetWClass ; closes any explorer window return ``` Hth
Updated Code and here is a [video stepping through the code](http://sendvid.com/a8v4jrd4): ``` path := "C:\Program Files" shell := ComObjCreate("Shell.Application") shell.open("file:///c:/") shell.open("file:///" . path) #If WinExist("ahk_class CabinetWClass") ; explorer F1:: for window in ComObjCreate("Shell.Application").Windows if (path == window.Document.Folder.Self.Path) window.quit() return #If ```
29,164,779
I'm working on a project that has many view controllers. Suppose that they are: A -> B -> C -> D -> E ->F ->G -> H. Each of them has a back and a next button to switch to another view and has many text fields. I typed text into every textfield. From H view, I can go back to previous views by popviewcontroller and review typed data. but when I click on next button again, all of data on the view were lost. I need to back/next continuous without losing data. How can I do that?
2015/03/20
[ "https://Stackoverflow.com/questions/29164779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4693597/" ]
Create a Singleton class. Give in Singleton class a property like `Form *form;` If you start your first ViewController create a new Form ``` [Singleton sharedInstance].form = [[Form alloc] init]; ``` On leave first ViewController set property from TextField ``` [Singleton sharedInstance].form.name = textField.text ``` On leave second ViewController set property ``` [Singleton sharedInstance].form.mail = textField.text ``` In each ViewController in viewWillAppear method set stored text ``` self.textField.text = [Singleton sharedInstance].form.name ``` or ``` self.textField.text = [Singleton sharedInstance].form.mail ``` It's a simple example, but hope it helps to understand what is to do :)
What about using a NSMutableDictionary to keep the models for each view controller as a key value pair. And Each View Controller initialized with this NSMutableDictionary ``` - (id) initWithDataDictionary:(NSMutableDictionary *)aDataDictionary { self = [super init]; _myDataModel = (MyDataModel*)[aDictionary valueForKey:@"MyKeyName"]; if(_myDataModel == nil) { _myDataModel = [MyDataModel alloc] init]; aDataDictionary setValue:_myDataModel forKey:@"MyKeyName"]; } return self; } - (void) viewDidLoad { [super viewDidLoad]; [self displayData]; } - (void) displayData { self.text1.text = _myDataModel.name; } ``` You may also able to keep a key-value pair for setting focus to a last focused textfield.
29,164,779
I'm working on a project that has many view controllers. Suppose that they are: A -> B -> C -> D -> E ->F ->G -> H. Each of them has a back and a next button to switch to another view and has many text fields. I typed text into every textfield. From H view, I can go back to previous views by popviewcontroller and review typed data. but when I click on next button again, all of data on the view were lost. I need to back/next continuous without losing data. How can I do that?
2015/03/20
[ "https://Stackoverflow.com/questions/29164779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4693597/" ]
Create a Singleton class. Give in Singleton class a property like `Form *form;` If you start your first ViewController create a new Form ``` [Singleton sharedInstance].form = [[Form alloc] init]; ``` On leave first ViewController set property from TextField ``` [Singleton sharedInstance].form.name = textField.text ``` On leave second ViewController set property ``` [Singleton sharedInstance].form.mail = textField.text ``` In each ViewController in viewWillAppear method set stored text ``` self.textField.text = [Singleton sharedInstance].form.name ``` or ``` self.textField.text = [Singleton sharedInstance].form.mail ``` It's a simple example, but hope it helps to understand what is to do :)
I see two options here: * If you use storyboards [unwind](http://spin.atomicobject.com/2014/10/25/ios-unwind-segues/) segues are very good option. * Else you can create own [delegate](http://www.idev101.com/code/Objective-C/delegate.html).
46,036,140
I upload a blob using the SDK and add some metadata e.g: ``` blob.Metadata["fileLoadId"] = "5"; ``` I then have a logic app that is triggered by this new blob, but I want to be able to access this 'fileLoadId' within the logic app so I can pass it to functions. In the logic app the blob has the following metadata: ``` { "Id": "L2VtcGxveWVlcy9lbXBsb3llZS10ZXN0LmNzdg==", "Name": "employee-test.csv", "DisplayName": "employee-test.csv", "Path": "/employees/employee-test.csv", "LastModified": "2017-09-04T10:13:21Z", "Size": 507, "MediaType": "text/csv", "IsFolder": false, "ETag": "\"0x8D4F37D9209EC29\"", "FileLocator": "L2VtcGxveWVlcy9lbXBsb3llZS10ZXN0LmNzdg==", "LastModifiedBy": null } ``` but doesn't include any custom metadata related to the blob. Is it possible to get access to all the metadata in a logic app? Thanks
2017/09/04
[ "https://Stackoverflow.com/questions/46036140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/592192/" ]
To generate URL's for assets like CSS/JS/images/etc., in Laravel, use the helper function `asset`, instead of specifying the relative URL: ``` <link rel="stylesheet" href="{{ asset('css/style.css') }}"> ``` [See the documentation](https://laravel.com/docs/5.4/helpers#method-asset)
The right solution is the following one: ``` <link rel="stylesheet" href="/css/style.css"> ``` Don't forget to add the `/` before the `css/style.css` or it wont load.
46,036,140
I upload a blob using the SDK and add some metadata e.g: ``` blob.Metadata["fileLoadId"] = "5"; ``` I then have a logic app that is triggered by this new blob, but I want to be able to access this 'fileLoadId' within the logic app so I can pass it to functions. In the logic app the blob has the following metadata: ``` { "Id": "L2VtcGxveWVlcy9lbXBsb3llZS10ZXN0LmNzdg==", "Name": "employee-test.csv", "DisplayName": "employee-test.csv", "Path": "/employees/employee-test.csv", "LastModified": "2017-09-04T10:13:21Z", "Size": 507, "MediaType": "text/csv", "IsFolder": false, "ETag": "\"0x8D4F37D9209EC29\"", "FileLocator": "L2VtcGxveWVlcy9lbXBsb3llZS10ZXN0LmNzdg==", "LastModifiedBy": null } ``` but doesn't include any custom metadata related to the blob. Is it possible to get access to all the metadata in a logic app? Thanks
2017/09/04
[ "https://Stackoverflow.com/questions/46036140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/592192/" ]
``` <link rel="stylesheet" href="{{ asset('public/css/style.css') }} "> ``` or ``` <link rel="stylesheet" href="{{ asset('css/style.css') }} "> ```
The right solution is the following one: ``` <link rel="stylesheet" href="/css/style.css"> ``` Don't forget to add the `/` before the `css/style.css` or it wont load.
46,036,140
I upload a blob using the SDK and add some metadata e.g: ``` blob.Metadata["fileLoadId"] = "5"; ``` I then have a logic app that is triggered by this new blob, but I want to be able to access this 'fileLoadId' within the logic app so I can pass it to functions. In the logic app the blob has the following metadata: ``` { "Id": "L2VtcGxveWVlcy9lbXBsb3llZS10ZXN0LmNzdg==", "Name": "employee-test.csv", "DisplayName": "employee-test.csv", "Path": "/employees/employee-test.csv", "LastModified": "2017-09-04T10:13:21Z", "Size": 507, "MediaType": "text/csv", "IsFolder": false, "ETag": "\"0x8D4F37D9209EC29\"", "FileLocator": "L2VtcGxveWVlcy9lbXBsb3llZS10ZXN0LmNzdg==", "LastModifiedBy": null } ``` but doesn't include any custom metadata related to the blob. Is it possible to get access to all the metadata in a logic app? Thanks
2017/09/04
[ "https://Stackoverflow.com/questions/46036140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/592192/" ]
Use absolute paths like this (starting from the end of 'public'): ``` <link rel="stylesheet" href="/css/style.css">, ```
The right solution is the following one: ``` <link rel="stylesheet" href="/css/style.css"> ``` Don't forget to add the `/` before the `css/style.css` or it wont load.
63,729,967
Here is some code I've written to save a UrlEntity : ``` public UrlEntity saveUrlEntity(String longUrl, LocalDate dateAdded) { int urlLength = longUrl.length(); if (urlLength >= Constants.MAX_LONG_URL_LENGTH) { throw new LongUrlLengthExceededException("URL with length " + urlLength + " exceeds the max length of " + Constants.MAX_LONG_URL_LENGTH + " characters"); } else { List<UrlEntity> urlEntity = urlRepository.findByLongUrl(longUrl); if (urlEntity.size() > 0) { return urlEntity.get(0); } else { final String shortUrl = urlShorten.shortenURL(longUrl); if (urlRepository.findFirstByShortUrl(shortUrl).isPresent()) { logger.error("A short short URL collision occured for long URL: " + longUrl + " with generated short URL" + shortUrl); throw new ShortUrlCollisionException("A short URL collision occured"); } else { logger.info("Shortened URL: " + shortUrl); final UrlEntity urlEntityToSave = new UrlEntity(dateAdded, longUrl, shortUrl); return urlRepository.save(urlEntityToSave); } } } } ``` The above code exists in a service class and looks unnecessarily complex. I'm attempting to refactor so that the intent is clear. This is a basic refactoring I've written: ``` public UrlEntity saveUrlEntity(String longUrl, LocalDate dateAdded) { int urlLength = longUrl.length(); if (urlLength >= Constants.MAX_LONG_URL_LENGTH) { throw new LongUrlLengthExceededException("URL with length " + urlLength + " exceeds the max length of " + Constants.MAX_LONG_URL_LENGTH + " characters"); } else { List<UrlEntity> urlEntity = urlRepository.findByLongUrl(longUrl); if (urlEntity.size() > 0) { return urlEntity.get(0); } else { return saveUrlEntityValue(longUrl, dateAdded); } } } private UrlEntity saveUrlEntityValue(String longUrl, LocalDate dateAdded){ final String shortUrl = urlShorten.shortenURL(longUrl); if (urlRepository.findFirstByShortUrl(shortUrl).isPresent()) { logger.error("A short short URL collision occured for long URL: " + longUrl + " with generated short URL" + shortUrl); throw new ShortUrlCollisionException("A short URL collision occured"); } else { logger.info("Shortened URL: " + shortUrl); final UrlEntity urlEntityToSave = new UrlEntity(dateAdded, longUrl, shortUrl); return urlRepository.save(urlEntityToSave); } } ``` This refactoring does not improve the code substantially. Is there a code pattern or idiomatic way to refactor the method `saveUrlEntity`? I'm using `Java11`
2020/09/03
[ "https://Stackoverflow.com/questions/63729967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470184/" ]
This is very subjective, but... Since most of your `if` statements are guard/short-circuit clauses, which `throw` or `return`, there is no need to use `else`. I think this simple change makes the code much more readable. ``` public UrlEntity saveUrlEntity(String longUrl, LocalDate dateAdded) { final int urlLength = longUrl.length(); if (urlLength >= Constants.MAX_LONG_URL_LENGTH) { throw new LongUrlLengthExceededException("URL with length " + urlLength + " exceeds the max length of " + Constants.MAX_LONG_URL_LENGTH + " characters"); } final List<UrlEntity> urlEntity = urlRepository.findByLongUrl(longUrl); if (urlEntity.size() > 0) { return urlEntity.get(0); } final String shortUrl = urlShorten.shortenURL(longUrl); if (urlRepository.findFirstByShortUrl(shortUrl).isPresent()) { logger.error("A short short URL collision occured for long URL: " + longUrl + " with generated short URL" + shortUrl); throw new ShortUrlCollisionException("A short URL collision occured"); } logger.info("Shortened URL: " + shortUrl); final UrlEntity urlEntityToSave = new UrlEntity(dateAdded, longUrl, shortUrl); return urlRepository.save(urlEntityToSave); } ``` I'd also recommend replacing `urlEntity.size() > 0` with `!urlEntity.isEmpty()`. The method does seem to be doing several things, which violates the Single Responsibility Principle; you might want to think about breaking that out better.
If you use `throw new` or `return` you do not need the else condition because the method ends like ``` public UrlEntity saveUrlEntity(String longUrl, LocalDate dateAdded) { int urlLength = longUrl.length(); if (urlLength >= Constants.MAX_LONG_URL_LENGTH) { throw new LongUrlLengthExceededException("URL with length " + urlLength + " exceeds the max length of " + Constants.MAX_LONG_URL_LENGTH + " characters"); } List<UrlEntity> urlEntity = urlRepository.findByLongUrl(longUrl); if (urlEntity.size() > 0) { return urlEntity.get(0); } final String shortUrl = urlShorten.shortenURL(longUrl); if (urlRepository.findFirstByShortUrl(shortUrl).isPresent()) { logger.error("A short short URL collision occured for long URL: " + longUrl + " with generated short URL" + shortUrl); throw new ShortUrlCollisionException("A short URL collision occured"); } logger.info("Shortened URL: " + shortUrl); final UrlEntity urlEntityToSave = new UrlEntity(dateAdded, longUrl, shortUrl); return urlRepository.save(urlEntityToSave); } ```
62,222,463
I'm trying to change, with CSS, the size and color of an SVG element that's being rendered with `<use>`. The SVG in question: ``` <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24"> <path fill="#000000" fill-rule="evenodd" d="<all the actual svg path info>" clip-rule="evenodd"/> </svg> ``` I do not have permission to change the contents of the SVG itself. The way I'm using the SVG: ``` <svg> <use xlink:href="#myIcon"></use> </svg> ``` I've fought with this for hours, read through [a pretty comprehensive article on the subject](http://tympanus.net/codrops/2015/07/16/styling-svg-use-content-css/), and I still haven't had any success. I've tried applying classes to both the `use` element and the outer `svg` element, as well as referencing the `path` element inside. I can't seem to do anything to override the provided styles. How can I change the width, height, and fill color with this arrangement?
2020/06/05
[ "https://Stackoverflow.com/questions/62222463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11719027/" ]
For the size it's easy if you correctly set the viewBox and then you adjust the width/height. For the coloration you can rely on blending mode since the color of the SVG is black. ```css .icon { display: inline-block; background: #fff; position: relative; } .icon::after { content:""; position:absolute; top:0; left:0; right:0; bottom:0; background:var(--c); mix-blend-mode:lighten; } .icon>svg { display: block; } ``` ```html <svg xmlns="http://www.w3.org/2000/svg" width="0" height="0"> <symbol id="myIcon"> <path fill="#000" d="M81,40.933c0-4.25-3-7.811-6.996-8.673c-0.922-5.312-3.588-10.178-7.623-13.844 c-2.459-2.239-5.326-3.913-8.408-4.981c-0.797-3.676-4.066-6.437-7.979-6.437c-3.908,0-7.184,2.764-7.979,6.442 c-3.078,1.065-5.939,2.741-8.396,4.977c-4.035,3.666-6.701,8.531-7.623,13.844C22.002,33.123,19,36.682,19,40.933 c0,2.617,1.145,4.965,2.957,6.589c0.047,0.195,0.119,0.389,0.225,0.568l26.004,43.873c0.383,0.646,1.072,1.04,1.824,1.04 c0.748,0,1.439-0.395,1.824-1.04L77.82,48.089c0.105-0.179,0.178-0.373,0.225-0.568C79.855,45.897,81,43.549,81,40.933z M49.994,11.235c2.164,0,3.928,1.762,3.928,3.93c0,2.165-1.764,3.929-3.928,3.929s-3.928-1.764-3.928-3.929 C46.066,12.997,47.83,11.235,49.994,11.235z M27.842,36.301c0.014,0,0.027,0,0.031,0c1.086,0,1.998-0.817,2.115-1.907 c0.762-7.592,5.641-13.791,12.303-16.535c1.119,3.184,4.146,5.475,7.703,5.475c3.561,0,6.588-2.293,7.707-5.48 c6.664,2.742,11.547,8.944,12.312,16.54c0.115,1.092,1.037,1.929,2.143,1.907c2.541,0.013,4.604,2.087,4.604,4.631 c0,1.684-0.914,3.148-2.266,3.958H25.508c-1.354-0.809-2.268-2.273-2.268-3.958C23.24,38.389,25.303,36.316,27.842,36.301z M50.01,86.723L27.73,49.13h44.541L50.01,86.723z" fill-rule="evenodd" clip-rule="evenodd"/> </symbol> </svg> <!-- your code --> <div class="icon" style="--c:red;"> <svg viewBox="0 0 100 125" width="100"> <use xlink:href="#myIcon"></use> </svg> </div> <div class="icon" style="--c:green;"> <svg viewBox="0 0 100 125" width="150"> <use xlink:href="#myIcon"></use> </svg> </div> <div class="icon" style="--c:blue;"> <svg viewBox="0 0 100 125" width="200"> <use xlink:href="#myIcon"></use> </svg> </div> ```
Save svg as a image with svg format then add the color and width or whatever you want to your img then add this to the html file as a img tag and display: none the svg code. If you can't reach the html code then you can't do anything.
416,977
Let $B$ be a paracompact space with the property that any (topological) vector bundle $E \to B$ is trivial. What are some non-trivial examples of such spaces, and are there any interesting properties that characterize them? For simple known examples we of course have contractible spaces, as well as the 3-sphere $S^3$. This one follows from the fact that its rank $n$ vector bundles are classified by $\pi\_3 (BO(n)) = \pi\_2 (O(n)) = 0$. I'm primarily interested in the case where $B$ is a closed manifold. Do we know any other such examples? There is this [nice answer](https://math.stackexchange.com/a/1108129/354855) to a MSE question which talks about using the Whitehead tower of the appropriate classifying space to determine whether a bundle is trivial or not. This seems like a nice tool (of which I am not familiar with) to approaching this problem. As a secondary question, could I ask for some insight/references to this approach? **EDIT** Now that we know from the answers all the examples for closed $3$-manifolds, I guess I can now update the question to the case of higher odd dimensions. Does there exist a higher dimensional example?
2022/02/25
[ "https://mathoverflow.net/questions/416977", "https://mathoverflow.net", "https://mathoverflow.net/users/143629/" ]
Let $B$ be a closed manifold with such that every vector bundle is trivial. Then $H^1(B; \mathbb{Z}\_2) = 0$, otherwise there would be a non-trivial line bundle. Therefore every bundle over $B$ is orientable and $B$ itself is orientable. Orientable rank two bundles over $B$ are classified by $H^2(B; \mathbb{Z})$, so we must have $H^2(B; \mathbb{Z}) = 0$. It follows these conditions that there are no examples with $\dim B = 1, 2$. If $\dim B > 2$ we then have to consider the possibility of non-trivial bundles of rank at least three. Suppose now that $\dim B = 3$. As $B$ is closed and orientable we have $H\_1(B; \mathbb{Z}) \cong H^2(B; \mathbb{Z}) = 0$ by Poincaré duality and $H^3(B; \mathbb{Z}) \cong \mathbb{Z}$. It follows that $B$ is an integral homology sphere - note, the condition $H^1(B; \mathbb{Z}\_2) = 0$ is superfluous in this case as $H^1(B; \mathbb{Z}) \cong \operatorname{Hom}(H\_1(B; \mathbb{Z}), \mathbb{Z}\_2)$ by the Universal Coefficient Theorem. We still have to consider the possibility of non-trivial bundles of rank at least three. Suppose $E \to B$ has rank greater than three, then $E\cong E\_0\oplus\varepsilon^k$ for some rank three bundle $E\_0$, see [this answer](https://mathoverflow.net/a/417820/21564); in particular, we only need to consider the possibility of a non-trivial vector bundle of rank three. Suppose then that $\operatorname{rank} E = 3$. As $E$ is orientable, it has an Euler class $e(E)$ which is the first obstruction to a nowhere-zero section (it is also the only obstruction because $\operatorname{rank}E = \dim B$). As $E$ has odd rank, the Euler class of $E$ is two-torsion, but $e(E) \in H^3(B; \mathbb{Z}) \cong \mathbb{Z}$ which is torsion-free, so $e(E) = 0$. Therefore $E \cong E\_0\oplus\varepsilon^1$ where $\operatorname{rank}E\_0 = 2$. As we already know rank two bundles over $B$ are trivial, we see that $E$ is also trivial. In conclusion, we have the following: > > Let $B$ be a closed three-manifold. Every vector over $B$ is trivial if and only if $B$ is an integral homology sphere. > > > Note, we only considered real vector bundles above, but the same is true for complex vector bundles since every such bundle is the direct sum of a trivial bundle and a complex line bundle, but the latter are classified by $H^2(B; \mathbb{Z}) = 0$. The fact that every vector bundle over a three-dimensional integral homology sphere is trivial can also be seen using [Quillen's plus construction](https://encyclopediaofmath.org/index.php?title=Plus-construction) (also see section $\mathrm{IV}.1$ of Weibel's *An Introduction to Algebraic K-Theory*). As $B$ is an integral homology sphere, its fundamental group $\pi\_1(B)$ is perfect. By the plus construction, there is a simply connected CW complex $B^+ = B^+\_{\pi\_1(B)}$ and a map $q : B \to B^+$ inducing isomorphisms on homology satisfying the following: if $f : B \to X$ is a map with $\ker f\_\* : \pi\_1(B) \to \pi\_1(X)$ equal to $\pi\_1(B)$, then there is a map $g : B^+ \to X$, unique up to homotopy, such that $f = g\circ q$. As $H^1(B; \mathbb{Z}\_2) = 0$, every bundle over $B$ is orientable and hence classified by a map $f : B \to BSO(n)$. Since $\pi\_1(BSO(n)) \cong \pi\_0(SO(n)) = 0$, the kernel of $f\_\* : \pi\_1(B) \to \pi\_1(BSO(n))$ is $\pi\_1(B)$ so $f = g\circ q$ for some map $g : B^+ \to BSO(n)$. Note that $B^+$ is a simply connected CW complex with $H\_\*(B^+) \cong H^+(S^3)$, so $B^+$ is homotopy equivalent to $S^3$ by the homological Whitehead Theorem. As $\pi\_3(BSO(n)) \cong \pi\_2(SO(n)) = 0$, the maps $g$ and $f$ are nullhomotopic, so $f$ classifies the trivial bundle. Replacing $BSO(n)$ with $BU(n)$ yields the same result for complex vector bundles. As for higher-dimensional examples, note that they must have odd dimension. To see this, suppose $\dim B = 2m$. Choose a degree one map $\varphi : B \to S^{2m}$ and consider the bundle $\varphi^\*TS^{2m} \to B$. As $e(TS^{2m}) \neq 0$ and $\varphi^\* : H^{2m}(S^{2m}; \mathbb{Z}) \to H^{2m}(B; \mathbb{Z})$ is an isomorphism, we see that $e(\varphi^\*TS^{2m}) = \varphi^\*e(TS^{2m}) \neq 0$ and hence $\varphi^\*TS^{2m}$ is non-trivial. If one considers complex bundles instead, the same argument works by replacing $TS^{2m}$ with a complex vector bundle $E$ with $e(E) = c\_n(E) \neq 0$ - such a bundle always exists as $\operatorname{ch} : K(S^{2m})\otimes\mathbb{Q}\to H^{\text{even}}(S^{2m}; \mathbb{Q})$ is an isomorphism. One last comment about dimension five. As was established by Jason DeVito [here](https://math.stackexchange.com/a/4409768/39599), $B$ must be a rational homology sphere. If a five-dimensional example exists, I claim it is also a $\mathbb{Z}\_2$ homology sphere. To see this, first note that we have $H^1(B; \mathbb{Z}\_2) = 0$ from above. Now, if $v \in H^2(B; \mathbb{Z}\_2)$, then there is a bundle $E \to B$ with $w\_2(E) = v$ if and only if $\beta(v^2) \in H^5(B; \mathbb{Z})$ is zero where $\beta$ denotes the mod $2$ Bockstein, see [this answer](https://mathoverflow.net/a/344172/21564). As $\beta(v^2)$ is two-torsion and $H^5(B; \mathbb{Z}) \cong \mathbb{Z}$ is torsion-free, we see that $\beta(v^2) = 0$ for every $v \in H^2(B; \mathbb{Z}\_2)$, so every such class arises as $w\_2(E)$ for some $E$. Therefore, we must have $H^2(B; \mathbb{Z}\_2) = 0$. The claim now follows by Poincaré duality.
Here is one constraint, which seems relevant in light of Michael Albanese's answer: **Claim:** Let $B$ be a closed orientable odd-dimensional manifold with no stably nontrivial complex vector bundles. Then $B$ is a rational homology sphere (of odd dimension). **Proof:** 1. By Bott periodicity, $\widetilde{KU}^\ast(B)$ is concentrated in odd dimensions. 2. Now, $\widetilde H^\ast(B; \mathbb Q[\beta^\pm])$ (with $|\beta| = 2$) is the rationalization of $\widetilde{KU}^\ast(B)$, so it is also concentrated in odd dimensions. So $\widetilde H^\ast(B; \mathbb Q)$ is also concentrated in odd dimensions. 3. Now since $B$ is odd-dimensional, it follows by Poincaré duality that $B$ is a rational homology sphere.
416,977
Let $B$ be a paracompact space with the property that any (topological) vector bundle $E \to B$ is trivial. What are some non-trivial examples of such spaces, and are there any interesting properties that characterize them? For simple known examples we of course have contractible spaces, as well as the 3-sphere $S^3$. This one follows from the fact that its rank $n$ vector bundles are classified by $\pi\_3 (BO(n)) = \pi\_2 (O(n)) = 0$. I'm primarily interested in the case where $B$ is a closed manifold. Do we know any other such examples? There is this [nice answer](https://math.stackexchange.com/a/1108129/354855) to a MSE question which talks about using the Whitehead tower of the appropriate classifying space to determine whether a bundle is trivial or not. This seems like a nice tool (of which I am not familiar with) to approaching this problem. As a secondary question, could I ask for some insight/references to this approach? **EDIT** Now that we know from the answers all the examples for closed $3$-manifolds, I guess I can now update the question to the case of higher odd dimensions. Does there exist a higher dimensional example?
2022/02/25
[ "https://mathoverflow.net/questions/416977", "https://mathoverflow.net", "https://mathoverflow.net/users/143629/" ]
Let $B$ be a closed manifold with such that every vector bundle is trivial. Then $H^1(B; \mathbb{Z}\_2) = 0$, otherwise there would be a non-trivial line bundle. Therefore every bundle over $B$ is orientable and $B$ itself is orientable. Orientable rank two bundles over $B$ are classified by $H^2(B; \mathbb{Z})$, so we must have $H^2(B; \mathbb{Z}) = 0$. It follows these conditions that there are no examples with $\dim B = 1, 2$. If $\dim B > 2$ we then have to consider the possibility of non-trivial bundles of rank at least three. Suppose now that $\dim B = 3$. As $B$ is closed and orientable we have $H\_1(B; \mathbb{Z}) \cong H^2(B; \mathbb{Z}) = 0$ by Poincaré duality and $H^3(B; \mathbb{Z}) \cong \mathbb{Z}$. It follows that $B$ is an integral homology sphere - note, the condition $H^1(B; \mathbb{Z}\_2) = 0$ is superfluous in this case as $H^1(B; \mathbb{Z}) \cong \operatorname{Hom}(H\_1(B; \mathbb{Z}), \mathbb{Z}\_2)$ by the Universal Coefficient Theorem. We still have to consider the possibility of non-trivial bundles of rank at least three. Suppose $E \to B$ has rank greater than three, then $E\cong E\_0\oplus\varepsilon^k$ for some rank three bundle $E\_0$, see [this answer](https://mathoverflow.net/a/417820/21564); in particular, we only need to consider the possibility of a non-trivial vector bundle of rank three. Suppose then that $\operatorname{rank} E = 3$. As $E$ is orientable, it has an Euler class $e(E)$ which is the first obstruction to a nowhere-zero section (it is also the only obstruction because $\operatorname{rank}E = \dim B$). As $E$ has odd rank, the Euler class of $E$ is two-torsion, but $e(E) \in H^3(B; \mathbb{Z}) \cong \mathbb{Z}$ which is torsion-free, so $e(E) = 0$. Therefore $E \cong E\_0\oplus\varepsilon^1$ where $\operatorname{rank}E\_0 = 2$. As we already know rank two bundles over $B$ are trivial, we see that $E$ is also trivial. In conclusion, we have the following: > > Let $B$ be a closed three-manifold. Every vector over $B$ is trivial if and only if $B$ is an integral homology sphere. > > > Note, we only considered real vector bundles above, but the same is true for complex vector bundles since every such bundle is the direct sum of a trivial bundle and a complex line bundle, but the latter are classified by $H^2(B; \mathbb{Z}) = 0$. The fact that every vector bundle over a three-dimensional integral homology sphere is trivial can also be seen using [Quillen's plus construction](https://encyclopediaofmath.org/index.php?title=Plus-construction) (also see section $\mathrm{IV}.1$ of Weibel's *An Introduction to Algebraic K-Theory*). As $B$ is an integral homology sphere, its fundamental group $\pi\_1(B)$ is perfect. By the plus construction, there is a simply connected CW complex $B^+ = B^+\_{\pi\_1(B)}$ and a map $q : B \to B^+$ inducing isomorphisms on homology satisfying the following: if $f : B \to X$ is a map with $\ker f\_\* : \pi\_1(B) \to \pi\_1(X)$ equal to $\pi\_1(B)$, then there is a map $g : B^+ \to X$, unique up to homotopy, such that $f = g\circ q$. As $H^1(B; \mathbb{Z}\_2) = 0$, every bundle over $B$ is orientable and hence classified by a map $f : B \to BSO(n)$. Since $\pi\_1(BSO(n)) \cong \pi\_0(SO(n)) = 0$, the kernel of $f\_\* : \pi\_1(B) \to \pi\_1(BSO(n))$ is $\pi\_1(B)$ so $f = g\circ q$ for some map $g : B^+ \to BSO(n)$. Note that $B^+$ is a simply connected CW complex with $H\_\*(B^+) \cong H^+(S^3)$, so $B^+$ is homotopy equivalent to $S^3$ by the homological Whitehead Theorem. As $\pi\_3(BSO(n)) \cong \pi\_2(SO(n)) = 0$, the maps $g$ and $f$ are nullhomotopic, so $f$ classifies the trivial bundle. Replacing $BSO(n)$ with $BU(n)$ yields the same result for complex vector bundles. As for higher-dimensional examples, note that they must have odd dimension. To see this, suppose $\dim B = 2m$. Choose a degree one map $\varphi : B \to S^{2m}$ and consider the bundle $\varphi^\*TS^{2m} \to B$. As $e(TS^{2m}) \neq 0$ and $\varphi^\* : H^{2m}(S^{2m}; \mathbb{Z}) \to H^{2m}(B; \mathbb{Z})$ is an isomorphism, we see that $e(\varphi^\*TS^{2m}) = \varphi^\*e(TS^{2m}) \neq 0$ and hence $\varphi^\*TS^{2m}$ is non-trivial. If one considers complex bundles instead, the same argument works by replacing $TS^{2m}$ with a complex vector bundle $E$ with $e(E) = c\_n(E) \neq 0$ - such a bundle always exists as $\operatorname{ch} : K(S^{2m})\otimes\mathbb{Q}\to H^{\text{even}}(S^{2m}; \mathbb{Q})$ is an isomorphism. One last comment about dimension five. As was established by Jason DeVito [here](https://math.stackexchange.com/a/4409768/39599), $B$ must be a rational homology sphere. If a five-dimensional example exists, I claim it is also a $\mathbb{Z}\_2$ homology sphere. To see this, first note that we have $H^1(B; \mathbb{Z}\_2) = 0$ from above. Now, if $v \in H^2(B; \mathbb{Z}\_2)$, then there is a bundle $E \to B$ with $w\_2(E) = v$ if and only if $\beta(v^2) \in H^5(B; \mathbb{Z})$ is zero where $\beta$ denotes the mod $2$ Bockstein, see [this answer](https://mathoverflow.net/a/344172/21564). As $\beta(v^2)$ is two-torsion and $H^5(B; \mathbb{Z}) \cong \mathbb{Z}$ is torsion-free, we see that $\beta(v^2) = 0$ for every $v \in H^2(B; \mathbb{Z}\_2)$, so every such class arises as $w\_2(E)$ for some $E$. Therefore, we must have $H^2(B; \mathbb{Z}\_2) = 0$. The claim now follows by Poincaré duality.
Here is another obstruction. > > Suppose $M^n$ is a closed simply connected manifold which admits only trivial vector bundles. Then $M$ cannot be a $\mathbb{Z}/2\mathbb{Z}$-homology sphere, unless $n=3$. > > > I'm not sure if the hypothesis that $M$ is simply connected is necessary, but it's certainly necessary in the proof. Together with the end of Michael Albanese's answer, this implies that every simply connected $5$-manifold admits a non-trivial vector bundle. **Proof Sketch**: By the work in the other answers, we already know that if $M$ admits only trivial vector bundles, then $M$ is odd dimensional, orientable, and it has the rational homology of a sphere. Thus, we may assume $n\geq 5$. Now, assume for a contradiction that all the torsion in $H^\ast(M)$ is of odd order. Let $k$ denote the least common multiple of the orders of the torsion and note that $k$ is odd. Because $M$ is orientable, it has a degree $1$ map $f:M\rightarrow S^n$. We will construct a non-trivial vector bundle on $M$ by pulling back a non-trivial bundle $E$ over $S^n$ along $f$. When $n\neq 7$, we may use the tangent bundle $E=TS^n$. When $n=7$, we let $E$ denote the rank $3$ vector bundle corresponding to a generator of $\pi\_7(BO(3))\cong \pi\_6(O(3)) = \pi\_6(S^3) = \mathbb{Z}/12\mathbb{Z}$. Let $\phi:S^n\rightarrow BO(s)$ denote the classifying map of the bundle $E$ (where $s = n$ if $n\neq 7$, and $s= 3$ when $n = 7$.) We claim that $f^\ast E$ is a non-trivial vector bundle over $M$. To see this, note that since $M$ is simply connected and all torsion is annihilated by $k$, there is a map $g:S^n\rightarrow E$ of degree $k^r$ for some integer $r\geq 1$. (See [the answer here for a proof.)](https://math.stackexchange.com/questions/2271532/if-m-is-a-rational-homology-sphere-is-there-a-map-sn-to-m-of-non-zero-deg) It is enough to show that $g^\ast(f^\ast E)$ is a non-trivial vector bundle over $S^n$. Of course, it is enough to show that the map $\phi\circ g\circ f:S^n\rightarrow BO(s)$ is homotopically non-trivial. We'll show this by showing the induced map on $\pi\_n$ is non-trivial. So, consider the induced map on $\pi\_n$. For $n\geq 5$ odd (except $n=7$), [Kervaire has shown](https://projecteuclid.org/journals/illinois-journal-of-mathematics/volume-4/issue-2/Some-nonstable-homotopy-groups-of-Lie-groups/10.1215/ijm/1255455861.full) that $\pi\_n(BO(n))\cong \pi\_{n-1}(O(n))$ is either $\mathbb{Z}/2\mathbb{Z}$ or $(\mathbb{Z}/2\mathbb{Z})^2$. When $n\neq 7$, the fact that $E$ is non-trivial implies that $\phi\_\ast$ is non-trivial, so, for $n\neq 7$, the kernel of the map $\phi\_\ast:\pi\_n(S^n)\rightarrow \pi\_n(BO(n))$ is the even integers. On the other hand, by our choice of $E$ when $n=7$, we have $\ker \phi\_\ast = 12\mathbb{Z}$. In either case, the image of $(g\circ f)\_\ast:\pi\_n(S^n)\rightarrow \pi\_n(S^n)$ is multiplication by the odd number $k^r$, so not contained in $\ker \phi\_\ast$. The completes the sketch. $\square$.
416,977
Let $B$ be a paracompact space with the property that any (topological) vector bundle $E \to B$ is trivial. What are some non-trivial examples of such spaces, and are there any interesting properties that characterize them? For simple known examples we of course have contractible spaces, as well as the 3-sphere $S^3$. This one follows from the fact that its rank $n$ vector bundles are classified by $\pi\_3 (BO(n)) = \pi\_2 (O(n)) = 0$. I'm primarily interested in the case where $B$ is a closed manifold. Do we know any other such examples? There is this [nice answer](https://math.stackexchange.com/a/1108129/354855) to a MSE question which talks about using the Whitehead tower of the appropriate classifying space to determine whether a bundle is trivial or not. This seems like a nice tool (of which I am not familiar with) to approaching this problem. As a secondary question, could I ask for some insight/references to this approach? **EDIT** Now that we know from the answers all the examples for closed $3$-manifolds, I guess I can now update the question to the case of higher odd dimensions. Does there exist a higher dimensional example?
2022/02/25
[ "https://mathoverflow.net/questions/416977", "https://mathoverflow.net", "https://mathoverflow.net/users/143629/" ]
Here is one constraint, which seems relevant in light of Michael Albanese's answer: **Claim:** Let $B$ be a closed orientable odd-dimensional manifold with no stably nontrivial complex vector bundles. Then $B$ is a rational homology sphere (of odd dimension). **Proof:** 1. By Bott periodicity, $\widetilde{KU}^\ast(B)$ is concentrated in odd dimensions. 2. Now, $\widetilde H^\ast(B; \mathbb Q[\beta^\pm])$ (with $|\beta| = 2$) is the rationalization of $\widetilde{KU}^\ast(B)$, so it is also concentrated in odd dimensions. So $\widetilde H^\ast(B; \mathbb Q)$ is also concentrated in odd dimensions. 3. Now since $B$ is odd-dimensional, it follows by Poincaré duality that $B$ is a rational homology sphere.
Here is another obstruction. > > Suppose $M^n$ is a closed simply connected manifold which admits only trivial vector bundles. Then $M$ cannot be a $\mathbb{Z}/2\mathbb{Z}$-homology sphere, unless $n=3$. > > > I'm not sure if the hypothesis that $M$ is simply connected is necessary, but it's certainly necessary in the proof. Together with the end of Michael Albanese's answer, this implies that every simply connected $5$-manifold admits a non-trivial vector bundle. **Proof Sketch**: By the work in the other answers, we already know that if $M$ admits only trivial vector bundles, then $M$ is odd dimensional, orientable, and it has the rational homology of a sphere. Thus, we may assume $n\geq 5$. Now, assume for a contradiction that all the torsion in $H^\ast(M)$ is of odd order. Let $k$ denote the least common multiple of the orders of the torsion and note that $k$ is odd. Because $M$ is orientable, it has a degree $1$ map $f:M\rightarrow S^n$. We will construct a non-trivial vector bundle on $M$ by pulling back a non-trivial bundle $E$ over $S^n$ along $f$. When $n\neq 7$, we may use the tangent bundle $E=TS^n$. When $n=7$, we let $E$ denote the rank $3$ vector bundle corresponding to a generator of $\pi\_7(BO(3))\cong \pi\_6(O(3)) = \pi\_6(S^3) = \mathbb{Z}/12\mathbb{Z}$. Let $\phi:S^n\rightarrow BO(s)$ denote the classifying map of the bundle $E$ (where $s = n$ if $n\neq 7$, and $s= 3$ when $n = 7$.) We claim that $f^\ast E$ is a non-trivial vector bundle over $M$. To see this, note that since $M$ is simply connected and all torsion is annihilated by $k$, there is a map $g:S^n\rightarrow E$ of degree $k^r$ for some integer $r\geq 1$. (See [the answer here for a proof.)](https://math.stackexchange.com/questions/2271532/if-m-is-a-rational-homology-sphere-is-there-a-map-sn-to-m-of-non-zero-deg) It is enough to show that $g^\ast(f^\ast E)$ is a non-trivial vector bundle over $S^n$. Of course, it is enough to show that the map $\phi\circ g\circ f:S^n\rightarrow BO(s)$ is homotopically non-trivial. We'll show this by showing the induced map on $\pi\_n$ is non-trivial. So, consider the induced map on $\pi\_n$. For $n\geq 5$ odd (except $n=7$), [Kervaire has shown](https://projecteuclid.org/journals/illinois-journal-of-mathematics/volume-4/issue-2/Some-nonstable-homotopy-groups-of-Lie-groups/10.1215/ijm/1255455861.full) that $\pi\_n(BO(n))\cong \pi\_{n-1}(O(n))$ is either $\mathbb{Z}/2\mathbb{Z}$ or $(\mathbb{Z}/2\mathbb{Z})^2$. When $n\neq 7$, the fact that $E$ is non-trivial implies that $\phi\_\ast$ is non-trivial, so, for $n\neq 7$, the kernel of the map $\phi\_\ast:\pi\_n(S^n)\rightarrow \pi\_n(BO(n))$ is the even integers. On the other hand, by our choice of $E$ when $n=7$, we have $\ker \phi\_\ast = 12\mathbb{Z}$. In either case, the image of $(g\circ f)\_\ast:\pi\_n(S^n)\rightarrow \pi\_n(S^n)$ is multiplication by the odd number $k^r$, so not contained in $\ker \phi\_\ast$. The completes the sketch. $\square$.
43,502,432
I am writing tests for a simple REST service in GoLang. But, because I am using [julienschmidt/httprouter](https://github.com/julienschmidt/httprouter) as the routing library. I am struggling on how to write test. main.go ``` package main func main() { router := httprouter.New() bookController := controllers.NewBookController() router.GET("/book/:id", bookController.GetBook) http.ListenAndServe(":8080", router) } ``` controllers ``` package controllers type BookController struct {} func NewBookController *BookController { return &BookController() } func (bc BookController) GetBook(w http.ResponseWriter, r *http.Request, p httprouter.Params) { fmt.Fprintf(w,"%s", p) } ``` My question is: How can test this while GetBook is neither HttpHandler nor HttpHandle If I use a traditional handler, the test will be easy like this ``` func TestGetBook(t *testing.T) { req, _ := http.NewRequest("GET", "/book/sampleid", nil) rr := httptest.NewRecorder() handler := controllers.NewBookController().GetBook handler.ServeHTTP(rr,req) if status := rr.code; status != http.StatusOK { t.Errorf("Wrong status") } } ``` The problem is, httprouter is not handler, or handlefunc. So I am stuck now
2017/04/19
[ "https://Stackoverflow.com/questions/43502432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490615/" ]
Just spin up a new router for each test and then register the handler under test, then pass the test request to the router, not the handler, so that the router can parse the path parameters and pass them to the handler. ``` func TestGetBook(t *testing.T) { handler := controllers.NewBookController() router := httprouter.New() router.GET("/book/:id", handler.GetBook) req, _ := http.NewRequest("GET", "/book/sampleid", nil) rr := httptest.NewRecorder() router.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("Wrong status") } } ```
You need to wrap your handler so that it can be accessed as an `http.HandlerFunc`: ``` func TestGetBook(t *testing.T) { req, _ := http.NewRequest("GET", "/book/sampleid", nil) rr := httptest.NewRecorder() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { controllers.NewBookController().GetBook(w, r, httprouter.Params{}) }) handler.ServeHTTP(rr,req) if status := rr.code; status != http.StatusOK { t.Errorf("Wrong status") } } ``` If your handler requires parameters, you'll either have to parse them manually from the request, or just supply them as the third argument.
43,502,432
I am writing tests for a simple REST service in GoLang. But, because I am using [julienschmidt/httprouter](https://github.com/julienschmidt/httprouter) as the routing library. I am struggling on how to write test. main.go ``` package main func main() { router := httprouter.New() bookController := controllers.NewBookController() router.GET("/book/:id", bookController.GetBook) http.ListenAndServe(":8080", router) } ``` controllers ``` package controllers type BookController struct {} func NewBookController *BookController { return &BookController() } func (bc BookController) GetBook(w http.ResponseWriter, r *http.Request, p httprouter.Params) { fmt.Fprintf(w,"%s", p) } ``` My question is: How can test this while GetBook is neither HttpHandler nor HttpHandle If I use a traditional handler, the test will be easy like this ``` func TestGetBook(t *testing.T) { req, _ := http.NewRequest("GET", "/book/sampleid", nil) rr := httptest.NewRecorder() handler := controllers.NewBookController().GetBook handler.ServeHTTP(rr,req) if status := rr.code; status != http.StatusOK { t.Errorf("Wrong status") } } ``` The problem is, httprouter is not handler, or handlefunc. So I am stuck now
2017/04/19
[ "https://Stackoverflow.com/questions/43502432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490615/" ]
Just spin up a new router for each test and then register the handler under test, then pass the test request to the router, not the handler, so that the router can parse the path parameters and pass them to the handler. ``` func TestGetBook(t *testing.T) { handler := controllers.NewBookController() router := httprouter.New() router.GET("/book/:id", handler.GetBook) req, _ := http.NewRequest("GET", "/book/sampleid", nil) rr := httptest.NewRecorder() router.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("Wrong status") } } ```
here is one more good blog and corresponding working code for this: > > <https://medium.com/@gauravsingharoy/build-your-first-api-server-with-httprouter-in-golang-732b7b01f6ab> > > > <https://github.com/gsingharoy/httprouter-tutorial/blob/master/part4/handlers_test.go> > > >
43,502,432
I am writing tests for a simple REST service in GoLang. But, because I am using [julienschmidt/httprouter](https://github.com/julienschmidt/httprouter) as the routing library. I am struggling on how to write test. main.go ``` package main func main() { router := httprouter.New() bookController := controllers.NewBookController() router.GET("/book/:id", bookController.GetBook) http.ListenAndServe(":8080", router) } ``` controllers ``` package controllers type BookController struct {} func NewBookController *BookController { return &BookController() } func (bc BookController) GetBook(w http.ResponseWriter, r *http.Request, p httprouter.Params) { fmt.Fprintf(w,"%s", p) } ``` My question is: How can test this while GetBook is neither HttpHandler nor HttpHandle If I use a traditional handler, the test will be easy like this ``` func TestGetBook(t *testing.T) { req, _ := http.NewRequest("GET", "/book/sampleid", nil) rr := httptest.NewRecorder() handler := controllers.NewBookController().GetBook handler.ServeHTTP(rr,req) if status := rr.code; status != http.StatusOK { t.Errorf("Wrong status") } } ``` The problem is, httprouter is not handler, or handlefunc. So I am stuck now
2017/04/19
[ "https://Stackoverflow.com/questions/43502432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490615/" ]
Just spin up a new router for each test and then register the handler under test, then pass the test request to the router, not the handler, so that the router can parse the path parameters and pass them to the handler. ``` func TestGetBook(t *testing.T) { handler := controllers.NewBookController() router := httprouter.New() router.GET("/book/:id", handler.GetBook) req, _ := http.NewRequest("GET", "/book/sampleid", nil) rr := httptest.NewRecorder() router.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("Wrong status") } } ```
u can try this without `ServeHTTP` ``` func TestGetBook(t *testing.T) { req := httptest.NewRequest("GET", "http://example.com/foo", nil) w := httptest.NewRecorder() controllers.NewBookController().GetBook(w, req, []httprouter.Param{{Key: "id", Value: "101"}}) resp := w.Result() body, _ := ioutil.ReadAll(resp.Body) t.Log(resp.StatusCode) t.Log(resp.Header.Get("Content-Type")) t.Log(string(body)) } ```
43,502,432
I am writing tests for a simple REST service in GoLang. But, because I am using [julienschmidt/httprouter](https://github.com/julienschmidt/httprouter) as the routing library. I am struggling on how to write test. main.go ``` package main func main() { router := httprouter.New() bookController := controllers.NewBookController() router.GET("/book/:id", bookController.GetBook) http.ListenAndServe(":8080", router) } ``` controllers ``` package controllers type BookController struct {} func NewBookController *BookController { return &BookController() } func (bc BookController) GetBook(w http.ResponseWriter, r *http.Request, p httprouter.Params) { fmt.Fprintf(w,"%s", p) } ``` My question is: How can test this while GetBook is neither HttpHandler nor HttpHandle If I use a traditional handler, the test will be easy like this ``` func TestGetBook(t *testing.T) { req, _ := http.NewRequest("GET", "/book/sampleid", nil) rr := httptest.NewRecorder() handler := controllers.NewBookController().GetBook handler.ServeHTTP(rr,req) if status := rr.code; status != http.StatusOK { t.Errorf("Wrong status") } } ``` The problem is, httprouter is not handler, or handlefunc. So I am stuck now
2017/04/19
[ "https://Stackoverflow.com/questions/43502432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490615/" ]
You need to wrap your handler so that it can be accessed as an `http.HandlerFunc`: ``` func TestGetBook(t *testing.T) { req, _ := http.NewRequest("GET", "/book/sampleid", nil) rr := httptest.NewRecorder() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { controllers.NewBookController().GetBook(w, r, httprouter.Params{}) }) handler.ServeHTTP(rr,req) if status := rr.code; status != http.StatusOK { t.Errorf("Wrong status") } } ``` If your handler requires parameters, you'll either have to parse them manually from the request, or just supply them as the third argument.
here is one more good blog and corresponding working code for this: > > <https://medium.com/@gauravsingharoy/build-your-first-api-server-with-httprouter-in-golang-732b7b01f6ab> > > > <https://github.com/gsingharoy/httprouter-tutorial/blob/master/part4/handlers_test.go> > > >
43,502,432
I am writing tests for a simple REST service in GoLang. But, because I am using [julienschmidt/httprouter](https://github.com/julienschmidt/httprouter) as the routing library. I am struggling on how to write test. main.go ``` package main func main() { router := httprouter.New() bookController := controllers.NewBookController() router.GET("/book/:id", bookController.GetBook) http.ListenAndServe(":8080", router) } ``` controllers ``` package controllers type BookController struct {} func NewBookController *BookController { return &BookController() } func (bc BookController) GetBook(w http.ResponseWriter, r *http.Request, p httprouter.Params) { fmt.Fprintf(w,"%s", p) } ``` My question is: How can test this while GetBook is neither HttpHandler nor HttpHandle If I use a traditional handler, the test will be easy like this ``` func TestGetBook(t *testing.T) { req, _ := http.NewRequest("GET", "/book/sampleid", nil) rr := httptest.NewRecorder() handler := controllers.NewBookController().GetBook handler.ServeHTTP(rr,req) if status := rr.code; status != http.StatusOK { t.Errorf("Wrong status") } } ``` The problem is, httprouter is not handler, or handlefunc. So I am stuck now
2017/04/19
[ "https://Stackoverflow.com/questions/43502432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490615/" ]
You need to wrap your handler so that it can be accessed as an `http.HandlerFunc`: ``` func TestGetBook(t *testing.T) { req, _ := http.NewRequest("GET", "/book/sampleid", nil) rr := httptest.NewRecorder() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { controllers.NewBookController().GetBook(w, r, httprouter.Params{}) }) handler.ServeHTTP(rr,req) if status := rr.code; status != http.StatusOK { t.Errorf("Wrong status") } } ``` If your handler requires parameters, you'll either have to parse them manually from the request, or just supply them as the third argument.
u can try this without `ServeHTTP` ``` func TestGetBook(t *testing.T) { req := httptest.NewRequest("GET", "http://example.com/foo", nil) w := httptest.NewRecorder() controllers.NewBookController().GetBook(w, req, []httprouter.Param{{Key: "id", Value: "101"}}) resp := w.Result() body, _ := ioutil.ReadAll(resp.Body) t.Log(resp.StatusCode) t.Log(resp.Header.Get("Content-Type")) t.Log(string(body)) } ```
43,502,432
I am writing tests for a simple REST service in GoLang. But, because I am using [julienschmidt/httprouter](https://github.com/julienschmidt/httprouter) as the routing library. I am struggling on how to write test. main.go ``` package main func main() { router := httprouter.New() bookController := controllers.NewBookController() router.GET("/book/:id", bookController.GetBook) http.ListenAndServe(":8080", router) } ``` controllers ``` package controllers type BookController struct {} func NewBookController *BookController { return &BookController() } func (bc BookController) GetBook(w http.ResponseWriter, r *http.Request, p httprouter.Params) { fmt.Fprintf(w,"%s", p) } ``` My question is: How can test this while GetBook is neither HttpHandler nor HttpHandle If I use a traditional handler, the test will be easy like this ``` func TestGetBook(t *testing.T) { req, _ := http.NewRequest("GET", "/book/sampleid", nil) rr := httptest.NewRecorder() handler := controllers.NewBookController().GetBook handler.ServeHTTP(rr,req) if status := rr.code; status != http.StatusOK { t.Errorf("Wrong status") } } ``` The problem is, httprouter is not handler, or handlefunc. So I am stuck now
2017/04/19
[ "https://Stackoverflow.com/questions/43502432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490615/" ]
u can try this without `ServeHTTP` ``` func TestGetBook(t *testing.T) { req := httptest.NewRequest("GET", "http://example.com/foo", nil) w := httptest.NewRecorder() controllers.NewBookController().GetBook(w, req, []httprouter.Param{{Key: "id", Value: "101"}}) resp := w.Result() body, _ := ioutil.ReadAll(resp.Body) t.Log(resp.StatusCode) t.Log(resp.Header.Get("Content-Type")) t.Log(string(body)) } ```
here is one more good blog and corresponding working code for this: > > <https://medium.com/@gauravsingharoy/build-your-first-api-server-with-httprouter-in-golang-732b7b01f6ab> > > > <https://github.com/gsingharoy/httprouter-tutorial/blob/master/part4/handlers_test.go> > > >
128,186
I would like to calculate the Riemann sum of $\sin(x)$. Fun starts here: $$R = \frac{\pi}{n} \sum\_{j=1}^n \sin\left(\frac{\pi}{n}\cdot j\right)$$ What would be the simplest way to calculate the sum of $\sin\left(\frac{\pi}{n}\cdot j\right)$, so that one could proceed to evaluating the limit and thus getting the value of the Riemann sum, in other words - the integral? There maybe a way using $\mathbb{C}$?
2012/04/05
[ "https://math.stackexchange.com/questions/128186", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
There's a way to find an expression for the sum $$\sum\_{j = 1}^{n} \sin{(j \theta)}$$ by considering instead the geometric sum $$1 + z + z^2 + \cdots + z^n = \frac{z^{n+ 1} - 1}{z - 1} \quad \text{for $z \neq 1$}$$ in combination with Euler's formula by taking $ z = e^{i\theta} = \cos{\theta} + i \sin{\theta}$ and also using [De Moivre's formula](http://en.wikipedia.org/wiki/De_Moivre%27s_formula). Then you can find that $$\sum\_{j = 1}^{n} \sin{(j \theta)} = \frac{\cos{\left (\frac{\theta}{2} \right)} - \cos{\left ((n + \frac{1}{2})\theta \right )}}{2 \sin{ \left ( \frac{\theta}{2} \right )}}$$ This is a standard exercise in most complex analysis books or actually any book that introduces complex numbers. In your case you just have to take $\theta = \frac{\pi}{n}$.
Use $$ 2 \sin\left(\frac{\pi}{2 n} \right) \sin\left(\frac{\pi}{n} \cdot j \right) = \cos\left( \frac{\pi}{2n} (2j-1) \right) - \cos\left( \frac{\pi}{2n} (2j+1) \right) $$ Thus the sum telescopes $\sum\_{j=1}^n \left(g(j) - g(j+1) \right) = g(1) - g(n+1) $: $$ R\_n =\frac{\pi}{n} \sum\_{j=1}^n \sin\left(\frac{\pi}{n} \cdot j \right) = \frac{\pi}{2 n \sin\left( \frac{\pi}{2n} \right)} \left( \cos\left( \frac{\pi}{2n} \right) - \cos\left( \frac{\pi}{2n} (2n+1)\right) \right) = \frac{\pi}{n} \cdot \frac{1}{\tan\left( \frac{\pi}{2n} \right)} $$ The large $n$ limit is easy: $$ \lim\_{n \to \infty} R\_n = 2 \lim\_{n \to \infty} \frac{\pi}{2 n} \cdot \frac{1}{\tan\left( \frac{\pi}{2n} \right)} = 2 \lim\_{x \to 0} \frac{x}{\tan(x)} = 2 $$
771,864
I have a laptop (with Windows 8 pre-installed) that has been through numerous dual-boot configurations. At one point, I had removed everything and ran Linux Mint as the only OS. Eventually, I decided to remove that and reinstall Windows 8. Upon doing so, I had a number of drivers to install/update in order to restore some basic functionality (USB ports, HDMI, FN keys, etc.). This was relatively easy to fix as all the drivers I needed were online. The problem I'm left with though, that I haven't found anything which pertains to my specific situation, is that **I can no longer boot into UEFI mode**. When I was running Linux Mint as my sole OS, I left UEFI boot mode enabled with Secure and Fast boot both **off**. In order to reinstall Windows 8, I burned the ISO to a USB and the ONLY way it would work is if I turned UEFI mode off, and used *CSM Mode*. Since reinstalling Win8, I cannot boot into UEFI mode. Which is ultimately, I think, affecting my wishes to dual-boot Ubuntu alongside Windows again. Any ideas as to how to fix this? [![gparted warning screenshot](https://i.stack.imgur.com/FgcWJ.jpg)](https://i.stack.imgur.com/FgcWJ.jpg)
2014/06/22
[ "https://superuser.com/questions/771864", "https://superuser.com", "https://superuser.com/users/293349/" ]
Windows (and many other operating systems) **requires** GPT to be able to boot on UEFI systems. And some UEFI systems automatically boot on legacy BIOS mode if it detects the HDD as "legacy" MBR (although technically it's a buggy implementation). So you must convert the disk to GPT. But gparted is very slow on disk operations, and it can't convert MBR to GPT either (that's a long time ago, I don't know if newer versions can, but I doubt that it can). As a result if you don't want to lose data you must use other partitioning tools to convert. Some GUI examples: * [AOMEI Partition Assistant](http://www.disk-partition.com/help/convert-gpt-mbr-disk.html) * [Partition Wizard](http://www.partitionwizard.com/help/Convert-GPT-disk-to-MBR-disk.html) * [EaseUS Partition Master](https://www.easeus.com/partition-manager/epm-free.html) If you want to work with command line then there's [gdisk](http://www.rodsbooks.com/gdisk/) which can also convert MBR to GPT without data loss. Windows 10 has the same capability with [MBR2GPT.EXE](https://docs.microsoft.com/en-us/windows/deployment/mbr-to-gpt) > > `MBR2GPT.EXE` converts a disk from the Master Boot Record (MBR) to the GUID Partition Table (GPT) partition style without modifying or deleting data on the disk. The tool is designed to be run from a Windows Preinstallation Environment (Windows PE) command prompt, but can also be run from the full Windows 10 operating system (OS) by using the `/allowFullOS` option. > > > See also [Converting between GPT and MBR hard drive without losing data](https://superuser.com/q/1250895/241386)
> > Since reinstalling Win8, I cannot boot into UEFI mode. Which is > ultimately, I think, affecting my wishes to dual-boot Ubuntu alongside > Windows again. > > > Any ideas as to how to fix this? > > > I had the same problem on an ASUS Q500A laptop. I was attempting to multi-boot Windows 8, Debian, Fedora and Ubuntu. The idea was to install all the base operating systems first, and then spend the next two days in patching (in case one install blew out earlier install/patch work). My solution was to install Windows first, and then apply *all* the Windows patches. After all the Windows patches were installed, I could boot into UEFI and load the other OSes. And the "apply all Windows patches" included the required reboots too. Its not enough to just install the patches. Without the patches, I could not even get the UEFI boot screen to show. And I tried everything I could find to get to that boot screen - from pressing `ESC`, `F2`, `F10`, `F12`, etc. I even read the damn laptop manual and the manual on the Aptios Firmware. I could not find the behavior documented anywhere. Here's a few threads when I was trying to avoid the "fully patch Windows" solution: [How to enter UEFI on computer startup (what did Windows change)?](http://answers.microsoft.com/en-us/windows/forum/windows_8-windows_install/how-to-enter-uefi-on-computer-startup-what-did/5664905c-1344-4a55-a9e6-932daeb48f88) from Microsoft Forums and [Dual Boot Linux and Windows 8 on ASUS laptop (Windows 8 Installed)](https://superuser.com/questions/685806/dual-boot-linux-and-windows-8-on-asus-laptop-windows-8-installed) from Super User. And I never was able to determine who was at fault for locking me out of my own system (i.e., UEFI spec requirement, Microsoft logo requirement, Firmware feature, etc).
4,841,219
Is there a way to only print part of a string? For example, if I have ``` char *str = "hello there"; ``` Is there a way to just print `"hello"`, keeping in mind that the substring I want to print is variable length, not always 5 chars? I know that I could use a `for` loop and `putchar` or that I could copy the array and then add a null-terminator but I'm wondering if there's a more elegant way?
2011/01/30
[ "https://Stackoverflow.com/questions/4841219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/525814/" ]
Try this: ``` int length = 5; printf("%*.*s", length, length, "hello there"); ```
You can use [`strncpy`](http://www.opengroup.org/onlinepubs/000095399/functions/strncpy.html) to duplicate the part of your string you want to print, but you'd have to take care to add a null terminator, as `strncpy` won't do that if it doesn't encounter one in the source string. A better solution, as Jerry Coffin pointed out, is using the appropriate `*printf` function to write out or copy the substring you want. While `strncpy` can be dangerous in the hands of someone not used to it, it can be quicker in terms of execution time compared to a `printf`/`sprintf`/`fprintf` style solution, since there is none of the overhead of dealing with the formatting strings. My suggestion is to avoid `strncpy` if you can, but it's good to know about just in case. ``` size_t len = 5; char sub[6]; sub[5] = 0; strncpy(sub, str + 5, len); // char[] to copy to, char[] to copy from(plus offset // to first character desired), length you want to copy ```
4,841,219
Is there a way to only print part of a string? For example, if I have ``` char *str = "hello there"; ``` Is there a way to just print `"hello"`, keeping in mind that the substring I want to print is variable length, not always 5 chars? I know that I could use a `for` loop and `putchar` or that I could copy the array and then add a null-terminator but I'm wondering if there's a more elegant way?
2011/01/30
[ "https://Stackoverflow.com/questions/4841219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/525814/" ]
Try this: ``` int length = 5; printf("%*.*s", length, length, "hello there"); ```
*printf* and friends work well when that's all you want to do with the partial string, but for a more general solution: ``` char *s2 = s + offset; char c = s2[length]; // Temporarily save character... s2[length] = '\0'; // ...that will be replaced by a NULL f(s2); // Now do whatever you want with the temporarily truncated string s2[length] = c; // Finally, restore the character that we had saved ```
4,841,219
Is there a way to only print part of a string? For example, if I have ``` char *str = "hello there"; ``` Is there a way to just print `"hello"`, keeping in mind that the substring I want to print is variable length, not always 5 chars? I know that I could use a `for` loop and `putchar` or that I could copy the array and then add a null-terminator but I'm wondering if there's a more elegant way?
2011/01/30
[ "https://Stackoverflow.com/questions/4841219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/525814/" ]
This will work too: ``` fwrite(str, 1, len, stdout); ``` It will not have the overhead of parsing the format specifier. Obviously, to adjust the beginning of the substring, you can simply add the index to the pointer.
You can use [`strncpy`](http://www.opengroup.org/onlinepubs/000095399/functions/strncpy.html) to duplicate the part of your string you want to print, but you'd have to take care to add a null terminator, as `strncpy` won't do that if it doesn't encounter one in the source string. A better solution, as Jerry Coffin pointed out, is using the appropriate `*printf` function to write out or copy the substring you want. While `strncpy` can be dangerous in the hands of someone not used to it, it can be quicker in terms of execution time compared to a `printf`/`sprintf`/`fprintf` style solution, since there is none of the overhead of dealing with the formatting strings. My suggestion is to avoid `strncpy` if you can, but it's good to know about just in case. ``` size_t len = 5; char sub[6]; sub[5] = 0; strncpy(sub, str + 5, len); // char[] to copy to, char[] to copy from(plus offset // to first character desired), length you want to copy ```
4,841,219
Is there a way to only print part of a string? For example, if I have ``` char *str = "hello there"; ``` Is there a way to just print `"hello"`, keeping in mind that the substring I want to print is variable length, not always 5 chars? I know that I could use a `for` loop and `putchar` or that I could copy the array and then add a null-terminator but I'm wondering if there's a more elegant way?
2011/01/30
[ "https://Stackoverflow.com/questions/4841219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/525814/" ]
This will work too: ``` fwrite(str, 1, len, stdout); ``` It will not have the overhead of parsing the format specifier. Obviously, to adjust the beginning of the substring, you can simply add the index to the pointer.
*printf* and friends work well when that's all you want to do with the partial string, but for a more general solution: ``` char *s2 = s + offset; char c = s2[length]; // Temporarily save character... s2[length] = '\0'; // ...that will be replaced by a NULL f(s2); // Now do whatever you want with the temporarily truncated string s2[length] = c; // Finally, restore the character that we had saved ```
4,841,219
Is there a way to only print part of a string? For example, if I have ``` char *str = "hello there"; ``` Is there a way to just print `"hello"`, keeping in mind that the substring I want to print is variable length, not always 5 chars? I know that I could use a `for` loop and `putchar` or that I could copy the array and then add a null-terminator but I'm wondering if there's a more elegant way?
2011/01/30
[ "https://Stackoverflow.com/questions/4841219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/525814/" ]
You can use [`strncpy`](http://www.opengroup.org/onlinepubs/000095399/functions/strncpy.html) to duplicate the part of your string you want to print, but you'd have to take care to add a null terminator, as `strncpy` won't do that if it doesn't encounter one in the source string. A better solution, as Jerry Coffin pointed out, is using the appropriate `*printf` function to write out or copy the substring you want. While `strncpy` can be dangerous in the hands of someone not used to it, it can be quicker in terms of execution time compared to a `printf`/`sprintf`/`fprintf` style solution, since there is none of the overhead of dealing with the formatting strings. My suggestion is to avoid `strncpy` if you can, but it's good to know about just in case. ``` size_t len = 5; char sub[6]; sub[5] = 0; strncpy(sub, str + 5, len); // char[] to copy to, char[] to copy from(plus offset // to first character desired), length you want to copy ```
*printf* and friends work well when that's all you want to do with the partial string, but for a more general solution: ``` char *s2 = s + offset; char c = s2[length]; // Temporarily save character... s2[length] = '\0'; // ...that will be replaced by a NULL f(s2); // Now do whatever you want with the temporarily truncated string s2[length] = c; // Finally, restore the character that we had saved ```
117,902
Does anybody have experience creating languages for the world they are creating? I am world building for a comic, and I am by no means a linguist. If I could avoid making an entirely new language I would, but because the story is visually communicated through the pages of a comic book, readers will have to see writing at some point (like in town squares, books, etc). My only concern is if I draw scribbles on a book, it may compromise the reader's suspension of belief. Any advice? EDIT: The world I'm creating is arabian inspired. That means that it would make sense to create a language similar to arabic. Since I don't know how to read arabic, this can be somewhat of a challenge. I'm just wondering how I can get away with using a pseudo language based off of a language I can't even read in the first place.
2018/07/11
[ "https://worldbuilding.stackexchange.com/questions/117902", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/50265/" ]
There are a number of paths you can take, some of which may be easier than others while others may not get you where you want to go. **Create Your Own Full Fledged Language!** Obviously, this is the way of worldbuilder cum glossopoet. Channel your inner Tolkien and make your own fully functional language complete with grammar, lexicon, syntax, texts and writing systems and all of that diachronically (starting from an older level and "evolving" the language through time). Die-hard fans of your work will love you forever if you go this route! It sounds like this is not the way you want to go, but it is loads of fun! **Make a Language Sketch!** This is just a step below the first option. Here, you're creating enough grammar and lexicon and example sentences that fans of your work could write simple in-world messages and bits of lore. They can also use that knowledge to decode whatever hidden gems you place in your work, be it road signs or billboards or whatever. A good example of this kind of language invention in comics is Herge's *Syldavian* language in the Tintin series. **Make a Naming Language!** A naming language is basically a list of (say, 100 or 200) highly important words & phrases that you plan on using in your work. If it's sword-n-sorcery fantasy, you probably won't have a word for starship, but you might have words for the various races of beings, curse words, expressions of surprise & anger, greetings, benedictions, and the like. For the purposes of a visual work, even a naming language should be given its own writing system. **Do the Work Yourself!** This may involve an amount of study in how languages work (grammar) and sound (phonology) and are written. There are print resources ([Language Construction Kit](https://rads.stackoverflow.com/amzn/click/098447000X) & [Create a Language Clinic](https://rads.stackoverflow.com/amzn/click/B004EYUHYC)) as well as online resources ([Conlang List](https://listserv.brown.edu/conlang.html) & [CBB](http://aveneca.com/cbb/) for example) readily available to help you undertake the task. Some are geared towards writers (probably what you're interested in) while some are aimed at the hobbyist. [Constructed Languages Stack Exchange](https://conlang.stackexchange.com) exists to help you if you go this route. **Hire Someone to Do the Work for You!** Glossopoetry is an imaginative art. Making a good language is also a craft that takes practice and skill. If you think you can not or do not want to undertake that part of your project, you can consider extending a commission to a language inventor. This is how Dothraki got invented for Game of Thrones. The [Language Creation Society](https://conlang.org) exists, in part, to help connect people looking to have a bespoke language made with people who can make those languages. They can also help with questions of legalities, remuneration, properly crediting and so forth.
If you're not planning on using the language in the narrative, just in the background, you don't need to make a language, just design a few signs and labels. There's plenty of videogames and anime that do that. [![Ni No Kuni - Wrath of the White Witch](https://i.stack.imgur.com/YSQHn.jpg)](https://i.stack.imgur.com/YSQHn.jpg) [Ni No Kuni - Wrath of the White Witch](https://en.wikipedia.org/wiki/Ni_no_Kuni:_Wrath_of_the_White_Witch)
117,902
Does anybody have experience creating languages for the world they are creating? I am world building for a comic, and I am by no means a linguist. If I could avoid making an entirely new language I would, but because the story is visually communicated through the pages of a comic book, readers will have to see writing at some point (like in town squares, books, etc). My only concern is if I draw scribbles on a book, it may compromise the reader's suspension of belief. Any advice? EDIT: The world I'm creating is arabian inspired. That means that it would make sense to create a language similar to arabic. Since I don't know how to read arabic, this can be somewhat of a challenge. I'm just wondering how I can get away with using a pseudo language based off of a language I can't even read in the first place.
2018/07/11
[ "https://worldbuilding.stackexchange.com/questions/117902", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/50265/" ]
There are a number of paths you can take, some of which may be easier than others while others may not get you where you want to go. **Create Your Own Full Fledged Language!** Obviously, this is the way of worldbuilder cum glossopoet. Channel your inner Tolkien and make your own fully functional language complete with grammar, lexicon, syntax, texts and writing systems and all of that diachronically (starting from an older level and "evolving" the language through time). Die-hard fans of your work will love you forever if you go this route! It sounds like this is not the way you want to go, but it is loads of fun! **Make a Language Sketch!** This is just a step below the first option. Here, you're creating enough grammar and lexicon and example sentences that fans of your work could write simple in-world messages and bits of lore. They can also use that knowledge to decode whatever hidden gems you place in your work, be it road signs or billboards or whatever. A good example of this kind of language invention in comics is Herge's *Syldavian* language in the Tintin series. **Make a Naming Language!** A naming language is basically a list of (say, 100 or 200) highly important words & phrases that you plan on using in your work. If it's sword-n-sorcery fantasy, you probably won't have a word for starship, but you might have words for the various races of beings, curse words, expressions of surprise & anger, greetings, benedictions, and the like. For the purposes of a visual work, even a naming language should be given its own writing system. **Do the Work Yourself!** This may involve an amount of study in how languages work (grammar) and sound (phonology) and are written. There are print resources ([Language Construction Kit](https://rads.stackoverflow.com/amzn/click/098447000X) & [Create a Language Clinic](https://rads.stackoverflow.com/amzn/click/B004EYUHYC)) as well as online resources ([Conlang List](https://listserv.brown.edu/conlang.html) & [CBB](http://aveneca.com/cbb/) for example) readily available to help you undertake the task. Some are geared towards writers (probably what you're interested in) while some are aimed at the hobbyist. [Constructed Languages Stack Exchange](https://conlang.stackexchange.com) exists to help you if you go this route. **Hire Someone to Do the Work for You!** Glossopoetry is an imaginative art. Making a good language is also a craft that takes practice and skill. If you think you can not or do not want to undertake that part of your project, you can consider extending a commission to a language inventor. This is how Dothraki got invented for Game of Thrones. The [Language Creation Society](https://conlang.org) exists, in part, to help connect people looking to have a bespoke language made with people who can make those languages. They can also help with questions of legalities, remuneration, properly crediting and so forth.
I've just started developing my own proto-languages to base my story's language development on. So take what I say with a pinch of salt. If all you want is a different looking alphabet but you don't want to create actual new words and meanings etc, AND you want some sort of consistency other than just squiggles. I would recommend an [abugida](https://en.wikipedia.org/wiki/Abugida). It's mostly made up of syllable pairs, made up of a consonant and vowel combination. So, for example, *a bu gi da*. These languages can be written in latin squiggles or in their own native foreign looking squiggles. > > Abugidas include the extensive Brahmic family of scripts of South and Southeast Asia, Semitic Ethiopic scripts, and Canadian Aboriginal syllabics (which are themselves based in part on Brahmic scripts). > > > You can then just break down your English or whatever language you are using into syllable pairs etc. And then translate into your new foreign looking alphabet. It shouldn't make *any sense* in that foreign language, but it should *look* foreign.
117,902
Does anybody have experience creating languages for the world they are creating? I am world building for a comic, and I am by no means a linguist. If I could avoid making an entirely new language I would, but because the story is visually communicated through the pages of a comic book, readers will have to see writing at some point (like in town squares, books, etc). My only concern is if I draw scribbles on a book, it may compromise the reader's suspension of belief. Any advice? EDIT: The world I'm creating is arabian inspired. That means that it would make sense to create a language similar to arabic. Since I don't know how to read arabic, this can be somewhat of a challenge. I'm just wondering how I can get away with using a pseudo language based off of a language I can't even read in the first place.
2018/07/11
[ "https://worldbuilding.stackexchange.com/questions/117902", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/50265/" ]
There are a number of paths you can take, some of which may be easier than others while others may not get you where you want to go. **Create Your Own Full Fledged Language!** Obviously, this is the way of worldbuilder cum glossopoet. Channel your inner Tolkien and make your own fully functional language complete with grammar, lexicon, syntax, texts and writing systems and all of that diachronically (starting from an older level and "evolving" the language through time). Die-hard fans of your work will love you forever if you go this route! It sounds like this is not the way you want to go, but it is loads of fun! **Make a Language Sketch!** This is just a step below the first option. Here, you're creating enough grammar and lexicon and example sentences that fans of your work could write simple in-world messages and bits of lore. They can also use that knowledge to decode whatever hidden gems you place in your work, be it road signs or billboards or whatever. A good example of this kind of language invention in comics is Herge's *Syldavian* language in the Tintin series. **Make a Naming Language!** A naming language is basically a list of (say, 100 or 200) highly important words & phrases that you plan on using in your work. If it's sword-n-sorcery fantasy, you probably won't have a word for starship, but you might have words for the various races of beings, curse words, expressions of surprise & anger, greetings, benedictions, and the like. For the purposes of a visual work, even a naming language should be given its own writing system. **Do the Work Yourself!** This may involve an amount of study in how languages work (grammar) and sound (phonology) and are written. There are print resources ([Language Construction Kit](https://rads.stackoverflow.com/amzn/click/098447000X) & [Create a Language Clinic](https://rads.stackoverflow.com/amzn/click/B004EYUHYC)) as well as online resources ([Conlang List](https://listserv.brown.edu/conlang.html) & [CBB](http://aveneca.com/cbb/) for example) readily available to help you undertake the task. Some are geared towards writers (probably what you're interested in) while some are aimed at the hobbyist. [Constructed Languages Stack Exchange](https://conlang.stackexchange.com) exists to help you if you go this route. **Hire Someone to Do the Work for You!** Glossopoetry is an imaginative art. Making a good language is also a craft that takes practice and skill. If you think you can not or do not want to undertake that part of your project, you can consider extending a commission to a language inventor. This is how Dothraki got invented for Game of Thrones. The [Language Creation Society](https://conlang.org) exists, in part, to help connect people looking to have a bespoke language made with people who can make those languages. They can also help with questions of legalities, remuneration, properly crediting and so forth.
You could use **Amharic**. Benefits: 1: Region appropriate; supposedly Amharic is ancestral to Arabic and Hebrew. In an alternate timeline maybe it stayed. 2: Alphabet is unfamiliar looking to Western readers and I bet Arabic / Hebrew readers also. 3: It is in Google Translate which helps as regards making stuff up. Your text: እኔ ሙሉ በሙሉ አዲስ ቋንቋ ከመፍጠር መቆጠብ የምችል ከሆነ ፣ ግን ታሪኩ በኮሚክ መጽሐፍ ገጾች አማካይነት በእይታ የተላለፈ ስለሆነ አንባቢዎች በተወሰነ ደረጃ ጽሑፍን ማየት አለባቸው (እንደ የከተማ አደባባዮች ፣ መጻሕፍት ወዘተ ...) ፡፡ 4: It is discrete characters. Not cursive (which is intimidating). 5: There are people who read Amharic so make sure what you write in their language makes them smile.
6,390,960
``` class Bus<T> { static Bus() { foreach(FieldInfo fi in typeof(T).GetFields()) { if(fi.FieldType == typeof(Argument)) { fi.SetValue(typeof(T), new Argument("busyname", "busyvalue")); } } } } class Buss : Bus<Buss> { public static Argument field; } ``` Any ideas how to make this work so that a reference to the static field in Buss triggers the static constructor in Bus?
2011/06/17
[ "https://Stackoverflow.com/questions/6390960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/269061/" ]
The fact that this matters to you probably means that you are using static constructors wrong. With that in mind, you could make a static constructor in `Buss` that manually invokes the static constructor in `Bus`. Note that it's not possible to run a static constructor more than once.
[MSDN says](http://msdn.microsoft.com/en-us/library/aa645612%28v=vs.71%29.aspx) that 'Static constructors are not inherited'. I guess this is similar to static fields which are not inherited either.
6,390,960
``` class Bus<T> { static Bus() { foreach(FieldInfo fi in typeof(T).GetFields()) { if(fi.FieldType == typeof(Argument)) { fi.SetValue(typeof(T), new Argument("busyname", "busyvalue")); } } } } class Buss : Bus<Buss> { public static Argument field; } ``` Any ideas how to make this work so that a reference to the static field in Buss triggers the static constructor in Bus?
2011/06/17
[ "https://Stackoverflow.com/questions/6390960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/269061/" ]
The fact that this matters to you probably means that you are using static constructors wrong. With that in mind, you could make a static constructor in `Buss` that manually invokes the static constructor in `Bus`. Note that it's not possible to run a static constructor more than once.
The static constructor of a generic type is invoked exactly once per `Type`, when that type is referenced. Calling `Buss x = new Buss()` will invoke the static constructor of `Bus<Buss>`. Calling `Bus<Buss> x = new Bus<Buss>()` will also invoke the static constructor of `Bus<Buss>`, but it will do so for it's type argument `Buss`, setting `Buss.field`. If you create a `class Bugs : Bus<Buss>` it will never set `Bugs.field`, as it will first resolve the type argument `Buss`, which invokes the static constructor of it's base class `Bus<Buss>`, setting `Buss.field`. When it tries to call the static constructor of `Bugs` base class, it will think it had already invoked the static `Bus<Buss>` constructor and skip it. Basically if I copy paste your code, create a dummy `Argument` class and create a new instance of `Buss`, the static constructor *is* invoked and `Buss.field` *is* set to an instance of `Argument`, but I do recognize some strange behavoir here in which I'd have to advise not to use reflection from a static method to reach subclasses' statics. The example you provided only works because `Buss` is the type argument for itself.
6,390,960
``` class Bus<T> { static Bus() { foreach(FieldInfo fi in typeof(T).GetFields()) { if(fi.FieldType == typeof(Argument)) { fi.SetValue(typeof(T), new Argument("busyname", "busyvalue")); } } } } class Buss : Bus<Buss> { public static Argument field; } ``` Any ideas how to make this work so that a reference to the static field in Buss triggers the static constructor in Bus?
2011/06/17
[ "https://Stackoverflow.com/questions/6390960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/269061/" ]
The static constructor of a generic type is invoked exactly once per `Type`, when that type is referenced. Calling `Buss x = new Buss()` will invoke the static constructor of `Bus<Buss>`. Calling `Bus<Buss> x = new Bus<Buss>()` will also invoke the static constructor of `Bus<Buss>`, but it will do so for it's type argument `Buss`, setting `Buss.field`. If you create a `class Bugs : Bus<Buss>` it will never set `Bugs.field`, as it will first resolve the type argument `Buss`, which invokes the static constructor of it's base class `Bus<Buss>`, setting `Buss.field`. When it tries to call the static constructor of `Bugs` base class, it will think it had already invoked the static `Bus<Buss>` constructor and skip it. Basically if I copy paste your code, create a dummy `Argument` class and create a new instance of `Buss`, the static constructor *is* invoked and `Buss.field` *is* set to an instance of `Argument`, but I do recognize some strange behavoir here in which I'd have to advise not to use reflection from a static method to reach subclasses' statics. The example you provided only works because `Buss` is the type argument for itself.
[MSDN says](http://msdn.microsoft.com/en-us/library/aa645612%28v=vs.71%29.aspx) that 'Static constructors are not inherited'. I guess this is similar to static fields which are not inherited either.
28,781,377
I want to remove the subdomain from root path. I tried adding `:subdomain => false` to the `root` command in `routes.rb` file without success: when I enter manually a subdomain in the URL, the subdomain stays and will not be removed. Example: ``` my root is => lvh.me:3000 enter subdomain manually => xyz.lvh.me:3000 and hit enter then it remains the same ``` This is what I tried already in my `routes.rb` file, without success: ``` root :to => 'home#show', :subdomain => false or root :to => 'home#show', :constraints => { :subdomain => false }, via: [:get] ```
2015/02/28
[ "https://Stackoverflow.com/questions/28781377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3831672/" ]
Use [Visual Studio Online](http://visualstudioonline.com) to manage your Project, it is free for up to 5 users and you can use Git as your version control. Then you just create a new Project and add your code. AFter this it is easy to commit and sync your work on both computers.
Either use the VS community version; there is also a cloud version, or it could be shared with dropbox or onedrive and many others.
28,781,377
I want to remove the subdomain from root path. I tried adding `:subdomain => false` to the `root` command in `routes.rb` file without success: when I enter manually a subdomain in the URL, the subdomain stays and will not be removed. Example: ``` my root is => lvh.me:3000 enter subdomain manually => xyz.lvh.me:3000 and hit enter then it remains the same ``` This is what I tried already in my `routes.rb` file, without success: ``` root :to => 'home#show', :subdomain => false or root :to => 'home#show', :constraints => { :subdomain => false }, via: [:get] ```
2015/02/28
[ "https://Stackoverflow.com/questions/28781377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3831672/" ]
The best way is using version controlling system like Git
Either use the VS community version; there is also a cloud version, or it could be shared with dropbox or onedrive and many others.
28,781,377
I want to remove the subdomain from root path. I tried adding `:subdomain => false` to the `root` command in `routes.rb` file without success: when I enter manually a subdomain in the URL, the subdomain stays and will not be removed. Example: ``` my root is => lvh.me:3000 enter subdomain manually => xyz.lvh.me:3000 and hit enter then it remains the same ``` This is what I tried already in my `routes.rb` file, without success: ``` root :to => 'home#show', :subdomain => false or root :to => 'home#show', :constraints => { :subdomain => false }, via: [:get] ```
2015/02/28
[ "https://Stackoverflow.com/questions/28781377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3831672/" ]
The best way is using version controlling system like Git
Use [Visual Studio Online](http://visualstudioonline.com) to manage your Project, it is free for up to 5 users and you can use Git as your version control. Then you just create a new Project and add your code. AFter this it is easy to commit and sync your work on both computers.
164,479
I am writing a simple program with a producer and a few consumers: the producer pushes to a queue some integers, and the consumers pop elements from the queue and print them (order doesn't matter). The queue code can be found below (the implementation is based on [this](https://juanchopanzacpp.wordpress.com/2013/02/26/concurrent-queue-c11/) example). In addition to the regular `pop` and `push` operations, I want to add a `kill` method - this method will "kill" the queue but will let the consumers keep popping items until the queue is empty (hence the different implementation of `pop`). I am looking for an elegant way to do it. I want to know if this way is fine: ``` void kill() { _isAlive = false; _cv.notify_all(); } ``` I tried it, and it seems to work, but I am not sure about it - I thought that I might need to lock the `_mutex` again, like this: ``` void kill() { unique_lock<mutex> mlock(_mutex); _isAlive = false; mlock.unlock(); _cv.notify_all(); } ``` and at last, my first version looked like this: ``` void kill() { unique_lock<mutex> mlock(_mutex); _isAlive = false; mlock.unlock(); _cv.notify_all(); // wait until all elements are consumed while (!_queue.empty()); // busy loop - I know it's bad but it worked... // I tried the next line, but it got to a deadlock: //_cv.wait(mlock, [this] {return _queue.empty(); }); } ``` So I'd like to know which `kill` is the best for my purposes (reminder - all the `int`s in the queue must be printed!). A sample `main` is also shown below. Queue source code ----------------- Mainly based on [this](https://juanchopanzacpp.wordpress.com/2013/02/26/concurrent-queue-c11/): ``` #include <queue> #include <thread> #include <mutex> #include <condition_variable> #include <iostream> using namespace std; template <class T> class SafeQueue { queue<T> _queue; mutex _mutex; condition_variable _cv; bool _isAlive; public: struct IsDead {}; // for handling end of tournament SafeQueue() : _isAlive(true) {} // block copy & move ctors and assignments SafeQueue(const SafeQueue& other) = delete; SafeQueue& operator=(const SafeQueue& other) = delete; SafeQueue(SafeQueue&& other) noexcept = delete; SafeQueue& operator=(SafeQueue&& other) noexcept = delete; /* returns the first item of the queue and deletes it*/ T pop() { unique_lock<mutex> mlock(_mutex); _cv.wait(mlock, [this] {return !(_queue.empty() && _isAlive); }); // if the queue is not empty, we still want to consume the next game (even if _isAlive = false) if (!_queue.empty()) { T item = _queue.front(); _queue.pop(); return item; } // in this case the queue is empty - we notify all waiting threads (and especially the one that waits on kill()) mlock.unlock(); _cv.notify_all(); throw IsDead(); } void push(const T& item) { unique_lock<mutex> mlock(_mutex); _queue.push(item); mlock.unlock(); _cv.notify_one(); } void push(T&& item) { unique_lock<mutex> mlock(_mutex); _queue.push(std::move(item)); mlock.unlock(); _cv.notify_one(); } }; ``` Sample main ----------- ``` SafeQueue<int> q; mutex cout_mutex; void consumerMethod(int id) { while (true) { try { auto a = q.pop(); lock_guard<mutex> mlock(cout_mutex); cout << "#" << id << ": " << a << endl; } catch(SafeQueue<int>::IsDead&) { lock_guard<mutex> mlock(cout_mutex); cout << "#" << id << ": catched IsDead" << endl; return; } } } int main() { vector<thread> consumers(5); for (auto i = 0; i < 5; ++i) { consumers[i] = thread(consumerMethod, i + 1); } for (auto j = 0; j < 30; ++j) { q.push(j + 1); } q.kill(); for (auto& t : consumers) { t.join(); } return 0; } ```
2017/05/29
[ "https://codereview.stackexchange.com/questions/164479", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/139924/" ]
Let's start with `pop`. As many have noted, a `pop` that returns the value being removed from the collection can (will) cause problems unless copying (or moving) the value is guaranteed to be exception free. Unfortunately, the design used by the standard containers (use `front()` to retrieve the item, then `pop` to remove it) has an equally serious problem in the face of multiple threads (specifically, multiple consumers): you have to make a mutex visible to all the consumers of the queue, and they all have to cooperate correctly in its use for synchronization to work correctly. I'd much rather hide the synchronization inside the queue itself if at all reasonable--and in this case, it is entirely possible, with the right signature/design. Specifically, a signature I've found to work well is something like this: ``` bool pop(T &dest); ``` With this, `pop` can lock the mutex, copy `front()` to `dest`, and `pop_front()` to remove the item from the queue--and (just as we want) the item is removed if and only if the value made it to its destination correctly. In practical use, that does often get embellished with one addition: a timeout specified: ``` bool pop(T &dest, Duration const &dur); ``` This lets us specify that if the queue is empty when it's called, it'll wait up to some maximum period of time attempting to retrieve a value. Either way, if popping an item fails for any reason (including the queue being empty) it simply returns false to indicate failure. The next point is how to "kill" the queue. In reality, this isn't about killing the queue itself though--it's about killing all the queue's consumers. Rather than using a `notify_all` to tell them that the queue has been killed, I'd set a flag inside the queue itself. Then, rather than just passing `int`s through the queue, I'd pass some type of object that can inform the target that it's to cease processing jobs from the queue. Calling the `queue`'s `kill` just sets a flag. Then we add a bit to the queue's `pop` to check that flag, and if it's set it just gives the client a `cease processing` task: ``` class task { std::atomic_bool cease = false; int value; public: task() : cease(true) {} task(int value) : value(value) {} bool done() const { return cease; } int get_value() const { return value; } }; template <class T> class Q { std::deque<T> tasks; std::atomic_bool killed; public: Q() : killed(false) { } void kill() { killed = true; } bool pop(T &dest) { std::unique_lock // ... if (tasks.empty() && killed) { dest = task(); // default task has `cease` set to `true` return true; } else // normal return } // ... }; ``` This way, the parent does something like this: ``` Q q; for (int i=0; i<n; i++) q.push(i); q.kill(); ``` The queue itself will hand out tasks to its consumers as long as it has tasks for them to execute (regardless of whether `kill` has been called). After `kill` has been called *and* it's run out of tasks to give to clients, then it'll return a default constructed `task` to tell the client thread that processing is done. In a typical case, the client will look something like this: ``` task t; while (q.pop(t) && !t.done()) process(t); ``` As soon as it receives a task with `cease` set, it'll know it's done processing tasks (at least from this queue) so it'll drop out of the loop and can proceed appropriately (e.g., exit the thread, start trying to get tasks from some other queue, etc.) Another possibility is to keep the `queue` a "pure" queue--just something that queues up tasks and dispenses them to consumers. In this case, it has no `kill` at all, it just has `push`, `pop` and such. It's then up to the producer to queue up an appropriate number of `kill` tasks when it's produced all the "real" tasks: ``` queue q; for (int i=0; i<thread_count; i++) threads[i] = std::thread(i, q); for (int i=0; i<n; i++) q.push(task(i)); for (int i=0; i<thread_count; i++) q.push(task()); ``` In this case, consumer threads retrieve tasks to execute as long as there are any. Each then receives a "suicide" task. In response to that, it quits attempting to retrieve tasks to execute. This ensures that one `suicide` task will be distributed to each consumer thread.
There is no need to manually `unlock`. ``` void push(const T& item) { unique_lock<mutex> mlock(_mutex); _queue.push(item); mlock.unlock(); // This is not needed. _cv.notify_one(); } ``` Your pop is fine (apart from the `unlock()` as before). There are reason that most c++ queues separate front/pop [Why doesn't std::queue::pop return value.?](https://stackoverflow.com/q/25035691/14065) So we may need to re-think `pop()` and not use the traditional of pop. Why not pass `pop()` a function that is called for each value. ``` // Don't return a value // Pass a function to be called from each value. template<typename F> void pop(F f) { { // Make sure there is a value in the queue. unique_lock<mutex> mlock(_mutex); _cv.wait(mlock, [this] {return !(_queue.empty() && _isAlive); }); } if (!_queue.empty()) { // We can read the value without a lock? f(_queue.front()); // Just lock for modification. unique_lock<mutex> mlock(_mutex); _queue.pop(); return; } // Bad things happen. _cv.notify_all(); throw IsDead(); } ```
164,479
I am writing a simple program with a producer and a few consumers: the producer pushes to a queue some integers, and the consumers pop elements from the queue and print them (order doesn't matter). The queue code can be found below (the implementation is based on [this](https://juanchopanzacpp.wordpress.com/2013/02/26/concurrent-queue-c11/) example). In addition to the regular `pop` and `push` operations, I want to add a `kill` method - this method will "kill" the queue but will let the consumers keep popping items until the queue is empty (hence the different implementation of `pop`). I am looking for an elegant way to do it. I want to know if this way is fine: ``` void kill() { _isAlive = false; _cv.notify_all(); } ``` I tried it, and it seems to work, but I am not sure about it - I thought that I might need to lock the `_mutex` again, like this: ``` void kill() { unique_lock<mutex> mlock(_mutex); _isAlive = false; mlock.unlock(); _cv.notify_all(); } ``` and at last, my first version looked like this: ``` void kill() { unique_lock<mutex> mlock(_mutex); _isAlive = false; mlock.unlock(); _cv.notify_all(); // wait until all elements are consumed while (!_queue.empty()); // busy loop - I know it's bad but it worked... // I tried the next line, but it got to a deadlock: //_cv.wait(mlock, [this] {return _queue.empty(); }); } ``` So I'd like to know which `kill` is the best for my purposes (reminder - all the `int`s in the queue must be printed!). A sample `main` is also shown below. Queue source code ----------------- Mainly based on [this](https://juanchopanzacpp.wordpress.com/2013/02/26/concurrent-queue-c11/): ``` #include <queue> #include <thread> #include <mutex> #include <condition_variable> #include <iostream> using namespace std; template <class T> class SafeQueue { queue<T> _queue; mutex _mutex; condition_variable _cv; bool _isAlive; public: struct IsDead {}; // for handling end of tournament SafeQueue() : _isAlive(true) {} // block copy & move ctors and assignments SafeQueue(const SafeQueue& other) = delete; SafeQueue& operator=(const SafeQueue& other) = delete; SafeQueue(SafeQueue&& other) noexcept = delete; SafeQueue& operator=(SafeQueue&& other) noexcept = delete; /* returns the first item of the queue and deletes it*/ T pop() { unique_lock<mutex> mlock(_mutex); _cv.wait(mlock, [this] {return !(_queue.empty() && _isAlive); }); // if the queue is not empty, we still want to consume the next game (even if _isAlive = false) if (!_queue.empty()) { T item = _queue.front(); _queue.pop(); return item; } // in this case the queue is empty - we notify all waiting threads (and especially the one that waits on kill()) mlock.unlock(); _cv.notify_all(); throw IsDead(); } void push(const T& item) { unique_lock<mutex> mlock(_mutex); _queue.push(item); mlock.unlock(); _cv.notify_one(); } void push(T&& item) { unique_lock<mutex> mlock(_mutex); _queue.push(std::move(item)); mlock.unlock(); _cv.notify_one(); } }; ``` Sample main ----------- ``` SafeQueue<int> q; mutex cout_mutex; void consumerMethod(int id) { while (true) { try { auto a = q.pop(); lock_guard<mutex> mlock(cout_mutex); cout << "#" << id << ": " << a << endl; } catch(SafeQueue<int>::IsDead&) { lock_guard<mutex> mlock(cout_mutex); cout << "#" << id << ": catched IsDead" << endl; return; } } } int main() { vector<thread> consumers(5); for (auto i = 0; i < 5; ++i) { consumers[i] = thread(consumerMethod, i + 1); } for (auto j = 0; j < 30; ++j) { q.push(j + 1); } q.kill(); for (auto& t : consumers) { t.join(); } return 0; } ```
2017/05/29
[ "https://codereview.stackexchange.com/questions/164479", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/139924/" ]
The thing to remember is that C++ (as of C++11) has an "official" memory model, which defines what operations are legal and illegal according to the official spec. In particular, a program which contains a *data race* is not legal according to the official memory model. A *data race* is any occasion on which two different threads access the same data, at the same time, at least one of which is doing a *write*, and where there's no special-case synchronization primitive involved (for example, concurrent accesses to a `std::atomic` or a `std::mutex` are fine). --- ``` void kill() { _isAlive = false; _cv.notify_all(); } ``` This function will likely be fine in practice... until it matters! The problem is that you're modifying `bool _isAlive` in thread A while, simultaneously, you might be reading `_isAlive` from thread B (within `pop`). This is a *data race* and invalidates your program. --- ``` void kill() { unique_lock<mutex> mlock(_mutex); _isAlive = false; mlock.unlock(); _cv.notify_all(); } ``` This is better. You're no longer modifying `_isAlive` while another thread might be reading it, because both `kill` and `pop` touch `_isAlive` only under the mutex lock. So this code is data-race-free. However, your next modification breaks it again: ``` void kill() { unique_lock<mutex> mlock(_mutex); _isAlive = false; mlock.unlock(); _cv.notify_all(); // wait until all elements are consumed while (!_queue.empty()); // busy loop - I know it's bad but it worked... // I tried the next line, but it got to a deadlock: //_cv.wait(mlock, [this] {return _queue.empty(); }); } ``` Here you're reading `_queue` not-under-a-mutex-lock, while simultaneously `pop` might be writing to `_queue` (that is, it might be popping from it). So you have a data race and your program is invalid. Also, your "busy loop" ``` while (!_queue.empty()); ``` is highly likely to be optimized into an infinite loop by any modern compiler, since the compiler can see that `_queue.empty()` is a *loop invariant* — there is no code in the body of the loop that could conceivably change the status of the queue, so there's no point in testing the condition every time through the loop. If you want the compiler to know that there's *some other thread* participating in this loop, you'll have to explicitly tell the compiler that, via e.g. waiting on a condition variable. --- How many producers and how many consumers are you planning to have, by the way? If it's just 1 and 1 respectively (a Single-Producer-Single-Consumer or SPSC queue), then Loki's suggestion to omit some locks *might* be reasonable — although I still wouldn't recommend it. --- The simplest way to "wait for" this one-time condition is to use a one-shot `std::future<void>`: ``` template <class T> class SafeQueue { queue<T> _queue; mutex _mutex; condition_variable _cv; bool _isAlive; std::promise<void> _pAllDone; // NEW std::future<void> _fAllDone; // NEW T pop() { unique_lock<mutex> mlock(_mutex); while (_queue.empty() && _isAlive) { _cv.wait(mlock); } if (!_queue.empty()) { T item = std::move(_queue.front()); _queue.pop(); return item; } // in this case the queue is empty mlock.unlock(); try { _pAllDone.set_value(); } catch (...) {} // NEW _cv.notify_all(); throw IsDead(); } void kill() { unique_lock<mutex> mlock(_mutex); _isAlive = false; mlock.unlock(); _cv.notify_all(); _fAllDone.wait(); // NEW } }; ``` The try-catch is necessary if there might be more than one "consumer" thread trying to set the value of the promise. Also notice that we're assuming that there is *at least one* "consumer" thread; if there's only the "killer" left, then it'll wait forever since there's no "consumer" left to finish emptying the queue. --- Really, the logic for cleaning up the queue should probably be external to the queue class itself. The person who knows how best to deal with the lifetime and ownership of *the queue itself* is, by definition, outside of the queue class. For example, if *I* were killing a queue, I wouldn't want all of its consumers to "finish up" emptying the queue; I'd actually want the consumers to stop ASAP, and just discard whatever tasks were left in the queue. I might do that by having the "killer" push a "killer task" onto the queue, and then making sure that any consumer who dequeued that task (A) decremented some external "count of consumers still living", (B) requeued the killer task if that count were `>=1`, and then (C) killed itself. But if you only have a single consumer thread in *your* program, then the above idea might be overkill. It really depends on your use-case... which is why this logic shouldn't be part of the reusable queue class itself, if you can help it.
There is no need to manually `unlock`. ``` void push(const T& item) { unique_lock<mutex> mlock(_mutex); _queue.push(item); mlock.unlock(); // This is not needed. _cv.notify_one(); } ``` Your pop is fine (apart from the `unlock()` as before). There are reason that most c++ queues separate front/pop [Why doesn't std::queue::pop return value.?](https://stackoverflow.com/q/25035691/14065) So we may need to re-think `pop()` and not use the traditional of pop. Why not pass `pop()` a function that is called for each value. ``` // Don't return a value // Pass a function to be called from each value. template<typename F> void pop(F f) { { // Make sure there is a value in the queue. unique_lock<mutex> mlock(_mutex); _cv.wait(mlock, [this] {return !(_queue.empty() && _isAlive); }); } if (!_queue.empty()) { // We can read the value without a lock? f(_queue.front()); // Just lock for modification. unique_lock<mutex> mlock(_mutex); _queue.pop(); return; } // Bad things happen. _cv.notify_all(); throw IsDead(); } ```
164,479
I am writing a simple program with a producer and a few consumers: the producer pushes to a queue some integers, and the consumers pop elements from the queue and print them (order doesn't matter). The queue code can be found below (the implementation is based on [this](https://juanchopanzacpp.wordpress.com/2013/02/26/concurrent-queue-c11/) example). In addition to the regular `pop` and `push` operations, I want to add a `kill` method - this method will "kill" the queue but will let the consumers keep popping items until the queue is empty (hence the different implementation of `pop`). I am looking for an elegant way to do it. I want to know if this way is fine: ``` void kill() { _isAlive = false; _cv.notify_all(); } ``` I tried it, and it seems to work, but I am not sure about it - I thought that I might need to lock the `_mutex` again, like this: ``` void kill() { unique_lock<mutex> mlock(_mutex); _isAlive = false; mlock.unlock(); _cv.notify_all(); } ``` and at last, my first version looked like this: ``` void kill() { unique_lock<mutex> mlock(_mutex); _isAlive = false; mlock.unlock(); _cv.notify_all(); // wait until all elements are consumed while (!_queue.empty()); // busy loop - I know it's bad but it worked... // I tried the next line, but it got to a deadlock: //_cv.wait(mlock, [this] {return _queue.empty(); }); } ``` So I'd like to know which `kill` is the best for my purposes (reminder - all the `int`s in the queue must be printed!). A sample `main` is also shown below. Queue source code ----------------- Mainly based on [this](https://juanchopanzacpp.wordpress.com/2013/02/26/concurrent-queue-c11/): ``` #include <queue> #include <thread> #include <mutex> #include <condition_variable> #include <iostream> using namespace std; template <class T> class SafeQueue { queue<T> _queue; mutex _mutex; condition_variable _cv; bool _isAlive; public: struct IsDead {}; // for handling end of tournament SafeQueue() : _isAlive(true) {} // block copy & move ctors and assignments SafeQueue(const SafeQueue& other) = delete; SafeQueue& operator=(const SafeQueue& other) = delete; SafeQueue(SafeQueue&& other) noexcept = delete; SafeQueue& operator=(SafeQueue&& other) noexcept = delete; /* returns the first item of the queue and deletes it*/ T pop() { unique_lock<mutex> mlock(_mutex); _cv.wait(mlock, [this] {return !(_queue.empty() && _isAlive); }); // if the queue is not empty, we still want to consume the next game (even if _isAlive = false) if (!_queue.empty()) { T item = _queue.front(); _queue.pop(); return item; } // in this case the queue is empty - we notify all waiting threads (and especially the one that waits on kill()) mlock.unlock(); _cv.notify_all(); throw IsDead(); } void push(const T& item) { unique_lock<mutex> mlock(_mutex); _queue.push(item); mlock.unlock(); _cv.notify_one(); } void push(T&& item) { unique_lock<mutex> mlock(_mutex); _queue.push(std::move(item)); mlock.unlock(); _cv.notify_one(); } }; ``` Sample main ----------- ``` SafeQueue<int> q; mutex cout_mutex; void consumerMethod(int id) { while (true) { try { auto a = q.pop(); lock_guard<mutex> mlock(cout_mutex); cout << "#" << id << ": " << a << endl; } catch(SafeQueue<int>::IsDead&) { lock_guard<mutex> mlock(cout_mutex); cout << "#" << id << ": catched IsDead" << endl; return; } } } int main() { vector<thread> consumers(5); for (auto i = 0; i < 5; ++i) { consumers[i] = thread(consumerMethod, i + 1); } for (auto j = 0; j < 30; ++j) { q.push(j + 1); } q.kill(); for (auto& t : consumers) { t.join(); } return 0; } ```
2017/05/29
[ "https://codereview.stackexchange.com/questions/164479", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/139924/" ]
Let's start with `pop`. As many have noted, a `pop` that returns the value being removed from the collection can (will) cause problems unless copying (or moving) the value is guaranteed to be exception free. Unfortunately, the design used by the standard containers (use `front()` to retrieve the item, then `pop` to remove it) has an equally serious problem in the face of multiple threads (specifically, multiple consumers): you have to make a mutex visible to all the consumers of the queue, and they all have to cooperate correctly in its use for synchronization to work correctly. I'd much rather hide the synchronization inside the queue itself if at all reasonable--and in this case, it is entirely possible, with the right signature/design. Specifically, a signature I've found to work well is something like this: ``` bool pop(T &dest); ``` With this, `pop` can lock the mutex, copy `front()` to `dest`, and `pop_front()` to remove the item from the queue--and (just as we want) the item is removed if and only if the value made it to its destination correctly. In practical use, that does often get embellished with one addition: a timeout specified: ``` bool pop(T &dest, Duration const &dur); ``` This lets us specify that if the queue is empty when it's called, it'll wait up to some maximum period of time attempting to retrieve a value. Either way, if popping an item fails for any reason (including the queue being empty) it simply returns false to indicate failure. The next point is how to "kill" the queue. In reality, this isn't about killing the queue itself though--it's about killing all the queue's consumers. Rather than using a `notify_all` to tell them that the queue has been killed, I'd set a flag inside the queue itself. Then, rather than just passing `int`s through the queue, I'd pass some type of object that can inform the target that it's to cease processing jobs from the queue. Calling the `queue`'s `kill` just sets a flag. Then we add a bit to the queue's `pop` to check that flag, and if it's set it just gives the client a `cease processing` task: ``` class task { std::atomic_bool cease = false; int value; public: task() : cease(true) {} task(int value) : value(value) {} bool done() const { return cease; } int get_value() const { return value; } }; template <class T> class Q { std::deque<T> tasks; std::atomic_bool killed; public: Q() : killed(false) { } void kill() { killed = true; } bool pop(T &dest) { std::unique_lock // ... if (tasks.empty() && killed) { dest = task(); // default task has `cease` set to `true` return true; } else // normal return } // ... }; ``` This way, the parent does something like this: ``` Q q; for (int i=0; i<n; i++) q.push(i); q.kill(); ``` The queue itself will hand out tasks to its consumers as long as it has tasks for them to execute (regardless of whether `kill` has been called). After `kill` has been called *and* it's run out of tasks to give to clients, then it'll return a default constructed `task` to tell the client thread that processing is done. In a typical case, the client will look something like this: ``` task t; while (q.pop(t) && !t.done()) process(t); ``` As soon as it receives a task with `cease` set, it'll know it's done processing tasks (at least from this queue) so it'll drop out of the loop and can proceed appropriately (e.g., exit the thread, start trying to get tasks from some other queue, etc.) Another possibility is to keep the `queue` a "pure" queue--just something that queues up tasks and dispenses them to consumers. In this case, it has no `kill` at all, it just has `push`, `pop` and such. It's then up to the producer to queue up an appropriate number of `kill` tasks when it's produced all the "real" tasks: ``` queue q; for (int i=0; i<thread_count; i++) threads[i] = std::thread(i, q); for (int i=0; i<n; i++) q.push(task(i)); for (int i=0; i<thread_count; i++) q.push(task()); ``` In this case, consumer threads retrieve tasks to execute as long as there are any. Each then receives a "suicide" task. In response to that, it quits attempting to retrieve tasks to execute. This ensures that one `suicide` task will be distributed to each consumer thread.
The thing to remember is that C++ (as of C++11) has an "official" memory model, which defines what operations are legal and illegal according to the official spec. In particular, a program which contains a *data race* is not legal according to the official memory model. A *data race* is any occasion on which two different threads access the same data, at the same time, at least one of which is doing a *write*, and where there's no special-case synchronization primitive involved (for example, concurrent accesses to a `std::atomic` or a `std::mutex` are fine). --- ``` void kill() { _isAlive = false; _cv.notify_all(); } ``` This function will likely be fine in practice... until it matters! The problem is that you're modifying `bool _isAlive` in thread A while, simultaneously, you might be reading `_isAlive` from thread B (within `pop`). This is a *data race* and invalidates your program. --- ``` void kill() { unique_lock<mutex> mlock(_mutex); _isAlive = false; mlock.unlock(); _cv.notify_all(); } ``` This is better. You're no longer modifying `_isAlive` while another thread might be reading it, because both `kill` and `pop` touch `_isAlive` only under the mutex lock. So this code is data-race-free. However, your next modification breaks it again: ``` void kill() { unique_lock<mutex> mlock(_mutex); _isAlive = false; mlock.unlock(); _cv.notify_all(); // wait until all elements are consumed while (!_queue.empty()); // busy loop - I know it's bad but it worked... // I tried the next line, but it got to a deadlock: //_cv.wait(mlock, [this] {return _queue.empty(); }); } ``` Here you're reading `_queue` not-under-a-mutex-lock, while simultaneously `pop` might be writing to `_queue` (that is, it might be popping from it). So you have a data race and your program is invalid. Also, your "busy loop" ``` while (!_queue.empty()); ``` is highly likely to be optimized into an infinite loop by any modern compiler, since the compiler can see that `_queue.empty()` is a *loop invariant* — there is no code in the body of the loop that could conceivably change the status of the queue, so there's no point in testing the condition every time through the loop. If you want the compiler to know that there's *some other thread* participating in this loop, you'll have to explicitly tell the compiler that, via e.g. waiting on a condition variable. --- How many producers and how many consumers are you planning to have, by the way? If it's just 1 and 1 respectively (a Single-Producer-Single-Consumer or SPSC queue), then Loki's suggestion to omit some locks *might* be reasonable — although I still wouldn't recommend it. --- The simplest way to "wait for" this one-time condition is to use a one-shot `std::future<void>`: ``` template <class T> class SafeQueue { queue<T> _queue; mutex _mutex; condition_variable _cv; bool _isAlive; std::promise<void> _pAllDone; // NEW std::future<void> _fAllDone; // NEW T pop() { unique_lock<mutex> mlock(_mutex); while (_queue.empty() && _isAlive) { _cv.wait(mlock); } if (!_queue.empty()) { T item = std::move(_queue.front()); _queue.pop(); return item; } // in this case the queue is empty mlock.unlock(); try { _pAllDone.set_value(); } catch (...) {} // NEW _cv.notify_all(); throw IsDead(); } void kill() { unique_lock<mutex> mlock(_mutex); _isAlive = false; mlock.unlock(); _cv.notify_all(); _fAllDone.wait(); // NEW } }; ``` The try-catch is necessary if there might be more than one "consumer" thread trying to set the value of the promise. Also notice that we're assuming that there is *at least one* "consumer" thread; if there's only the "killer" left, then it'll wait forever since there's no "consumer" left to finish emptying the queue. --- Really, the logic for cleaning up the queue should probably be external to the queue class itself. The person who knows how best to deal with the lifetime and ownership of *the queue itself* is, by definition, outside of the queue class. For example, if *I* were killing a queue, I wouldn't want all of its consumers to "finish up" emptying the queue; I'd actually want the consumers to stop ASAP, and just discard whatever tasks were left in the queue. I might do that by having the "killer" push a "killer task" onto the queue, and then making sure that any consumer who dequeued that task (A) decremented some external "count of consumers still living", (B) requeued the killer task if that count were `>=1`, and then (C) killed itself. But if you only have a single consumer thread in *your* program, then the above idea might be overkill. It really depends on your use-case... which is why this logic shouldn't be part of the reusable queue class itself, if you can help it.
29,391,450
I recently had a comment in a code review: > > it's better to enumerate the fields explicitly. "select \*" doesn't > guarantee an order > > > Is that true in this case with a query like `select * from (select a,b,c ...)`? I can't imagine a database engine that would re-order the columns in the result, but then my imagination is more logical than some database engines.
2015/04/01
[ "https://Stackoverflow.com/questions/29391450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152580/" ]
The advice against `select *` is mainly for when you're querying tables directly. In some databases it's possible to insert a new column partway through a table, such that table `t (a, b)` becomes table `t (a, c, b)`. PostgreSQL does not (yet) support this, but it can still append columns, and it can drop columns from anywhere, so you can still get `t (a, c)` if you add `c` and drop `b`. This is why it's considered bad practice to use `*` in production queries, especially if your application relies on ordinal column position to read results. But really, that only applies to situations where you do not specify the fields elsewhere in the query. In your case you do so in the subquery. So `*` is perfectly safe and IMO quite acceptable in this usage. This: ``` select * from (select a,b,c ... from t) ``` is fine. This: ``` select * from t ``` or ``` select * from (select * from t) ``` are problematic, because they leave the column-order undefined to the application. Even then that's only a problem if your application *assumes* the column order without checking the query metadata. Personally I prefer to fully qualify my columns most of the time, but there sure are times when `*` is the most readable option. It's also, IMO, quite fine to use `select *` when the client application reads columns by name, not by ordinal. If your app never cares if `c` is the 2nd column or the 3rd because it uses the result metadata to build a row dictionary (like Perl's DBI or Python's psycopg2 can do) then there's no real reason not to just use `*`. There can be performance costs to `SELECT *` when you only need a subset of columns, though. Missed opportunities to use index-only scans, unnecessary fetching of out-of-line TOASTed data, and bandwidth wasted for unwanted values, among other things. So most of the time it's still not a great idea.
The columns are always in the order defined in the table. However the rows aren't always fetched in the same order if no order by clause is included.
71,873,058
I am calling an API from external source and want to do the registration based on given API. I have few problem: I would like to get the data and pass it to my view registration, but I am getting Undefined index:country. i know where I did wrong but I couldnt find the solution. in this method, I should declare my $countries right? ``` public function showRegistrationForm() { return view('auth.register'); } ``` but I declared at my register(Request $request) method ``` public function register(Request $request) { $country=$request->input('country'); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'test', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS =>'{ "country": "'.$country.'" }', CURLOPT_HTTPHEADER => array( 'accept: application/json', 'Content-Type: application/json', 'Cookie: device_view=full' ), )); if($password != $password_confirmation){ $msg = "passwords doesn't match"; }else { $msg = "passwords match"; } $response = curl_exec($curl); curl_close($curl); $registerArr= json_decode($response); if(!EMPTY($registerArr->message)){ // Bad credentials return $this->showRegistrationForm(); }else{ return redirect()->route('overview'); } } ``` and here is my blade view. I would like to get the countries using the dropdown ``` <div class="col-xs-6 col-sm-6"> <div class="form-group"> <select class="form-control" id="country" name="country" required> <option selected="true" disabled="disabled">Country</option> @foreach($countries as $country) <option value="{{$country->country_code}}"> {{$country->country_name}}</option> @endforeach </select> </div> </div> ``` and how do I know about the value name and text name? Because the API only showing the registration form without the value. Can someone help me? thank you
2022/04/14
[ "https://Stackoverflow.com/questions/71873058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10438190/" ]
I would convert everything to a string and then use some built-in methods: ``` def check(lst, n): lst = ''.join(map(str, lst)) n = str(n) pos = 0 for ch in lst: if pos < len(n) and ch == n[pos]: pos += 1 return pos == len(n) ``` Another very smart option using iterators: ``` def check(lst, n): lst = ''.join(map(str, lst)) n = str(n) it = iter(lst) return all(x in it for x in n) ``` Examples: ``` >>> check([1,2,3,1,5,7,8,8,0], 12358) True >>> check([1,2,3,1,5,7,8,8,0], 315782) False ```
You could convert the integer to a string, then to a list. Then for each element in the new list, check if it is in the number list. If it is, remove the element from both lists, removing just the element in the input number, and removing the element and every element before it on the list. Repeat for every element in the list. If the length of the input string at the end is 0, then you can construct the list
71,873,058
I am calling an API from external source and want to do the registration based on given API. I have few problem: I would like to get the data and pass it to my view registration, but I am getting Undefined index:country. i know where I did wrong but I couldnt find the solution. in this method, I should declare my $countries right? ``` public function showRegistrationForm() { return view('auth.register'); } ``` but I declared at my register(Request $request) method ``` public function register(Request $request) { $country=$request->input('country'); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'test', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS =>'{ "country": "'.$country.'" }', CURLOPT_HTTPHEADER => array( 'accept: application/json', 'Content-Type: application/json', 'Cookie: device_view=full' ), )); if($password != $password_confirmation){ $msg = "passwords doesn't match"; }else { $msg = "passwords match"; } $response = curl_exec($curl); curl_close($curl); $registerArr= json_decode($response); if(!EMPTY($registerArr->message)){ // Bad credentials return $this->showRegistrationForm(); }else{ return redirect()->route('overview'); } } ``` and here is my blade view. I would like to get the countries using the dropdown ``` <div class="col-xs-6 col-sm-6"> <div class="form-group"> <select class="form-control" id="country" name="country" required> <option selected="true" disabled="disabled">Country</option> @foreach($countries as $country) <option value="{{$country->country_code}}"> {{$country->country_name}}</option> @endforeach </select> </div> </div> ``` and how do I know about the value name and text name? Because the API only showing the registration form without the value. Can someone help me? thank you
2022/04/14
[ "https://Stackoverflow.com/questions/71873058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10438190/" ]
I would convert everything to a string and then use some built-in methods: ``` def check(lst, n): lst = ''.join(map(str, lst)) n = str(n) pos = 0 for ch in lst: if pos < len(n) and ch == n[pos]: pos += 1 return pos == len(n) ``` Another very smart option using iterators: ``` def check(lst, n): lst = ''.join(map(str, lst)) n = str(n) it = iter(lst) return all(x in it for x in n) ``` Examples: ``` >>> check([1,2,3,1,5,7,8,8,0], 12358) True >>> check([1,2,3,1,5,7,8,8,0], 315782) False ```
How about taking your input value (num), and converting it into a list of digits? For example, making the number '123' into an array, [1,2,3]. Then check the first member of the array, 1, to see if its in your list '1st'? If it isn't, you fail. If it is, you take note of where in the list '1st' the number one is found, and then search from that index number, in '1st' to the end of '1st' for the second digit. And repeat? If you get to the end of '1st', before you get to the end of the [1,2,3] array, you fail. If you get to the end of the [1,2,3] array before (or equal to) when you arrive at the end of the '1st' array.. you succeed!
71,873,058
I am calling an API from external source and want to do the registration based on given API. I have few problem: I would like to get the data and pass it to my view registration, but I am getting Undefined index:country. i know where I did wrong but I couldnt find the solution. in this method, I should declare my $countries right? ``` public function showRegistrationForm() { return view('auth.register'); } ``` but I declared at my register(Request $request) method ``` public function register(Request $request) { $country=$request->input('country'); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'test', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS =>'{ "country": "'.$country.'" }', CURLOPT_HTTPHEADER => array( 'accept: application/json', 'Content-Type: application/json', 'Cookie: device_view=full' ), )); if($password != $password_confirmation){ $msg = "passwords doesn't match"; }else { $msg = "passwords match"; } $response = curl_exec($curl); curl_close($curl); $registerArr= json_decode($response); if(!EMPTY($registerArr->message)){ // Bad credentials return $this->showRegistrationForm(); }else{ return redirect()->route('overview'); } } ``` and here is my blade view. I would like to get the countries using the dropdown ``` <div class="col-xs-6 col-sm-6"> <div class="form-group"> <select class="form-control" id="country" name="country" required> <option selected="true" disabled="disabled">Country</option> @foreach($countries as $country) <option value="{{$country->country_code}}"> {{$country->country_name}}</option> @endforeach </select> </div> </div> ``` and how do I know about the value name and text name? Because the API only showing the registration form without the value. Can someone help me? thank you
2022/04/14
[ "https://Stackoverflow.com/questions/71873058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10438190/" ]
I would convert everything to a string and then use some built-in methods: ``` def check(lst, n): lst = ''.join(map(str, lst)) n = str(n) pos = 0 for ch in lst: if pos < len(n) and ch == n[pos]: pos += 1 return pos == len(n) ``` Another very smart option using iterators: ``` def check(lst, n): lst = ''.join(map(str, lst)) n = str(n) it = iter(lst) return all(x in it for x in n) ``` Examples: ``` >>> check([1,2,3,1,5,7,8,8,0], 12358) True >>> check([1,2,3,1,5,7,8,8,0], 315782) False ```
I think this code helps you. ```py lst = [1,2,3,1,5,7,8,8,0] def check(num): try: letter_index = [lst.index(int(a)) for a in str(num)] except ValueError: # if value not in list return False return False result = False greater = letter_index[0] for i in letter_index: if i>=greater: lesser= i result =True else: return False return result num = int(input('\nEnter Positive integer (0 to stop):')) if check(num): print('True') else: print("False") ```
71,873,058
I am calling an API from external source and want to do the registration based on given API. I have few problem: I would like to get the data and pass it to my view registration, but I am getting Undefined index:country. i know where I did wrong but I couldnt find the solution. in this method, I should declare my $countries right? ``` public function showRegistrationForm() { return view('auth.register'); } ``` but I declared at my register(Request $request) method ``` public function register(Request $request) { $country=$request->input('country'); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'test', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS =>'{ "country": "'.$country.'" }', CURLOPT_HTTPHEADER => array( 'accept: application/json', 'Content-Type: application/json', 'Cookie: device_view=full' ), )); if($password != $password_confirmation){ $msg = "passwords doesn't match"; }else { $msg = "passwords match"; } $response = curl_exec($curl); curl_close($curl); $registerArr= json_decode($response); if(!EMPTY($registerArr->message)){ // Bad credentials return $this->showRegistrationForm(); }else{ return redirect()->route('overview'); } } ``` and here is my blade view. I would like to get the countries using the dropdown ``` <div class="col-xs-6 col-sm-6"> <div class="form-group"> <select class="form-control" id="country" name="country" required> <option selected="true" disabled="disabled">Country</option> @foreach($countries as $country) <option value="{{$country->country_code}}"> {{$country->country_name}}</option> @endforeach </select> </div> </div> ``` and how do I know about the value name and text name? Because the API only showing the registration form without the value. Can someone help me? thank you
2022/04/14
[ "https://Stackoverflow.com/questions/71873058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10438190/" ]
I would convert everything to a string and then use some built-in methods: ``` def check(lst, n): lst = ''.join(map(str, lst)) n = str(n) pos = 0 for ch in lst: if pos < len(n) and ch == n[pos]: pos += 1 return pos == len(n) ``` Another very smart option using iterators: ``` def check(lst, n): lst = ''.join(map(str, lst)) n = str(n) it = iter(lst) return all(x in it for x in n) ``` Examples: ``` >>> check([1,2,3,1,5,7,8,8,0], 12358) True >>> check([1,2,3,1,5,7,8,8,0], 315782) False ```
You can convert your list into string then find substring in that string like that: ```py lst = [1,2,3,1,5,7,8,8,0] list_as_string = ''.join(str(e) for e in lst) lst_lenght = len(lst) num1 = 0 num2 = 0 index = 0 max_index = 0 flag = True while (flag == True): num = int(input('\nEnter Positive integer (0 to stop):')) num1 = num num2 = num if (num <= 0): print('Finish') flag = False else: checking_number = input(f"Enter {lst_lenght} number: ") if len(checking_number) == lst_lenght: if checking_number in list_as_string: print(True) else: print(False) else: print(f"Wrong length: Please! Enter {lst_lenght} number: ") ```
71,873,058
I am calling an API from external source and want to do the registration based on given API. I have few problem: I would like to get the data and pass it to my view registration, but I am getting Undefined index:country. i know where I did wrong but I couldnt find the solution. in this method, I should declare my $countries right? ``` public function showRegistrationForm() { return view('auth.register'); } ``` but I declared at my register(Request $request) method ``` public function register(Request $request) { $country=$request->input('country'); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'test', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS =>'{ "country": "'.$country.'" }', CURLOPT_HTTPHEADER => array( 'accept: application/json', 'Content-Type: application/json', 'Cookie: device_view=full' ), )); if($password != $password_confirmation){ $msg = "passwords doesn't match"; }else { $msg = "passwords match"; } $response = curl_exec($curl); curl_close($curl); $registerArr= json_decode($response); if(!EMPTY($registerArr->message)){ // Bad credentials return $this->showRegistrationForm(); }else{ return redirect()->route('overview'); } } ``` and here is my blade view. I would like to get the countries using the dropdown ``` <div class="col-xs-6 col-sm-6"> <div class="form-group"> <select class="form-control" id="country" name="country" required> <option selected="true" disabled="disabled">Country</option> @foreach($countries as $country) <option value="{{$country->country_code}}"> {{$country->country_name}}</option> @endforeach </select> </div> </div> ``` and how do I know about the value name and text name? Because the API only showing the registration form without the value. Can someone help me? thank you
2022/04/14
[ "https://Stackoverflow.com/questions/71873058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10438190/" ]
I would convert everything to a string and then use some built-in methods: ``` def check(lst, n): lst = ''.join(map(str, lst)) n = str(n) pos = 0 for ch in lst: if pos < len(n) and ch == n[pos]: pos += 1 return pos == len(n) ``` Another very smart option using iterators: ``` def check(lst, n): lst = ''.join(map(str, lst)) n = str(n) it = iter(lst) return all(x in it for x in n) ``` Examples: ``` >>> check([1,2,3,1,5,7,8,8,0], 12358) True >>> check([1,2,3,1,5,7,8,8,0], 315782) False ```
A couple of other options (besides the already great answers): --- Compare lists: You convert your string number to a list and then check if it's in your starting list of numbers. As they are found, you pop the value from the starting list into a new list. Then check your new list at the end to see if it matches your input string: ``` yourlist = [1,2,3,1,5,7,8,8,0] yournumber = '12358' outlist = [] for num in list(yournumber): print(num) if int(num) in yourlist: outlist.append(str(yourlist.pop(yourlist.index(int(num))))) print("".join(outlist) == yournumber) >>>True ``` You may recognize the pattern (`for: if: somelist.append()`) that can be converted to list comprehension to shorten your code: ``` yourlist = [1,2,3,1,5,7,8,8,0] yournumber = '12358' outlist = [str(yourlist.pop(yourlist.index(int(x)))) for x in list(yournumber) if int(x) in yourlist] print("".join(outlist) == yournumber) >>>True ``` --- Use Regex: Another option here is to use regex. You can split your input string into a list, and then join it back together using `.*` as a delimiter. Then perform a regex match: ``` import re yourlist = [1,2,3,1,5,7,8,8,0] yournumber = '12358' #turn `yournumber` into "1.*2.*3.*5.*8" regex string rex=".*".join(list(yournumber)) #join your starting list into a string and test it with the regex: print(bool(re.match(rex, "".join(map(str, yourlist))))) >>>True ``` Note that if your list elements are more than a single digit or character this can fail: ``` yourlist = [10, 23, 5, 8] yournumber = '12358' ``` This will say "True" even though "10" isn't in the `yournumber` variable.
38,361,940
I need to get typescript to stop complaining about my code. It runs fine in the browser but fullscreen api are not official yet so typescript definitions aren't up to date. I am calling document.documentElement.msRequestFullscreen. This causes type error: ``` Property 'msRequestFullscreen' does not exist on type 'HTMLElement'. ``` Upon looking at lib.d.ts, I find this: ``` documentElement: HTMLElement; ``` So documentElement is set to type HTMLElement. I tried adding a custom definition to override documentElement. My Custom definition: ``` // Extend Document Typings interface Document { msExitFullscreen: any; mozCancelFullScreen: any; documentElement: { msRequestFullscreen: any; mozRequestFullScreen: any; } } ``` I tried extending the interface for Document but it gives error Error is: ``` lib.d.ts:5704:5 Duplicate identifier 'documentElement'. ``` My typescript class ``` export class ToggleFullScreen { viewFullScreenTriggerID: string; viewFullScreenClass: string; cancelFullScreenClass: string; viewFullscreenElem: any; activeIcon: string; notFullscreenIcon: string; isFullscreenIcon: string constructor() { this.viewFullScreenTriggerID = "#fullScreenTrigger"; this.viewFullScreenClass = "not-fullscreen"; this.cancelFullScreenClass = "is-fullscreen"; this.notFullscreenIcon = "/assets/icon/fullscreen-enter.svg"; this.isFullscreenIcon = "/assets/icon/fullscreen-exit.svg"; this.activeIcon = this.notFullscreenIcon; } toggleFullScreen() { this.viewFullscreenElem = document.querySelector(this.viewFullScreenTriggerID); if (this.viewFullscreenElem.classList.contains(this.viewFullScreenClass)) { var docElm = document.documentElement; if (docElm.requestFullscreen) { docElm.requestFullscreen(); } else if (docElm.msRequestFullscreen) { docElm.msRequestFullscreen(); } else if (docElm.mozRequestFullScreen) { docElm.mozRequestFullScreen(); } else if (docElm.webkitRequestFullScreen) { docElm.webkitRequestFullScreen(); } this.viewFullscreenElem.classList.toggle(this.viewFullScreenClass); this.viewFullscreenElem.classList.toggle(this.cancelFullScreenClass); this.activeIcon = this.isFullscreenIcon; } else if (this.viewFullscreenElem.classList.contains(this.cancelFullScreenClass)) { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } this.viewFullscreenElem.classList.toggle(this.viewFullScreenClass); this.viewFullscreenElem.classList.toggle(this.cancelFullScreenClass); this.activeIcon = this.notFullscreenIcon; } } } ``` What is the proper way to get typescript compile errors to stop? **UPDATE**: I found a workaround. Instead of trying to override documentElement, which is set to type HTMLElement, I extended HTMLElement and added the properties which were missing. ``` // Extend Document Typings interface Document { msExitFullscreen: any; mozCancelFullScreen: any; } interface HTMLElement { msRequestFullscreen(): void; mozRequestFullScreen(): void; } ```
2016/07/13
[ "https://Stackoverflow.com/questions/38361940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5376813/" ]
I'm using newer version of Typescript and I faced the same problem. I tried the solution above and it didn't work - it seemed that I was masking the existing interface. To be able to extend correctly both interfaces, I had to use a declare global: ``` declare global { interface Document { msExitFullscreen: any; mozCancelFullScreen: any; } interface HTMLElement { msRequestFullscreen: any; mozRequestFullScreen: any; } } ``` Doing so, I was able to correctly compile and use code like this: ``` fullScreenClick(e): any { var element = document.documentElement; if (!$('body').hasClass("full-screen")) { $('body').addClass("full-screen"); $('#fullscreen-toggler').addClass("active"); if (element.requestFullscreen) { element.requestFullscreen(); } else if (element.mozRequestFullScreen()) { element.mozRequestFullScreen(); } else if (element.webkitRequestFullscreen) { element.webkitRequestFullscreen(); } else if (element.msRequestFullscreen) { element.msRequestFullscreen(); } } else { $('body').removeClass("full-screen"); $('#fullscreen-toggler').removeClass("active"); if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } } } ```
You can't override existing properties of an existing interface, only add new ones. Based on the MDN [Using fullscreen mode](https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API) and [Element documentation](https://developer.mozilla.org/en-US/docs/Web/API/Element) you need to have: ``` Element.requestFullscreen() ``` Which exists in the `lib.d.ts` and `lib.es6.d.ts`. If you're missing `msRequestFullscreen` and `mozRequestFullScreen` then you need to add them to `Element`: ``` interface Document { msExitFullscreen: any; mozCancelFullScreen: any; } interface Element { msRequestFullscreen(): void; mozRequestFullScreen(): void; } document.documentElement.mozRequestFullScreen(); // no error ```
50,287,558
I want to use join with 3 dataframe, but there are some columns we don't need or have some duplicate name with other dataframes, so I want to drop some columns like below: ```py result_df = (aa_df.join(bb_df, 'id', 'left') .join(cc_df, 'id', 'left') .withColumnRenamed(bb_df.status, 'user_status')) ``` Please note that `status` column is in two dataframes, i.e. `aa_df` and `bb_df`. The above doesn't work. I also tried to use `withColumn`, but the new column is created, and the old column is still existed.
2018/05/11
[ "https://Stackoverflow.com/questions/50287558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9172344/" ]
If you are trying to rename the `status` column of `bb_df` dataframe then you can do so while joining as ``` result_df = aa_df.join(bb_df.withColumnRenamed('status', 'user_status'),'id', 'left').join(cc_df, 'id', 'left') ```
Please see the docs : [withColumnRenamed()](http://spark.apache.org/docs/2.2.0/api/python/pyspark.sql.html#pyspark.sql.DataFrame.withColumnRenamed) You need to pass the name of the existing column and the new name to the function. Both of these should be strings. ``` result_df = aa_df.join(bb_df,'id', 'left').join(cc_df, 'id', 'left').withColumnRenamed('status', 'user_status') ``` If you have 'status' columns in 2 dataframes, you can use them in the join as `aa_df.join(bb_df, ['id','status'], 'left')` assuming aa\_df and bb\_df have the common column. This way you will not end up having 2 'status' columns.
50,287,558
I want to use join with 3 dataframe, but there are some columns we don't need or have some duplicate name with other dataframes, so I want to drop some columns like below: ```py result_df = (aa_df.join(bb_df, 'id', 'left') .join(cc_df, 'id', 'left') .withColumnRenamed(bb_df.status, 'user_status')) ``` Please note that `status` column is in two dataframes, i.e. `aa_df` and `bb_df`. The above doesn't work. I also tried to use `withColumn`, but the new column is created, and the old column is still existed.
2018/05/11
[ "https://Stackoverflow.com/questions/50287558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9172344/" ]
> > I want to use join with 3 dataframe, but there are some columns we don't need or have some duplicate name with other dataframes > > > That's a fine use case for aliasing a Dataset using `alias` or `as` operators. > > **alias(alias: String): Dataset[T]** or **alias(alias: Symbol): Dataset[T]** > Returns a new Dataset with an alias set. Same as as. > > > **as(alias: String): Dataset[T]** or **as(alias: Symbol): Dataset[T]** > Returns a new Dataset with an alias set. > > > (And honestly I did only now see the `Symbol`-based variants.) **NOTE** There are two `as` operators, `as` for aliasing and `as` for type mapping. Consult the [Dataset](http://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.Dataset) API. After you've aliases a Dataset, you can reference columns using `[alias].[columnName]` format. This is particularly handy with joins and *star column dereferencing* using `*`. ``` val ds1 = spark.range(5) scala> ds1.as('one).select($"one.*").show +---+ | id| +---+ | 0| | 1| | 2| | 3| | 4| +---+ val ds2 = spark.range(10) // Using joins with aliased datasets // where clause is in a longer form to demo how ot reference columns by alias scala> ds1.as('one).join(ds2.as('two)).where($"one.id" === $"two.id").show +---+---+ | id| id| +---+---+ | 0| 0| | 1| 1| | 2| 2| | 3| 3| | 4| 4| +---+---+ ``` > > so I want to drop some columns like below > > > My general recommendation is not to `drop` columns, but `select` what you want to include in the result. That makes life more predictable as you know what you get (not what you don't). I was told that our brains work by positives which could also make a point for `select`. So, as you asked and I showed in the above example, the result has two columns of the same name `id`. The question is how to have only one. There are at least two answers with using the variant of `join` operator with the join columns or condition included (as you did show in your question), but that would not answer your real question about "dropping unwanted columns", would it? Given I prefer `select` (over `drop`), I'd do the following to have a single `id` column: ``` val q = ds1.as('one) .join(ds2.as('two)) .where($"one.id" === $"two.id") .select("one.*") // <-- select columns from "one" dataset scala> q.show +---+ | id| +---+ | 0| | 1| | 2| | 3| | 4| +---+ ``` Regardless of the reasons why you asked the question (which could also be answered with the points I raised above), let me answer the (burning) question how to use `withColumnRenamed` when there are two matching columns (after `join`). Let's assume you ended up with the following query and so you've got two `id` columns (per join side). ``` val q = ds1.as('one) .join(ds2.as('two)) .where($"one.id" === $"two.id") scala> q.show +---+---+ | id| id| +---+---+ | 0| 0| | 1| 1| | 2| 2| | 3| 3| | 4| 4| +---+---+ ``` `withColumnRenamed` won't work for this use case since it does not accept aliased column names. ``` scala> q.withColumnRenamed("one.id", "one_id").show +---+---+ | id| id| +---+---+ | 0| 0| | 1| 1| | 2| 2| | 3| 3| | 4| 4| +---+---+ ``` You could `select` the columns you're interested in as follows: ``` scala> q.select("one.id").show +---+ | id| +---+ | 0| | 1| | 2| | 3| | 4| +---+ scala> q.select("two.*").show +---+ | id| +---+ | 0| | 1| | 2| | 3| | 4| +---+ ```
Please see the docs : [withColumnRenamed()](http://spark.apache.org/docs/2.2.0/api/python/pyspark.sql.html#pyspark.sql.DataFrame.withColumnRenamed) You need to pass the name of the existing column and the new name to the function. Both of these should be strings. ``` result_df = aa_df.join(bb_df,'id', 'left').join(cc_df, 'id', 'left').withColumnRenamed('status', 'user_status') ``` If you have 'status' columns in 2 dataframes, you can use them in the join as `aa_df.join(bb_df, ['id','status'], 'left')` assuming aa\_df and bb\_df have the common column. This way you will not end up having 2 'status' columns.
50,287,558
I want to use join with 3 dataframe, but there are some columns we don't need or have some duplicate name with other dataframes, so I want to drop some columns like below: ```py result_df = (aa_df.join(bb_df, 'id', 'left') .join(cc_df, 'id', 'left') .withColumnRenamed(bb_df.status, 'user_status')) ``` Please note that `status` column is in two dataframes, i.e. `aa_df` and `bb_df`. The above doesn't work. I also tried to use `withColumn`, but the new column is created, and the old column is still existed.
2018/05/11
[ "https://Stackoverflow.com/questions/50287558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9172344/" ]
If you are trying to rename the `status` column of `bb_df` dataframe then you can do so while joining as ``` result_df = aa_df.join(bb_df.withColumnRenamed('status', 'user_status'),'id', 'left').join(cc_df, 'id', 'left') ```
> > I want to use join with 3 dataframe, but there are some columns we don't need or have some duplicate name with other dataframes > > > That's a fine use case for aliasing a Dataset using `alias` or `as` operators. > > **alias(alias: String): Dataset[T]** or **alias(alias: Symbol): Dataset[T]** > Returns a new Dataset with an alias set. Same as as. > > > **as(alias: String): Dataset[T]** or **as(alias: Symbol): Dataset[T]** > Returns a new Dataset with an alias set. > > > (And honestly I did only now see the `Symbol`-based variants.) **NOTE** There are two `as` operators, `as` for aliasing and `as` for type mapping. Consult the [Dataset](http://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.Dataset) API. After you've aliases a Dataset, you can reference columns using `[alias].[columnName]` format. This is particularly handy with joins and *star column dereferencing* using `*`. ``` val ds1 = spark.range(5) scala> ds1.as('one).select($"one.*").show +---+ | id| +---+ | 0| | 1| | 2| | 3| | 4| +---+ val ds2 = spark.range(10) // Using joins with aliased datasets // where clause is in a longer form to demo how ot reference columns by alias scala> ds1.as('one).join(ds2.as('two)).where($"one.id" === $"two.id").show +---+---+ | id| id| +---+---+ | 0| 0| | 1| 1| | 2| 2| | 3| 3| | 4| 4| +---+---+ ``` > > so I want to drop some columns like below > > > My general recommendation is not to `drop` columns, but `select` what you want to include in the result. That makes life more predictable as you know what you get (not what you don't). I was told that our brains work by positives which could also make a point for `select`. So, as you asked and I showed in the above example, the result has two columns of the same name `id`. The question is how to have only one. There are at least two answers with using the variant of `join` operator with the join columns or condition included (as you did show in your question), but that would not answer your real question about "dropping unwanted columns", would it? Given I prefer `select` (over `drop`), I'd do the following to have a single `id` column: ``` val q = ds1.as('one) .join(ds2.as('two)) .where($"one.id" === $"two.id") .select("one.*") // <-- select columns from "one" dataset scala> q.show +---+ | id| +---+ | 0| | 1| | 2| | 3| | 4| +---+ ``` Regardless of the reasons why you asked the question (which could also be answered with the points I raised above), let me answer the (burning) question how to use `withColumnRenamed` when there are two matching columns (after `join`). Let's assume you ended up with the following query and so you've got two `id` columns (per join side). ``` val q = ds1.as('one) .join(ds2.as('two)) .where($"one.id" === $"two.id") scala> q.show +---+---+ | id| id| +---+---+ | 0| 0| | 1| 1| | 2| 2| | 3| 3| | 4| 4| +---+---+ ``` `withColumnRenamed` won't work for this use case since it does not accept aliased column names. ``` scala> q.withColumnRenamed("one.id", "one_id").show +---+---+ | id| id| +---+---+ | 0| 0| | 1| 1| | 2| 2| | 3| 3| | 4| 4| +---+---+ ``` You could `select` the columns you're interested in as follows: ``` scala> q.select("one.id").show +---+ | id| +---+ | 0| | 1| | 2| | 3| | 4| +---+ scala> q.select("two.*").show +---+ | id| +---+ | 0| | 1| | 2| | 3| | 4| +---+ ```
48,214,751
Intro ===== I'm currently using the UPS Rate API to create a shipping plugin for a client to get an estimate on shipping charges for customers during checkout (among other things). I've briefly used Nodejs in the past, however this would be my first time using it in a production environment, and I want to ensure I'm using best practices for this application. Code ==== Below is the request I must send to UPS' API endpoint to get a shipping estimate: ``` { "UPSSecurity":{ "UsernameToken":{ "Username":"Your User Id", "Password":"Your Password" }, "ServiceAccessToken":{ "AccessLicenseNumber":"Your Access License" } }, "RateRequest":{ "Request":{ "RequestOption":"Rate", "TransactionReference":{ "CustomerContext":"Your Customer Context" } }, "Shipment":{ "Shipper":{ "Name":"Shipper Name", "ShipperNumber":"Shipper Number", "Address":{ "AddressLine":[ "Address Line ", "Address Line ", "Address Line " ], "City":"City", "StateProvinceCode":"State Province Code", "PostalCode":"Postal Code", "CountryCode":"US" } }, "ShipTo":{ "Name":"Ship To Name", "Address":{ "AddressLine":[ "Address Line ", "Address Line ", "Address Line " ], "City":"City", "StateProvinceCode":"State Province Code", "PostalCode":"Postal Code", "CountryCode":"US" } }, "ShipFrom":{ "Name":"Ship From Name", "Address":{ "AddressLine":[ "Address Line ", "Address Line ", "Address Line " ], "City":"City", "StateProvinceCode":"State Province Code", "PostalCode":"Postal Code", "CountryCode":"US" } }, "Service":{ "Code":"03", "Description":"Service Code Description" }, "Package":{ "PackagingType":{ "Code":"02", "Description":"Rate" }, "Dimensions":{ "UnitOfMeasurement":{ "Code":"IN", "Description":"inches" }, "Length":"5", "Width":"4", "Height":"3" }, "PackageWeight":{ "UnitOfMeasurement":{ "Code":"Lbs", "Description":"pounds" }, "Weight":"1" } }, "ShipmentRatingOptions":{ "NegotiatedRatesIndicator":"" } } } } ``` Seeing the amount of fields to fill out, whats the best way to approach this, while adhering to basic software engineering principles of low coupling and high cohesion? Should I do something similar to the code example below, but for each field section? ``` const shipToAddr1 = "A street with number" const shipToAddr2 = "Line 2 with number" const shipToAddr3 = "The third line" const shipToCity = "Boston" const shipToStateProvinceCode = "12" const shipToPostalCode = "01970" const shipToCountryCode = "US" const shipToName = "Bob Wallace" const packageLength = "10" const packageWidth = "5" const packageHeight = "18" const PackageWeight = "12" //See above code snippet var jsonRequest = {...} function writeShipToContents(json, shipToName, shipToAddr1, shipToAddr2, shipToAddr3){ json.RateRequest.Shipment.ShipTo.Name = shipToName json.RateRequest.Shipment.ShipTo.Address.AddressLine = [ shipToAddr1, shipToAddr2, shipToAddr3 ] } function writeShipFromContents(json){ ... } function writePackageDetails(json){ ... } function writeShipmentRequest(json){ writeShipToContents(json) writeShipFromContents(json) writePackageDetails(json) ... return json } writeShipmentRequest(jsonRequest) ``` My instinct is that many things are wrong with the above code, for instance having each function change the referenced object instead of returning a new object with the populated contents; having the functions use global variables to populate the information; and all in all, this seems like a lot of code for a simple task. The application will take a POST request with the information as `const` in the example, then return the results of the shipping estimate. Should I be creating a dictionary of each field, pass the json and the dictionary contents, and have the function lookup the dictionary items, populate the json, and return the results?
2018/01/11
[ "https://Stackoverflow.com/questions/48214751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3026356/" ]
Don't overthink this with unnecessary programming paradigms. According to your comment this is a simple creation of an object whose structure never changes. Treat it as such. If your task is to create a Javascript Object from values and send it in a POST request, simply create a Javascript Object with the short notation: ``` const upsPostBody = { property: value } ``` Do this for the whole object, e.g. (excerpt): ``` const username = 'Your User Id'; const password = 'Your Password'; const accessLicenseNumber: 'Your Access License'; const upsPostBody = { UPSSecurity:{ UsernameToken: { Username: username, Password: password }, ServiceAccessToken: { AccessLicenseNumber: accessLicenseNumber } } // Continue for all other keys and values } ``` After assigning the values to the object, pass the object as the body to your POST method.
The first thing to use best practice is to use object literals instead of polluting global namespace ``` `const anyObject = { // your object }` ``` the second thing is to use functional programming techniques ``` `function( anyObject, argsToDo) { // do what every you want to anyObject with other functions // anyObject could contain all the properties you need to write // () => setWhatever(anyObject) // or return new anyObjectWithArgsToDo(); }` ``` you can use the approach to write the fields dynamically for the JSON object that you need to submit example pseudocode: ``` `function writeFields( anyObject, fieldsObject ) { let i = 0; foreach( anyObject as value ) { value = fieldsObject[I]; i++; }` ``` you can combined objects to hold other objects JSON stands for JavaScript Object Notation so you can pass them as an argument to functions, perform operations on them with functions, create new Objects with objects as arguments et. cetera. Here is a link to the Wiki on functional programming <https://en.wikipedia.org/wiki/Functional_programming>. To use modern programming techniques would be to use a layer of abstraction and encapsulation among other things, it appears as though you are writing to the implementation instead of writing reusable code that performs a task. The best way to write the code is so that it would work with any object, that involves the use of functional programming techniques where the function does not care about the state of it's arguments. Example ``` `function writeSomeObject ( object, property, value) { object[${property}] = ${value}; // use back ticks // that allow dynamic use of arguments }` ``` I hope that helps
31,547,439
How can i prevent slidedown and slide up of a sub menu at the same time?My navigation has a menu and one of the menus has sub menu.When i click On the menu which has sub menu , The sub menu opens,closes about 2 times and finally closes but there was only one click.It happens in mobile devices.SO take a look at my codes HTML ---- ``` <ul class="nav-menu align-right"> <li class="current"><a href="index.html#header">home</a></li> <li><a href="index.html#about-us">about us</a></li> <li> <a href="#" class="extra">Extra</a> <ul> <li><a href="blog-three.html">blog grid 3</a></li> <li><a href="blog-four.html">blog grid 4</a></li> </ul> </li> <li><a href="index.html#contact">contact</a></li></li> </ul> ``` And js ------ ``` $(window).on('load resize', function(){ if($(window).width() < 1000){ $('.nav-menu li a').click(function(e) { e.preventDefault(); $(this).next('ul').slideToggle(200, 'easeInExpo'); $(this).parent().siblings().find('ul').slideUp(200, 'easeInExpo'); }); } }) ```
2015/07/21
[ "https://Stackoverflow.com/questions/31547439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4740633/" ]
Output is null because `getNodeValue` is not applicable here. `getTextContent` would give you the text between the start and end tags, e.g. FOOBAR in this example: ``` <Product pantone="100" blue="7.4" red="35" green="24">FOOBAR</Product>`. ``` However if you want to print all attribute values for your resultset: ``` NodeList nodes = (NodeList)result; for (int i = 0; i < nodes.getLength(); i++) { NamedNodeMap a = nodes.item(i).getAttributes(); for (int j=0; j<a.getLength(); j++) System.out.println(a.item(j)); } ``` or use `a.item(j).getNodeName()` or `a.item(j).getNodeValue()` to retrieve attribute name or value respectively.
I'm no expert with xpath (literally learned about it today) so I am not 100% certain about this, but you have `/inventory/product/pantone/text(@=100)`, instead try this: ``` /inventory/Product[@pantone='100'] ``` As I understand it, this will match the `Product` with the attribute `pantone` that equals `"100"`. As for printing the data, I am not sure, but hopefully this will get you on the right track. > > **Edit:** Check out this page: [`Node`](https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Node.html). It is the javadoc for the `Node` type. As geert3 said in his/her answer `getNodeValue()` returns the value of the node, which in this case is the value of the element, not the attributes (for example: in `<element>value</element>` the value of the element element is value) which in your case is `null` because it's empty (if it thought the type was String maybe it would be `""` instead of `null`?). > > > Try calling [`Node#getAttributes()`](https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Node.html#getAttributes%28%29) and then iterating across the [`NamedNodeMap`](https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/NamedNodeMap.html) with [`NamedNodeMap#item(int)`](https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/NamedNodeMap.html#item%28int%29) to get the `Node`s. ***These*** should be the attributes (I think, if I am understanding the API correctly). `getNodeName()` should be the name of the attribute (e.g., `pantone`) and `getNodeValue()` should be the value of the attribute (e.g., `100`). > > >
47,331
We had a party at my former school canteen yesterday night. While I was enjoying the food, I could feel that someone had been staring at me. Later, when he tried to get close to me, I said "Go away". I don't know him, but thinking that he might be a student of my former school, so I just politely kept telling him to go away but the words that I used most was "go away" Instead of "Go away", what can I say?
2015/01/20
[ "https://ell.stackexchange.com/questions/47331", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/13998/" ]
> > "Please excuse me, I would like to be left alone." > > > It's polite, firm, and if he responds "why?" you could say: > > "I don't feel comfortable around you. Please leave." > > >
The polite thing would be to make an excuse to not be in the persons company and if it got really out of hand to ask them to leave because they are bothering you. If "Go away" is your starting point then you can pretty much say anything that isn't outright nasty and its a step in the right direction. With a stalker though, you want to go the opposite direction. If the person is a proper weirdo then there is a good chance that most people are not that kind to them and so your perceived kindness weighs more than the meaning behind your words. If you are less bad than the average then you become comparatively good. However: Looking at someone is not stalking, unless you are going out of your way to watch them in secret. Neither is not obeying someone when told to "go away", that is just standing up for yourself. If you were to go away and he were to follow you after repeatedly requesting that he not, then that would be stalking. The situation you described is not a Stalker situation. Did he follow you to this party or home from it? If not then there is just as much chance he was there for his own reasons and only happened meet you there. Unless the stalking started after this point then you are just making drama out of nothing. From the description it appears as though you met someone and you didn't like them so you are calling them nasty things. It would seem plausible that this person just wanted to talk to you and then got embarrassed and didn't know how to leave without being humiliated. "Go away" is an extremely impolite thing to say to someone and if anyone else witnessed this then he would have been in a very difficult social situation.