qid
int64
1
74.6M
question
stringlengths
45
24.2k
date
stringlengths
10
10
metadata
stringlengths
101
178
response_j
stringlengths
32
23.2k
response_k
stringlengths
21
13.2k
12,523,146
> > **Possible Duplicate:** > > [How to remove all CSS classes using jQuery?](https://stackoverflow.com/questions/1424981/how-to-remove-all-css-classes-using-jquery) > > > I have the following: ``` <div id="abc"> </div> ``` Inside that div there can be one only of the following: ``` <p class="message"> <p class="message error"></p> <p class="message warning"></p> <p class="message success"></p> <p class="message loading"></p> ``` Is there a way that I can find and remove all classes from the `<p>` element?
2012/09/21
['https://Stackoverflow.com/questions/12523146', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
You can use `removeAttr` method: ``` $('#abc p').removeAttr('class') ```
From the documentation, [`.removeClass()`](http://api.jquery.com/removeClass/#example-2) ``` $('#abc p').removeClass(); ```
12,523,146
> > **Possible Duplicate:** > > [How to remove all CSS classes using jQuery?](https://stackoverflow.com/questions/1424981/how-to-remove-all-css-classes-using-jquery) > > > I have the following: ``` <div id="abc"> </div> ``` Inside that div there can be one only of the following: ``` <p class="message"> <p class="message error"></p> <p class="message warning"></p> <p class="message success"></p> <p class="message loading"></p> ``` Is there a way that I can find and remove all classes from the `<p>` element?
2012/09/21
['https://Stackoverflow.com/questions/12523146', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
You can do this: ``` $("#abc p").attr("class", ""); ``` or ``` $("#abc p").removeClass(); ```
> > If no class names are specified in the parameter, all classes will be removed. > > > [Source](http://api.jquery.com/removeClass/). Use `removeClass()` with no arguments.
12,523,146
> > **Possible Duplicate:** > > [How to remove all CSS classes using jQuery?](https://stackoverflow.com/questions/1424981/how-to-remove-all-css-classes-using-jquery) > > > I have the following: ``` <div id="abc"> </div> ``` Inside that div there can be one only of the following: ``` <p class="message"> <p class="message error"></p> <p class="message warning"></p> <p class="message success"></p> <p class="message loading"></p> ``` Is there a way that I can find and remove all classes from the `<p>` element?
2012/09/21
['https://Stackoverflow.com/questions/12523146', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
> > If no class names are specified in the parameter, all classes will be removed. > > > [Source](http://api.jquery.com/removeClass/). Use `removeClass()` with no arguments.
From the documentation, [`.removeClass()`](http://api.jquery.com/removeClass/#example-2) ``` $('#abc p').removeClass(); ```
12,523,146
> > **Possible Duplicate:** > > [How to remove all CSS classes using jQuery?](https://stackoverflow.com/questions/1424981/how-to-remove-all-css-classes-using-jquery) > > > I have the following: ``` <div id="abc"> </div> ``` Inside that div there can be one only of the following: ``` <p class="message"> <p class="message error"></p> <p class="message warning"></p> <p class="message success"></p> <p class="message loading"></p> ``` Is there a way that I can find and remove all classes from the `<p>` element?
2012/09/21
['https://Stackoverflow.com/questions/12523146', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
You can do this: ``` $("#abc p").attr("class", ""); ``` or ``` $("#abc p").removeClass(); ```
From the documentation, [`.removeClass()`](http://api.jquery.com/removeClass/#example-2) ``` $('#abc p').removeClass(); ```
33,668,984
I am stuck with the following issue. I have 1 table that looks like this: ``` field_number.. Value ```````````````````````````````` 1 ......................... 1 2 ..........................1 3 ......................... 2 4 ..........................2 ``` etc. I want to group different fieldnumbers and have an average for the value column. So the output should be: ``` field_number................Value name(1,2)...................... 1.............. ((1+1)/2) name(3,4)...................... 2.............. ((2+2)/2) ``` I have checked previous questions but cannot find any question that covers this issue (I might search on the wrong keywords though). So if this has already been covered my appologies, but any help or a point to a previous answer would be appreciated. \*\* =============UPDATE============= \*\* I went through your suggestions but did not get it right. So I am trying to be more specific. I almost have the result I want apart from the fact I want to have a fixed value in one of my columns. I have the following query: ``` Select Avg(wp_rg_lead_detail.value), wp_rg_lead_detail.field_number, From wp_rg_lead_detail Where wp_rg_lead_detail.field_number In (15, 17, 24) A UNION Select Avg(wp_rg_lead_detail.value), wp_rg_lead_detail.field_number, From wp_rg_lead_detail Where wp_rg_lead_detail.field_number In (16, 108, 18) ``` etc. This gives me a table with two columns ``` wp_rg_lead_detail.value................field_number 4.3 (average)..............................15 (first value of av calculation) ``` What I want is to change the field number (15 in this case) in a fixed value (text). What and how should I add this to the query?
2015/11/12
['https://Stackoverflow.com/questions/33668984', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5554171/']
Try join ``` SELECT a.`begin_date`, IF(b.`end_date` IS NOT NULL, b.`end_date`, a.`end_date`), a.`employer_id` FROM `mytable` a LEFT JOIN `mytable` b ON a.`employer_id` = b.`employer_id` AND a.`end_date` = b.`begin_date` LEFT JOIN `mytable` c ON a.`employer_id` = c.`employer_id` AND a.`begin_date` = c.`end_date` WHERE c.`id` IS NULL ``` But you should rebuild your schema.
You can use `MIN(),MAX()` if you want to get earlier and later times. ``` SELECT MIN(begin),MAX(end),employeesId FROM table_name GROUP BY employeesId ``` Hope this helps
865,659
sorry for asking the same question in a slightly different angle, I want a book in Category Theory similar to Dummit and Foote's book in Abstract Algebra. I want it to have tons of examples and problems, and I want it to be the sort of book in which you always have an idea about what the next results are going to be. Something I really liked about Dummit and Foote is I understood what was going on the first time I read it, but when I read it a second time I felt a lot better than the first time (I'm looking forward to a third). Sorry if this just sounds like a lost of demands, I just wanted to give some information about what I was looking for. Thank you kindly Regards.
2014/07/13
['https://math.stackexchange.com/questions/865659', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/33907/']
I definitely recommend [Number Theory by George Andrews](http://books.google.com.mx/books?id=eVwvvwZeBf4C&printsec=frontcover&dq=number+theory+andrew&hl=es-419&sa=X&ei=5PPBU67CHYiV8gHz64Bw&redir_esc=y#v=onepage&q=number%20theory%20andrew&f=false). It's a very comprehensive book, short sweet and cheap. his writing style and his ability to look at results from different angles is excellent. It's a very enjoyable book.
I'm enjoying this library book, Introduction to Number Theory by Daniel E. Flath. Pretty similar topics to the type of answers I generally give on MSE. It really is pretty basic, but I do think a semester of abstract algebra (groups, rings, fields) and one of linear algebra/matrix theory would help. I ordered a used copy online for myself, inexpensive.
865,659
sorry for asking the same question in a slightly different angle, I want a book in Category Theory similar to Dummit and Foote's book in Abstract Algebra. I want it to have tons of examples and problems, and I want it to be the sort of book in which you always have an idea about what the next results are going to be. Something I really liked about Dummit and Foote is I understood what was going on the first time I read it, but when I read it a second time I felt a lot better than the first time (I'm looking forward to a third). Sorry if this just sounds like a lost of demands, I just wanted to give some information about what I was looking for. Thank you kindly Regards.
2014/07/13
['https://math.stackexchange.com/questions/865659', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/33907/']
I really like "An Introduction to the Theory of Numbers" by Niven, Zuckerman and Montgomery. Great collection of problems too.
I'm enjoying this library book, Introduction to Number Theory by Daniel E. Flath. Pretty similar topics to the type of answers I generally give on MSE. It really is pretty basic, but I do think a semester of abstract algebra (groups, rings, fields) and one of linear algebra/matrix theory would help. I ordered a used copy online for myself, inexpensive.
25,805,883
So the objective is to make some buttons the size of 20% of the width & height of the screen. In regular Famo.us, this works: ``` var ww = window.innerWidth * .2; var hh = window.innerHeight * .2; // later in the code for(var i = 0; i < 2; i++) { surfaces.push(new Surface({ content: "button", size: [ww, hh] })); ``` However, in Angular when I use fa-size in the HTML, it's not calculating my objects: ``` <fa-modifier ng-repeat="item in list" fa-size="[ww, hh]" fa-origin="[0.5, 0.5]" fa-align="[0.5, 0.5]"> <fa-surface fa-background-color="item.bgColor"> {{item.content}} </fa-surface> </fa-modifier> ``` In the Angular Controller I have: ``` angular.module('famousAngularStarter') .controller('MainCtrl', function ($scope, $famous) { var Transitionable = $famous['famous/transitions/Transitionable']; var Easing = $famous['famous/transitions/Easing']; var ww = window.innerWidth; var hh = window.innerHeight; $scope.myGridLayoutOptions = { dimensions: [2, 3] }; }); ```
2014/09/12
['https://Stackoverflow.com/questions/25805883', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4033895/']
`CMD + N -> iOs -> Cocoa Touch -> Objective-C Class`
To create a Objective-C class, you have to select **"Cocoa class"**. This will create an .h and .m file for you. Alternatively you can manually add a "Header file" with the same name, but thats just more work for the same thing.
8,899,076
There seems to be a bug in firefox where if I put anything on the right edge of a container (using text-align or float) it makes the container larger than it should be. So for example - ``` <div style='width:100px; overflow:auto'> <div style='width:50px; float:left;'>Something</div> <div style='width:50px; float:right;'> <h1 style='text-align:right;'>Title</h1> </div> </div> ``` Creates a scroll bar in firefox, seems to work fine in chrome. Any ideas?
2012/01/17
['https://Stackoverflow.com/questions/8899076', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1075814/']
What you're seeing is that the text actually overflows its container, because the painted dimensions of text can be bigger than its layout dimensions. This is particularly visible with italic text, but can happen with any text, especially with subpixel layout and antialiasing. Chrome doesn't do subpixel layout of any sort, so it's just ignoring the overflowing text. Your simplest bet is to just style your right float as `overflow:hidden`.
When i am doing aligenment with objects i do ``` <div style='width:100px; overflow:auto'> <div style='width:50px; float:left;'>Something</div> <div style='width:49px; float:right;'> <h1 style='text-align:right;'>Title</h1> </div> ``` this prob will not help you but i have to do it alot when useing %'s
8,899,076
There seems to be a bug in firefox where if I put anything on the right edge of a container (using text-align or float) it makes the container larger than it should be. So for example - ``` <div style='width:100px; overflow:auto'> <div style='width:50px; float:left;'>Something</div> <div style='width:50px; float:right;'> <h1 style='text-align:right;'>Title</h1> </div> </div> ``` Creates a scroll bar in firefox, seems to work fine in chrome. Any ideas?
2012/01/17
['https://Stackoverflow.com/questions/8899076', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1075814/']
What you're seeing is that the text actually overflows its container, because the painted dimensions of text can be bigger than its layout dimensions. This is particularly visible with italic text, but can happen with any text, especially with subpixel layout and antialiasing. Chrome doesn't do subpixel layout of any sort, so it's just ignoring the overflowing text. Your simplest bet is to just style your right float as `overflow:hidden`.
Sorry reread you question you can remove the scroll bar like this: ``` <div style='width:100px; overflow:hidden'> <div style='width:50px; float:left;'>Something</div> <div style='width:50px; float:right;'> <h1 style='text-align:right;'>Title</h1> </div> </div> ``` you will lose 1px of content thou
8,899,076
There seems to be a bug in firefox where if I put anything on the right edge of a container (using text-align or float) it makes the container larger than it should be. So for example - ``` <div style='width:100px; overflow:auto'> <div style='width:50px; float:left;'>Something</div> <div style='width:50px; float:right;'> <h1 style='text-align:right;'>Title</h1> </div> </div> ``` Creates a scroll bar in firefox, seems to work fine in chrome. Any ideas?
2012/01/17
['https://Stackoverflow.com/questions/8899076', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1075814/']
What you're seeing is that the text actually overflows its container, because the painted dimensions of text can be bigger than its layout dimensions. This is particularly visible with italic text, but can happen with any text, especially with subpixel layout and antialiasing. Chrome doesn't do subpixel layout of any sort, so it's just ignoring the overflowing text. Your simplest bet is to just style your right float as `overflow:hidden`.
It's behaving as it should. You don't state which versions of Firefox and Chrome you're using, but for me with FF 9.0 and Chrome 16, they behave the same, i.e., the scrollbar appears. It's because your content extends beyond the defined width, and the default value for overflow is "visible", so the h1 in your right-floated div is extending beyond the div's boundaries. If you change your h1 to, say, a p tag, you note that the scrollbar disappears. Applying a border will illustrate what's happening with the box model (copy/paste to see how the content extends beyond the border): ``` <div style='width:104px; overflow:auto;'> <div style='width:50px; float:left; border:1px solid red;'>Something</div> <div style='width:50px; float:right; border:1px solid red;'> <h1 style='text-align:right;'>Title</h1> </div> </div> ``` So, again, it's behaving as it should. If your content extends beyond its container's width and no overflow value is assigned, overflow defaults to visible and the content shows and "pushes" the boundaries of the container. In this case, since your outer container has overflow:auto, you see a scrollbar.
12,451,787
I am trying to filter for a specific word ("no-image") in my image src and if it returns true, I want to remove that particular image but keep the rest of the images. This is my output: ``` <div class="product"> <div class="image"> <img src="mytee-red.jpg"> <img src="mytee-blue.jpg"> <img src="mytee-black.jpg"> <img src="mytee-no-image.jpg"> </div> </div> ``` This is what I've tried so far but cant seem to get it working: ``` var keyword = "no-image"; $(".product .image img").filter(function(index) { if ($(this).attr("src") == keyword) { $(this).remove(); } }); ``` Any help would be great!!!
2012/09/17
['https://Stackoverflow.com/questions/12451787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/992731/']
You could simplify this into a single command - ``` $(".product .image img[src*='no-image']").remove(); ``` The [jQuery attribute contains selector](http://api.jquery.com/attribute-equals-selector/) will help you pin-point the exact elements that you want containing the text "no-image" anywhere within the `src` attribute. > > This is the most generous of the jQuery attribute selectors that match > against a value. It will select an element if the selector's string > appears anywhere within the element's attribute value. > > >
Filter will only keep the items where the passed function returns true. Instead of trying to remove them inside the filter function, just return false. > > .filter( function(index) ): Reduce the set of matched elements to those that match the selector or pass the function's test. > > > ``` var keyword = "no-image"; $(".product .image img").filter(function(index) { return $(this).attr("src") != keyword; }); ```
12,451,787
I am trying to filter for a specific word ("no-image") in my image src and if it returns true, I want to remove that particular image but keep the rest of the images. This is my output: ``` <div class="product"> <div class="image"> <img src="mytee-red.jpg"> <img src="mytee-blue.jpg"> <img src="mytee-black.jpg"> <img src="mytee-no-image.jpg"> </div> </div> ``` This is what I've tried so far but cant seem to get it working: ``` var keyword = "no-image"; $(".product .image img").filter(function(index) { if ($(this).attr("src") == keyword) { $(this).remove(); } }); ``` Any help would be great!!!
2012/09/17
['https://Stackoverflow.com/questions/12451787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/992731/']
You could simplify this into a single command - ``` $(".product .image img[src*='no-image']").remove(); ``` The [jQuery attribute contains selector](http://api.jquery.com/attribute-equals-selector/) will help you pin-point the exact elements that you want containing the text "no-image" anywhere within the `src` attribute. > > This is the most generous of the jQuery attribute selectors that match > against a value. It will select an element if the selector's string > appears anywhere within the element's attribute value. > > >
``` $('.product .image img[src*="no-image"]').remove(); ``` <http://api.jquery.com/attribute-contains-selector/> No regex needed.
12,451,787
I am trying to filter for a specific word ("no-image") in my image src and if it returns true, I want to remove that particular image but keep the rest of the images. This is my output: ``` <div class="product"> <div class="image"> <img src="mytee-red.jpg"> <img src="mytee-blue.jpg"> <img src="mytee-black.jpg"> <img src="mytee-no-image.jpg"> </div> </div> ``` This is what I've tried so far but cant seem to get it working: ``` var keyword = "no-image"; $(".product .image img").filter(function(index) { if ($(this).attr("src") == keyword) { $(this).remove(); } }); ``` Any help would be great!!!
2012/09/17
['https://Stackoverflow.com/questions/12451787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/992731/']
You could simplify this into a single command - ``` $(".product .image img[src*='no-image']").remove(); ``` The [jQuery attribute contains selector](http://api.jquery.com/attribute-equals-selector/) will help you pin-point the exact elements that you want containing the text "no-image" anywhere within the `src` attribute. > > This is the most generous of the jQuery attribute selectors that match > against a value. It will select an element if the selector's string > appears anywhere within the element's attribute value. > > >
according to your example, you need to use `match()` instead of `==` ``` var keyword = "no-image"; $(".product .image img").filter(function(index) { if ($(this).attr("src").match(keyword)) { $(this).remove(); } }); ``` Assuming that you want to remove `<img src="mytee-no-image.jpg">` as it matches the keyword `no-image`
12,451,787
I am trying to filter for a specific word ("no-image") in my image src and if it returns true, I want to remove that particular image but keep the rest of the images. This is my output: ``` <div class="product"> <div class="image"> <img src="mytee-red.jpg"> <img src="mytee-blue.jpg"> <img src="mytee-black.jpg"> <img src="mytee-no-image.jpg"> </div> </div> ``` This is what I've tried so far but cant seem to get it working: ``` var keyword = "no-image"; $(".product .image img").filter(function(index) { if ($(this).attr("src") == keyword) { $(this).remove(); } }); ``` Any help would be great!!!
2012/09/17
['https://Stackoverflow.com/questions/12451787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/992731/']
You could simplify this into a single command - ``` $(".product .image img[src*='no-image']").remove(); ``` The [jQuery attribute contains selector](http://api.jquery.com/attribute-equals-selector/) will help you pin-point the exact elements that you want containing the text "no-image" anywhere within the `src` attribute. > > This is the most generous of the jQuery attribute selectors that match > against a value. It will select an element if the selector's string > appears anywhere within the element's attribute value. > > >
Other answers suggest better approaches, but a demonstration of `filter()` could be: ``` var keyword = "no-image"; $(".product .image img").filter(function(index) { return $(this).attr("src").match(keyword); }).remove(); ```
12,451,787
I am trying to filter for a specific word ("no-image") in my image src and if it returns true, I want to remove that particular image but keep the rest of the images. This is my output: ``` <div class="product"> <div class="image"> <img src="mytee-red.jpg"> <img src="mytee-blue.jpg"> <img src="mytee-black.jpg"> <img src="mytee-no-image.jpg"> </div> </div> ``` This is what I've tried so far but cant seem to get it working: ``` var keyword = "no-image"; $(".product .image img").filter(function(index) { if ($(this).attr("src") == keyword) { $(this).remove(); } }); ``` Any help would be great!!!
2012/09/17
['https://Stackoverflow.com/questions/12451787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/992731/']
``` $('.product .image img[src*="no-image"]').remove(); ``` <http://api.jquery.com/attribute-contains-selector/> No regex needed.
Filter will only keep the items where the passed function returns true. Instead of trying to remove them inside the filter function, just return false. > > .filter( function(index) ): Reduce the set of matched elements to those that match the selector or pass the function's test. > > > ``` var keyword = "no-image"; $(".product .image img").filter(function(index) { return $(this).attr("src") != keyword; }); ```
12,451,787
I am trying to filter for a specific word ("no-image") in my image src and if it returns true, I want to remove that particular image but keep the rest of the images. This is my output: ``` <div class="product"> <div class="image"> <img src="mytee-red.jpg"> <img src="mytee-blue.jpg"> <img src="mytee-black.jpg"> <img src="mytee-no-image.jpg"> </div> </div> ``` This is what I've tried so far but cant seem to get it working: ``` var keyword = "no-image"; $(".product .image img").filter(function(index) { if ($(this).attr("src") == keyword) { $(this).remove(); } }); ``` Any help would be great!!!
2012/09/17
['https://Stackoverflow.com/questions/12451787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/992731/']
according to your example, you need to use `match()` instead of `==` ``` var keyword = "no-image"; $(".product .image img").filter(function(index) { if ($(this).attr("src").match(keyword)) { $(this).remove(); } }); ``` Assuming that you want to remove `<img src="mytee-no-image.jpg">` as it matches the keyword `no-image`
Filter will only keep the items where the passed function returns true. Instead of trying to remove them inside the filter function, just return false. > > .filter( function(index) ): Reduce the set of matched elements to those that match the selector or pass the function's test. > > > ``` var keyword = "no-image"; $(".product .image img").filter(function(index) { return $(this).attr("src") != keyword; }); ```
12,451,787
I am trying to filter for a specific word ("no-image") in my image src and if it returns true, I want to remove that particular image but keep the rest of the images. This is my output: ``` <div class="product"> <div class="image"> <img src="mytee-red.jpg"> <img src="mytee-blue.jpg"> <img src="mytee-black.jpg"> <img src="mytee-no-image.jpg"> </div> </div> ``` This is what I've tried so far but cant seem to get it working: ``` var keyword = "no-image"; $(".product .image img").filter(function(index) { if ($(this).attr("src") == keyword) { $(this).remove(); } }); ``` Any help would be great!!!
2012/09/17
['https://Stackoverflow.com/questions/12451787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/992731/']
Other answers suggest better approaches, but a demonstration of `filter()` could be: ``` var keyword = "no-image"; $(".product .image img").filter(function(index) { return $(this).attr("src").match(keyword); }).remove(); ```
Filter will only keep the items where the passed function returns true. Instead of trying to remove them inside the filter function, just return false. > > .filter( function(index) ): Reduce the set of matched elements to those that match the selector or pass the function's test. > > > ``` var keyword = "no-image"; $(".product .image img").filter(function(index) { return $(this).attr("src") != keyword; }); ```
45,396,346
In my project there are a `stable` branch and a `dev` branch. Commits are cherry-picked from `dev` branch to `stable` branch. In order to filter all commits on `dev` that have not been merged to `stable`, `git cherry -v stable dev` looks like a good choice. However it identifies equivalence by diff, which usually changes after resolving merge conflict during `cherry-pick`: > > The equivalence test is based on the diff, after removing whitespace > and line numbers. git-cherry therefore detects when commits have been > "copied" by means of git-cherry-pick(1), git-am(1) or git-rebase(1). > > > I was wondering that is there any command that works like `git cherry`, but identifies equivalent commits by commit message?
2017/07/30
['https://Stackoverflow.com/questions/45396346', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4140668/']
It seems that there is no direct way to do this, so I wrote a short script: ``` #!/bin/bash git cherry -v stable dev | grep + | cut -d ' ' -f 3- > /tmp/unmerged xargs -a /tmp/unmerged -I{} git --no-pager log stable --pretty=oneline --grep {} | cut -d ' ' -f 2- > /tmp/cherry-picked diff /tmp/unmerged /tmp/cherry-picked ``` **Explanation**: `git cherry -v stable dev | grep + | cut -d ' ' -f 3- > /tmp/unmerged` writes commit messages of commits that only exist on `dev` branch. These commits include those have been cherry-picked and changed to `stable` branch, and we need to filter out these commits in the next step. `xargs -a /tmp/unmerged -I{} git --no-pager log stable --pretty=oneline --grep {} | cut -d ' ' -f 2- > /tmp/cherry-picked` outputs messages of commits from (1) that appears with the same message on `stable`. In other words, `/tmp/cherry-picked` stores all commits that are cherry-picked and changed from `dev` to `stable`. Finally, `diff /tmp/unmerged /tmp/cherry-picked` gives out all commits on `dev` where no commit with identical commit message is found on `stable`.
If commits in `dev` are not rebased, then you could use `git cherry-pick -x`, marking the source explicitly. There is no automatic use of this information, but with some bash fu it is possible to use it.
45,396,346
In my project there are a `stable` branch and a `dev` branch. Commits are cherry-picked from `dev` branch to `stable` branch. In order to filter all commits on `dev` that have not been merged to `stable`, `git cherry -v stable dev` looks like a good choice. However it identifies equivalence by diff, which usually changes after resolving merge conflict during `cherry-pick`: > > The equivalence test is based on the diff, after removing whitespace > and line numbers. git-cherry therefore detects when commits have been > "copied" by means of git-cherry-pick(1), git-am(1) or git-rebase(1). > > > I was wondering that is there any command that works like `git cherry`, but identifies equivalent commits by commit message?
2017/07/30
['https://Stackoverflow.com/questions/45396346', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4140668/']
It seems that there is no direct way to do this, so I wrote a short script: ``` #!/bin/bash git cherry -v stable dev | grep + | cut -d ' ' -f 3- > /tmp/unmerged xargs -a /tmp/unmerged -I{} git --no-pager log stable --pretty=oneline --grep {} | cut -d ' ' -f 2- > /tmp/cherry-picked diff /tmp/unmerged /tmp/cherry-picked ``` **Explanation**: `git cherry -v stable dev | grep + | cut -d ' ' -f 3- > /tmp/unmerged` writes commit messages of commits that only exist on `dev` branch. These commits include those have been cherry-picked and changed to `stable` branch, and we need to filter out these commits in the next step. `xargs -a /tmp/unmerged -I{} git --no-pager log stable --pretty=oneline --grep {} | cut -d ' ' -f 2- > /tmp/cherry-picked` outputs messages of commits from (1) that appears with the same message on `stable`. In other words, `/tmp/cherry-picked` stores all commits that are cherry-picked and changed from `dev` to `stable`. Finally, `diff /tmp/unmerged /tmp/cherry-picked` gives out all commits on `dev` where no commit with identical commit message is found on `stable`.
You want to use `patch-id`. This is the mechanism used by `git cherry`. To find an equivalent of commit `3642151` run: `git show 3642151 | git patch-id` You should get a line with two hashes; the first is the patchid (call it `PATCHID_FROM_ABOVE`) `git log -p | git patch-id | grep PATCHID_FROM_ABOVE` This should give you a list of all commits that correspond to that patchid. Stolen from: <http://git.661346.n2.nabble.com/git-cherry-to-find-equivalent-commit-IDs-td3440883.html>
45,396,346
In my project there are a `stable` branch and a `dev` branch. Commits are cherry-picked from `dev` branch to `stable` branch. In order to filter all commits on `dev` that have not been merged to `stable`, `git cherry -v stable dev` looks like a good choice. However it identifies equivalence by diff, which usually changes after resolving merge conflict during `cherry-pick`: > > The equivalence test is based on the diff, after removing whitespace > and line numbers. git-cherry therefore detects when commits have been > "copied" by means of git-cherry-pick(1), git-am(1) or git-rebase(1). > > > I was wondering that is there any command that works like `git cherry`, but identifies equivalent commits by commit message?
2017/07/30
['https://Stackoverflow.com/questions/45396346', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4140668/']
If commits in `dev` are not rebased, then you could use `git cherry-pick -x`, marking the source explicitly. There is no automatic use of this information, but with some bash fu it is possible to use it.
You want to use `patch-id`. This is the mechanism used by `git cherry`. To find an equivalent of commit `3642151` run: `git show 3642151 | git patch-id` You should get a line with two hashes; the first is the patchid (call it `PATCHID_FROM_ABOVE`) `git log -p | git patch-id | grep PATCHID_FROM_ABOVE` This should give you a list of all commits that correspond to that patchid. Stolen from: <http://git.661346.n2.nabble.com/git-cherry-to-find-equivalent-commit-IDs-td3440883.html>
63,593,917
I have 2 function for API connection: ``` //Load data from API private fun loadData() { compositeDisposable.add( ApiClient.getClient.getQuestions(Params.getParamsSearch()) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(this::handleResponse) ) } //Response handler for API private fun handleResponse(objectsQueryResult: ObjectsQueryResult) { updateAdapter(objectsQueryResult) } ``` What is the syntax to put all lines in handleResponse function inside subscribe instead of using the function? Something like this: ``` //Load data from API private fun loadData() { compositeDisposable.add( ApiClient.getClient.getQuestions(Params.getParamsSearch()) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe({ updateAdapter(objectsQueryResult) }) ) } ```
2020/08/26
['https://Stackoverflow.com/questions/63593917', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1075753/']
``` .subscribe({ objectsQueryResult -> updateAdapter(objectsQueryResult) }) ``` or ``` .subscribe({ updateAdapter(it) }) ```
```kotlin //Load data from API private fun loadData() { compositeDisposable.add( ApiClient.getClient.getQuestions(Params.getParamsSearch()) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe { objectsQueryResult -> updateAdapter(objectsQueryResult) } ) } ``` or ```kotlin //Load data from API private fun loadData() { compositeDisposable.add( ApiClient.getClient.getQuestions(Params.getParamsSearch()) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe { updateAdapter(it) } ) } ```
2,054,438
I'm working on a map of the native languages of California for Wikipedia. The map contains areas that each correspond to a language. The original looks like this (click it to see the [SVG](http://en.wikipedia.org/wiki/Scalable_Vector_Graphics)): [![](https://upload.wikimedia.org/wikipedia/commons/thumb/b/b1/California_languages_precontact.svg/200px-California_languages_precontact.svg.png)](http://en.wikipedia.org/wiki/File:California_languages_precontact.svg) I want to make "locator maps" for each of those individual languages by hand (in [Inkscape](http://en.wikipedia.org/wiki/Inkscape)), like this one, for a language called [Cahuilla](http://en.wikipedia.org/wiki/Cahuilla_language) (which has the language code `cah`): [![](https://upload.wikimedia.org/wikipedia/commons/thumb/b/bb/Cahuillia_language_with_California_inset.svg/200px-Cahuillia_language_with_California_inset.svg.png)](http://en.wikipedia.org/wiki/File:Cahuillia_language_with_California_inset.svg) Needless to say, doing this would be a pain in the neck if I generated all 60-some by hand in Inkscape. Worse, whenever I find a mistake in the original, I'd have to redo the whole set of locator maps. (And in fact I recently realized that my original is missing one language entirely. Sorry Cupeño.) So **my goal is to automate this process**. I don't have much experience processing SVG or even XML, so I'm looking for recommendations as to which libraries would be most helpful. I'd prefer solutions in Python, sincely I'm not hopeless in that language. To summarize, I need to: Get a list of references to all the language shapes in the original SVG file. For each language in this list: 1. change the background color of the shape for the current language 2. put a box around the language 3. duplicate the box and scale it to a given size (I recognize that in this step it might be difficult to actually "crop" the surrounding shapes as I did in my example -- just creating a box with the language shape on a white background would be sufficient.) 4. place the duplicate in the upper right corner 5. save all this stuff in code.svg The final product will then be 60 SVG files named `cah.svg`, etc. Better yet, it would be possible to re-generate the whole shebang if it became necessary to edit the original map (which is quite likely).
2010/01/13
['https://Stackoverflow.com/questions/2054438', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
I would recommend using Python and specifically creating extensions for Inkscape. I don't think you really need 60 SVG unless you really want to because the source map will have everything you need. What I would do is use Inkscape to rename the various regions to the same language code you will be using. For example, Cahuilla or cah is currently `path13882` in your SVG file. I would rename it to `cah` or `Cahuilla` and repeat the process for each of the language regions. Use the Edit\XML Editor to help make sure you update all of the paths. After you have updated the names/IDs, then you might look into SVG scripting. I would just create a javascript/ecmascript map or dictionary that has the relevant information for the language: ``` var langaugeMap = {}; languageMap["cah"] = { name: "Cahuilla", color: "rgb(255, 0, 0)" }; languageMap["cup"] = { name: "Cupeño", color: "rgb(255, 64, 0)" }; // and so on -- this could even be generated from a CSV file or Excel, etc. // if the highlighted color is always the same, then you don't need it in the map // or use style sheets for an activeshape and inactiveshape // Put any information that is specific to a language in the map ``` Then you just need to add a mouseover function that would add and position the bounding box and change the path color. Here is [one example](http://www.ibm.com/developerworks/library/x-svgint/) of events and scripting although it is quite dated. [Carto.net](http://www.carto.net/svg/samples/mouse_over_effects.shtml) has an interactive map example as well. The SVG would look something like: ``` <path style="fill:#800000;fill-opacity:1;display:inline" d="m 422.43078,517.40746 c 0.52151,0.006 1.10755,0.0374 1.75925,0.0825 3.82011,0.26462 5.01088,0.75501 5.75001,2.37491 0.51312,1.12355 2.4121,3.0097 4.22213,4.1946 3.906,2.55656 7.38824,2.07964 9.61517,-1.3194 2.12996,-3.25075 9.13451,-3.19196 13.61739,0.11545 1.77185,1.30707 4.04994,2.38037 5.06319,2.38041 1.01325,0 3.34593,0.92548 5.18421,2.06155 2.52816,1.56236 4.9918,2.09869 10.09889,2.19902 3.71359,0.0729 7.68145,0.64349 8.82374,1.26442 2.81717,1.53202 5.67633,1.42382 10.7693,-0.40133 4.97461,-1.78261 6.31161,-1.36525 17.10267,5.31063 3.39862,2.10239 6.90491,4.08094 7.7956,4.39801 2.46593,0.8776 4.55428,4.66976 3.95259,7.17971 -0.29359,1.22605 -0.75898,3.51121 -1.03349,5.07968 -0.27411,1.56855 -0.88382,3.33952 -1.35761,3.93621 -1.50842,1.89871 -20.98501,7.77151 -27.8945,8.41122 -3.66014,0.33879 -8.3091,1.04337 -10.32987,1.56676 -3.50666,0.90799 -3.81743,0.79746 -6.78388,-2.44089 -3.3486,-3.65594 -6.11308,-4.2716 -8.48815,-1.89661 -2.14408,2.14401 -1.85126,3.96434 1.0667,6.66846 1.40725,1.30409 1.85699,2.10446 1.00027,1.77571 -0.85672,-0.32883 -6.3937,-0.12213 -12.3033,0.46176 -5.9096,0.58386 -12.56062,1.27336 -14.78297,1.53381 -4.17058,0.4888 -5.09869,-0.37014 -2.61673,-2.42989 2.1563,-1.78956 1.74245,-2.63318 -1.65999,-3.36449 -1.69931,-0.36525 -4.94789,-1.90738 -7.213,-3.42496 -2.26473,-1.51754 -5.89662,-3.66823 -8.07583,-4.77731 -2.17921,-1.10923 -6.21922,-3.94186 -8.97721,-6.29463 -4.75318,-4.05478 -4.93682,-4.36681 -3.43604,-6.02527 0.96935,-1.07117 2.36209,-1.56397 3.5899,-1.26992 1.62639,0.38937 2.49494,-0.41237 4.59588,-4.24958 1.42481,-2.60257 2.23686,-4.95457 1.80316,-5.22266 -0.4337,-0.26805 -1.06784,-3.14557 -1.40725,-6.39358 -0.33978,-3.24797 -1.19001,-6.79064 -1.89134,-7.87242 -1.74322,-2.68957 -1.2114,-3.65437 2.44111,-3.61188 l 0,0 z" id="cah" inkscape:label="#cah" onmouseover="highlightRegion(evt);" onmouseout="restoreRegion(evt);" /> ``` For any automation with the SVG file, I would use Inkscape extensions. Look at the [Inkscape wiki](http://wiki.inkscape.org/wiki/index.php/Inkscape) under the Developer Tutorials / Extensions. Otherwise, SVG is still XML so if you have named your language regions in the source file with a distinguishing name, you could use Python to parse the XML and save each path/language region to a separate file.
Here's an [example](http://xn--dahlstrm-t4a.net/svg/examples/MapWithMiniView.svg) using your map. You can click any element to get the boundingbox, this can be used for the miniview viewBox (with some tweaking). As you see it's not adding much code to the map, just a couple of elements. When you have all the viewBoxes you can update the miniview `'viewBox'` attribute on the fly using javascript. For the coloring of the selected shape, I'd suggest adding a `<use>` element inside the miniview `<svg>` that has a fill that overrides any fill used in the main map (you may have to use a stylesheet rule for this to make sure it's got high specificity, e.g adding `#miniview .activeshape { fill: red !important }`. Let the `<use>` point to the selected shape, and make sure you add `class="activeshape"` on the shape you point to. This should be a start at least, hope it helps :)
63,146,323
I have made this mouse hover image zoom page. But I want the output to be shown on the left side and only when someone hovers the mouse on it. In this code the output window is continuously opened. HERE IS MY CODE: ```js function imageZoom(imgID, resultID) { var img, lens, result, cx, cy; img = document.getElementById(imgID); result = document.getElementById(resultID); /*create lens:*/ lens = document.createElement("DIV"); lens.setAttribute("class", "img-zoom-lens"); /*insert lens:*/ img.parentElement.insertBefore(lens, img); /*calculate the ratio between result DIV and lens:*/ cx = result.offsetWidth / lens.offsetWidth; cy = result.offsetHeight / lens.offsetHeight; /*set background properties for the result DIV:*/ result.style.backgroundImage = "url('" + img.src + "')"; result.style.backgroundSize = (img.width * cx) + "px " + (img.height * cy) + "px"; /*execute a function when someone moves the cursor over the image, or the lens:*/ lens.addEventListener("mousemove", moveLens); img.addEventListener("mousemove", moveLens); /*and also for touch screens:*/ lens.addEventListener("touchmove", moveLens); img.addEventListener("touchmove", moveLens); function moveLens(e) { var pos, x, y; /*prevent any other actions that may occur when moving over the image:*/ e.preventDefault(); /*get the cursor's x and y positions:*/ pos = getCursorPos(e); /*calculate the position of the lens:*/ x = pos.x - (lens.offsetWidth / 2); y = pos.y - (lens.offsetHeight / 2); /*prevent the lens from being positioned outside the image:*/ if (x > img.width - lens.offsetWidth) { x = img.width - lens.offsetWidth; } if (x < 0) { x = 0; } if (y > img.height - lens.offsetHeight) { y = img.height - lens.offsetHeight; } if (y < 0) { y = 0; } /*set the position of the lens:*/ lens.style.left = x + "px"; lens.style.top = y + "px"; /*display what the lens "sees":*/ result.style.backgroundPosition = "-" + (x * cx) + "px -" + (y * cy) + "px"; } function getCursorPos(e) { var a, x = 0, y = 0; e = e || window.event; /*get the x and y positions of the image:*/ a = img.getBoundingClientRect(); /*calculate the cursor's x and y coordinates, relative to the image:*/ x = e.pageX - a.left; y = e.pageY - a.top; /*consider any page scrolling:*/ x = x - window.pageXOffset; y = y - window.pageYOffset; return { x: x, y: y }; } } // Initiate zoom effect: imageZoom("myimage", "myresult"); ``` ```css * { box-sizing: border-box; } .img-zoom-container { position: relative; } .img-zoom-lens { position: absolute; border: 1px solid #d4d4d4; /*set the size of the lens:*/ width: 40px; height: 40px; } .img-zoom-result { border: 1px solid #d4d4d4; /*set the size of the result div:*/ width: 300px; height: 300px; } ``` ```html <h1>Image Zoom</h1> <p>Mouse over the image:</p> <div class="img-zoom-container"> <img id="myimage" src="img_girl.jpg" width="300" height="240"> <div id="myresult" class="img-zoom-result"></div> </div> <p>The image must be placed inside a container with relative positioning.</p> <p>The result can be put anywhere on the page, but must have the class name "img-zoom-result".</p> <p>Make sure both the image and the result have IDs. These IDs are used when a javaScript initiates the zoom effect.</p> ``` The code is working perfectly, but the result should be on the right and it should be only shown when user hovers the mouse on it.
2020/07/29
['https://Stackoverflow.com/questions/63146323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13993822/']
You can't set that flag. It's managed by Firebase Auth. My guess for the reason that it's always set true by default (for Google auth, as you imply here) is that Google manages the email verification scheme for their own accounts. You can be sure that, if you get an email address for a Google account, the email does in fact work and belong to the user.
As i can see that you are using google login , So if someone logins through google the email is already verified . If you want to send verification mail use email/password signin .
381,207
I've used a few Stack Exchange sites and am thinking of close / downvotes on *[Linguistics](https://linguistics.stackexchange.com/tour)*, *[Philosophy](https://philosophy.stackexchange.com/tour)* and *[English Language & Usage](https://english.stackexchange.com/tour)* especially. While it is obvious that SE should tolerate or even welcome entry-level questions that aren't catered for elsewhere on the Internet, I am wondering if simple questions no one can find nor knows the answer to inevitably seem at best stupid to other users. I have asked a lot of these sorts of questions, so it's difficult to illustrate except very loosely, and it may just be an imagined commonality to my poorly received questions. But is it a *known* problem with the site or Q&A format? It could be that simple, but unusual questions are just harder to ask.
2022/08/14
['https://meta.stackexchange.com/questions/381207', 'https://meta.stackexchange.com', 'https://meta.stackexchange.com/users/356826/']
What happens to sites is simply that questions accumulate over time and that in and of itself changes things. On day 1 there are no questions and you can ask anything you like no matter how simple and it will be a new and unique question. After 10 years though there will be a huge existing body of questions so unless you're asking about some newly discovered idea or concept, the chances are if you ask a simple question that it will already exist as a Q&A on the site. So it gets harder and harder to ask an unusual question or in fact any question if you don't spend time searching to see if it already exists. It's also the case that not searching for a duplicate may get your question downvoted because you're really just asking someone else to do that search for you.
SE in general shouldn't have any issue with simple questions that **are** googleable, so long as the question itself is well-constructed. The reception of such is often down to the rapidity & acceptability of the first answer. Get in too late, it's been downvoted to all heck, get in early with a fully comprehensive answer not just a sentence, & you end up with 500+ upvotes & your answer as the first hit on google. [I'm not proposing this in any other way than "it does actually happen". I personally have on occasions been gifted one of these 'low-hanging fruit' questions.] If you like irony, I once googled something I'd forgotten how to do, & the first hit was… my own answer on SE ;)
7,152,533
I have an Ajax call to create an image gallery. There is a combo box to set the number of images per page, and pagination to navigate through the pages. It's working fine, except that if a person is on the last page, and they increase the number of images per page, it reloads to the current page number. This is a problem because there are now less pages and so the page is blank. In other words, you end up on `page 7 of 5` for instance. I reckon the problem is in the PHP as that is where the number of pages is calculated. I've thought out an `if` statement to deal with this: ``` if ($page > $no_of_paginations) { $page = $no_of_paginations; } ``` However, I don't know where to place this. The reason being, `$page` needs to be defined *before* the mysql\_query, but `$no_of_paginations` is defined *after* the query. Any thoughts on how I can make this functional? I'll post the pertinent code below: ``` <?php $page = 0; if(isset($_GET['page'])){ $page = (int) $_GET['page']; } $cur_page = $page; $page -= 1; if((int) $_GET['imgs'] > 0){ $per_page = (int) $_GET['imgs']; } else { $per_page = 16; } $start = $per_page * $page; include"db.php"; $query_pag_data = "SELECT `imgURL`,`imgTitle` FROM `images` ". "ORDER BY `imgDate` DESC LIMIT $start, $per_page"; $result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error()); echo "<ul class='new_arrivals_gallery'>"; while($row = mysql_fetch_assoc($result_pag_data)) { echo "<li><a target='_blank' href='new_arrivals_img/".$row['imgURL']."' class='gallery' title='".$row['imgTitle']."'><img src='new_arrivals_img/thumbnails/".$row['imgURL']."'></a></li>"; } echo "</ul>"; /* --------------------------------------------- */ $query_pag_num = "SELECT COUNT(*) AS count FROM images"; $result_pag_num = mysql_query($query_pag_num); $row = mysql_fetch_array($result_pag_num); $count = $row['count']; $no_of_paginations = ceil($count / $per_page); ?> ``` Thanks for your help!
2011/08/22
['https://Stackoverflow.com/questions/7152533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/708274/']
You should use query: ``` $query_pag_data = "SELECT SQL_CALC_FOUND_ROWS `imgURL`,`imgTitle` FROM `images` ". "ORDER BY `imgDate` DESC LIMIT $start, $per_page"; ``` And instead of ``` $query_pag_num = "SELECT COUNT(*) AS count FROM images"; ``` use ``` $query_pag_num = "SELECT FOUND_ROWS()"; ```
If you do the "SELECT COUNT(\*) ..." query earlier in the script (at least before the other query), you will have $no\_of\_paginations earlier, and can use it to clamp $page to the correct range.
7,152,533
I have an Ajax call to create an image gallery. There is a combo box to set the number of images per page, and pagination to navigate through the pages. It's working fine, except that if a person is on the last page, and they increase the number of images per page, it reloads to the current page number. This is a problem because there are now less pages and so the page is blank. In other words, you end up on `page 7 of 5` for instance. I reckon the problem is in the PHP as that is where the number of pages is calculated. I've thought out an `if` statement to deal with this: ``` if ($page > $no_of_paginations) { $page = $no_of_paginations; } ``` However, I don't know where to place this. The reason being, `$page` needs to be defined *before* the mysql\_query, but `$no_of_paginations` is defined *after* the query. Any thoughts on how I can make this functional? I'll post the pertinent code below: ``` <?php $page = 0; if(isset($_GET['page'])){ $page = (int) $_GET['page']; } $cur_page = $page; $page -= 1; if((int) $_GET['imgs'] > 0){ $per_page = (int) $_GET['imgs']; } else { $per_page = 16; } $start = $per_page * $page; include"db.php"; $query_pag_data = "SELECT `imgURL`,`imgTitle` FROM `images` ". "ORDER BY `imgDate` DESC LIMIT $start, $per_page"; $result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error()); echo "<ul class='new_arrivals_gallery'>"; while($row = mysql_fetch_assoc($result_pag_data)) { echo "<li><a target='_blank' href='new_arrivals_img/".$row['imgURL']."' class='gallery' title='".$row['imgTitle']."'><img src='new_arrivals_img/thumbnails/".$row['imgURL']."'></a></li>"; } echo "</ul>"; /* --------------------------------------------- */ $query_pag_num = "SELECT COUNT(*) AS count FROM images"; $result_pag_num = mysql_query($query_pag_num); $row = mysql_fetch_array($result_pag_num); $count = $row['count']; $no_of_paginations = ceil($count / $per_page); ?> ``` Thanks for your help!
2011/08/22
['https://Stackoverflow.com/questions/7152533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/708274/']
As you are currently doing it, there would be no problem with moving the last section to above the main query. A better way to find the total records with MySQL is to use the [SQL\_CALC\_FOUND\_ROWS](http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows) keyword on your main query (so here it is `SELECT SQL_CALC_FOUND_ROWS imgURL, imgTitle FROM images WHERE etc`) then you can query `SELECT FOUND_ROWS()` and just get the number of records found in the last query. As well as being faster and more efficient, this avoids a race condition when records are added between the two queries. However, in this case you should probably just do the two current queries in the reverse order as your only other option is to check at the end and repeat if necessary.
If you do the "SELECT COUNT(\*) ..." query earlier in the script (at least before the other query), you will have $no\_of\_paginations earlier, and can use it to clamp $page to the correct range.
7,152,533
I have an Ajax call to create an image gallery. There is a combo box to set the number of images per page, and pagination to navigate through the pages. It's working fine, except that if a person is on the last page, and they increase the number of images per page, it reloads to the current page number. This is a problem because there are now less pages and so the page is blank. In other words, you end up on `page 7 of 5` for instance. I reckon the problem is in the PHP as that is where the number of pages is calculated. I've thought out an `if` statement to deal with this: ``` if ($page > $no_of_paginations) { $page = $no_of_paginations; } ``` However, I don't know where to place this. The reason being, `$page` needs to be defined *before* the mysql\_query, but `$no_of_paginations` is defined *after* the query. Any thoughts on how I can make this functional? I'll post the pertinent code below: ``` <?php $page = 0; if(isset($_GET['page'])){ $page = (int) $_GET['page']; } $cur_page = $page; $page -= 1; if((int) $_GET['imgs'] > 0){ $per_page = (int) $_GET['imgs']; } else { $per_page = 16; } $start = $per_page * $page; include"db.php"; $query_pag_data = "SELECT `imgURL`,`imgTitle` FROM `images` ". "ORDER BY `imgDate` DESC LIMIT $start, $per_page"; $result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error()); echo "<ul class='new_arrivals_gallery'>"; while($row = mysql_fetch_assoc($result_pag_data)) { echo "<li><a target='_blank' href='new_arrivals_img/".$row['imgURL']."' class='gallery' title='".$row['imgTitle']."'><img src='new_arrivals_img/thumbnails/".$row['imgURL']."'></a></li>"; } echo "</ul>"; /* --------------------------------------------- */ $query_pag_num = "SELECT COUNT(*) AS count FROM images"; $result_pag_num = mysql_query($query_pag_num); $row = mysql_fetch_array($result_pag_num); $count = $row['count']; $no_of_paginations = ceil($count / $per_page); ?> ``` Thanks for your help!
2011/08/22
['https://Stackoverflow.com/questions/7152533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/708274/']
You should use query: ``` $query_pag_data = "SELECT SQL_CALC_FOUND_ROWS `imgURL`,`imgTitle` FROM `images` ". "ORDER BY `imgDate` DESC LIMIT $start, $per_page"; ``` And instead of ``` $query_pag_num = "SELECT COUNT(*) AS count FROM images"; ``` use ``` $query_pag_num = "SELECT FOUND_ROWS()"; ```
Sometimes you just have to bite the bullet and do a query twice. Accept the user-provided "I want page X" value, and try to get that particular page. If it ends up being past the end of the available data, you can either say "hey, wait... that ain't right" and abort, or redo the loop and default to the last available page. ``` while(true) { $sql = "select sql_calc_found_rows .... limit $X,$Y"; $result = mysql_query($sql) or die(mysql_error()); $sql = "select found_rows();"; // retrieve the sql_calc_found_rows_value $res2 = mysql_query($sql); $row = mysql_fetch_array($res2); $total_rows = $row[0]; if ($total_rows < $requested_row) { ... redo the loop and request last possible page ... } else { break; } } ``` details on found\_rows() function [here](http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows).
7,152,533
I have an Ajax call to create an image gallery. There is a combo box to set the number of images per page, and pagination to navigate through the pages. It's working fine, except that if a person is on the last page, and they increase the number of images per page, it reloads to the current page number. This is a problem because there are now less pages and so the page is blank. In other words, you end up on `page 7 of 5` for instance. I reckon the problem is in the PHP as that is where the number of pages is calculated. I've thought out an `if` statement to deal with this: ``` if ($page > $no_of_paginations) { $page = $no_of_paginations; } ``` However, I don't know where to place this. The reason being, `$page` needs to be defined *before* the mysql\_query, but `$no_of_paginations` is defined *after* the query. Any thoughts on how I can make this functional? I'll post the pertinent code below: ``` <?php $page = 0; if(isset($_GET['page'])){ $page = (int) $_GET['page']; } $cur_page = $page; $page -= 1; if((int) $_GET['imgs'] > 0){ $per_page = (int) $_GET['imgs']; } else { $per_page = 16; } $start = $per_page * $page; include"db.php"; $query_pag_data = "SELECT `imgURL`,`imgTitle` FROM `images` ". "ORDER BY `imgDate` DESC LIMIT $start, $per_page"; $result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error()); echo "<ul class='new_arrivals_gallery'>"; while($row = mysql_fetch_assoc($result_pag_data)) { echo "<li><a target='_blank' href='new_arrivals_img/".$row['imgURL']."' class='gallery' title='".$row['imgTitle']."'><img src='new_arrivals_img/thumbnails/".$row['imgURL']."'></a></li>"; } echo "</ul>"; /* --------------------------------------------- */ $query_pag_num = "SELECT COUNT(*) AS count FROM images"; $result_pag_num = mysql_query($query_pag_num); $row = mysql_fetch_array($result_pag_num); $count = $row['count']; $no_of_paginations = ceil($count / $per_page); ?> ``` Thanks for your help!
2011/08/22
['https://Stackoverflow.com/questions/7152533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/708274/']
As you are currently doing it, there would be no problem with moving the last section to above the main query. A better way to find the total records with MySQL is to use the [SQL\_CALC\_FOUND\_ROWS](http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows) keyword on your main query (so here it is `SELECT SQL_CALC_FOUND_ROWS imgURL, imgTitle FROM images WHERE etc`) then you can query `SELECT FOUND_ROWS()` and just get the number of records found in the last query. As well as being faster and more efficient, this avoids a race condition when records are added between the two queries. However, in this case you should probably just do the two current queries in the reverse order as your only other option is to check at the end and repeat if necessary.
You should use query: ``` $query_pag_data = "SELECT SQL_CALC_FOUND_ROWS `imgURL`,`imgTitle` FROM `images` ". "ORDER BY `imgDate` DESC LIMIT $start, $per_page"; ``` And instead of ``` $query_pag_num = "SELECT COUNT(*) AS count FROM images"; ``` use ``` $query_pag_num = "SELECT FOUND_ROWS()"; ```
7,152,533
I have an Ajax call to create an image gallery. There is a combo box to set the number of images per page, and pagination to navigate through the pages. It's working fine, except that if a person is on the last page, and they increase the number of images per page, it reloads to the current page number. This is a problem because there are now less pages and so the page is blank. In other words, you end up on `page 7 of 5` for instance. I reckon the problem is in the PHP as that is where the number of pages is calculated. I've thought out an `if` statement to deal with this: ``` if ($page > $no_of_paginations) { $page = $no_of_paginations; } ``` However, I don't know where to place this. The reason being, `$page` needs to be defined *before* the mysql\_query, but `$no_of_paginations` is defined *after* the query. Any thoughts on how I can make this functional? I'll post the pertinent code below: ``` <?php $page = 0; if(isset($_GET['page'])){ $page = (int) $_GET['page']; } $cur_page = $page; $page -= 1; if((int) $_GET['imgs'] > 0){ $per_page = (int) $_GET['imgs']; } else { $per_page = 16; } $start = $per_page * $page; include"db.php"; $query_pag_data = "SELECT `imgURL`,`imgTitle` FROM `images` ". "ORDER BY `imgDate` DESC LIMIT $start, $per_page"; $result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error()); echo "<ul class='new_arrivals_gallery'>"; while($row = mysql_fetch_assoc($result_pag_data)) { echo "<li><a target='_blank' href='new_arrivals_img/".$row['imgURL']."' class='gallery' title='".$row['imgTitle']."'><img src='new_arrivals_img/thumbnails/".$row['imgURL']."'></a></li>"; } echo "</ul>"; /* --------------------------------------------- */ $query_pag_num = "SELECT COUNT(*) AS count FROM images"; $result_pag_num = mysql_query($query_pag_num); $row = mysql_fetch_array($result_pag_num); $count = $row['count']; $no_of_paginations = ceil($count / $per_page); ?> ``` Thanks for your help!
2011/08/22
['https://Stackoverflow.com/questions/7152533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/708274/']
As you are currently doing it, there would be no problem with moving the last section to above the main query. A better way to find the total records with MySQL is to use the [SQL\_CALC\_FOUND\_ROWS](http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows) keyword on your main query (so here it is `SELECT SQL_CALC_FOUND_ROWS imgURL, imgTitle FROM images WHERE etc`) then you can query `SELECT FOUND_ROWS()` and just get the number of records found in the last query. As well as being faster and more efficient, this avoids a race condition when records are added between the two queries. However, in this case you should probably just do the two current queries in the reverse order as your only other option is to check at the end and repeat if necessary.
Sometimes you just have to bite the bullet and do a query twice. Accept the user-provided "I want page X" value, and try to get that particular page. If it ends up being past the end of the available data, you can either say "hey, wait... that ain't right" and abort, or redo the loop and default to the last available page. ``` while(true) { $sql = "select sql_calc_found_rows .... limit $X,$Y"; $result = mysql_query($sql) or die(mysql_error()); $sql = "select found_rows();"; // retrieve the sql_calc_found_rows_value $res2 = mysql_query($sql); $row = mysql_fetch_array($res2); $total_rows = $row[0]; if ($total_rows < $requested_row) { ... redo the loop and request last possible page ... } else { break; } } ``` details on found\_rows() function [here](http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows).
3,119,558
i am trying to store the user preference of whether the checkbox is clicked or not in an Activity , but when i shutdown and restart the app, i don't get the desired result . i.e if the user had checked the checkbox then on restarting i am not getting it as checked. here's what i have tried: ``` public void onCreate() { .... checkbox=(CheckBox)findViewById(R.id.checkbox); // storing the user preference SharedPreferences sharedpref = getSharedPreferences(MYPREF,Activity.MODE_PRIVATE); //here MYPREF is the name of the file storing the preference SharedPreferences.Editor e = sharedpref.edit(); e.putBoolean("checkboxvalue", checkbox.isChecked()); e.commit(); //retrieving the preference set SharedPreferences mysharedpref = getSharedPreferences(TextSpeaker.MYPREF,Activity.MODE_PRIVATE); checked=mysharedpref.getBoolean("checkboxvalue", false); if(checked)checkbox.setChecked(true); ```
2010/06/25
['https://Stackoverflow.com/questions/3119558', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/238505/']
Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs. Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity. 1. Shared Preferences: The shared preferences can be used by all the components (activities, services etc) off the applications. 2. Activity handled preferences: These preferences can only be used with in the activity and can not be used by other components of the application. **Shared Preferences:** The shared preferences are managed with the help of `getSharedPreferences` method of the `Context` class. The preferences are stored in a default file(1) or you can specify a file name(2) to be used to refer to the preferences. (1) Here is how you get the instance when you specify the file name ``` public static final String PREF_FILE_NAME = "PrefFile"; SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE); ``` `MODE_PRIVATE` is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two mode supported are `MODE_WORLD_READABLE` and `MODE_WORLD_WRITEABLE`. In `MODE_WORLD_READABLE` other application can read the created file but can not modify it. In case of `MODE_WORLD_WRITEABLE` other applications also have write permissions for the created file. (2) **The recommended way** is to use by the default mode, without specifying the file name ``` SharedPreferences preferences = PreferencesManager.getDefaultSharedPreferences(context); ``` Finally, once you have the preferences instance, here is how you can **retrieve the stored values** from the preferences: ``` int storedPreference = preferences.getInt("storedInt", 0); ``` To **store values** in the preference file `SharedPreference.Editor` object has to be used. `Editor` is the nested interface of the `SharedPreference` class. ``` SharedPreferences.Editor editor = preferences.edit(); editor.putInt("storedInt", storedPreference); // value to store editor.commit(); ``` Editor also support methods like `remove()` and `clear()` to delete the preference value from the file. **Activity Preferences:** The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activities private preferences. You can do that with the help of `getPreferences()` method of the activity. The `getPreference` method uses the `getSharedPreferences()` method with the name of the activity class for the preference file name. Following is the code to get preferences ``` SharedPreferences preferences = getPreferences(MODE_PRIVATE); int storedPreference = preferences.getInt("storedInt", 0); ``` The code to store values is also same as in case of shared preferences. ``` SharedPreferences preferences = getPreference(MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("storedInt", storedPreference); // value to store editor.commit(); ``` You can also use other methods like storing the activity state in database. Note Android also contains a package called `android.preference`. The package defines classes to implement application preferences UI. To see some more examples check Android's [Data Storage](http://developer.android.com/intl/de/guide/topics/data/data-storage.html#pref) post on developers site.
You are working with two separate preference data files, in all likelihood, since it would appear that you have two different components (e.g., activities). Try switching to using `getDefaultSharedPreferences()` (available on `PreferenceManager`) instead of `getSharedPreferences()`, and see if that helps.
3,119,558
i am trying to store the user preference of whether the checkbox is clicked or not in an Activity , but when i shutdown and restart the app, i don't get the desired result . i.e if the user had checked the checkbox then on restarting i am not getting it as checked. here's what i have tried: ``` public void onCreate() { .... checkbox=(CheckBox)findViewById(R.id.checkbox); // storing the user preference SharedPreferences sharedpref = getSharedPreferences(MYPREF,Activity.MODE_PRIVATE); //here MYPREF is the name of the file storing the preference SharedPreferences.Editor e = sharedpref.edit(); e.putBoolean("checkboxvalue", checkbox.isChecked()); e.commit(); //retrieving the preference set SharedPreferences mysharedpref = getSharedPreferences(TextSpeaker.MYPREF,Activity.MODE_PRIVATE); checked=mysharedpref.getBoolean("checkboxvalue", false); if(checked)checkbox.setChecked(true); ```
2010/06/25
['https://Stackoverflow.com/questions/3119558', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/238505/']
Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs. Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity. 1. Shared Preferences: The shared preferences can be used by all the components (activities, services etc) off the applications. 2. Activity handled preferences: These preferences can only be used with in the activity and can not be used by other components of the application. **Shared Preferences:** The shared preferences are managed with the help of `getSharedPreferences` method of the `Context` class. The preferences are stored in a default file(1) or you can specify a file name(2) to be used to refer to the preferences. (1) Here is how you get the instance when you specify the file name ``` public static final String PREF_FILE_NAME = "PrefFile"; SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE); ``` `MODE_PRIVATE` is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two mode supported are `MODE_WORLD_READABLE` and `MODE_WORLD_WRITEABLE`. In `MODE_WORLD_READABLE` other application can read the created file but can not modify it. In case of `MODE_WORLD_WRITEABLE` other applications also have write permissions for the created file. (2) **The recommended way** is to use by the default mode, without specifying the file name ``` SharedPreferences preferences = PreferencesManager.getDefaultSharedPreferences(context); ``` Finally, once you have the preferences instance, here is how you can **retrieve the stored values** from the preferences: ``` int storedPreference = preferences.getInt("storedInt", 0); ``` To **store values** in the preference file `SharedPreference.Editor` object has to be used. `Editor` is the nested interface of the `SharedPreference` class. ``` SharedPreferences.Editor editor = preferences.edit(); editor.putInt("storedInt", storedPreference); // value to store editor.commit(); ``` Editor also support methods like `remove()` and `clear()` to delete the preference value from the file. **Activity Preferences:** The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activities private preferences. You can do that with the help of `getPreferences()` method of the activity. The `getPreference` method uses the `getSharedPreferences()` method with the name of the activity class for the preference file name. Following is the code to get preferences ``` SharedPreferences preferences = getPreferences(MODE_PRIVATE); int storedPreference = preferences.getInt("storedInt", 0); ``` The code to store values is also same as in case of shared preferences. ``` SharedPreferences preferences = getPreference(MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("storedInt", storedPreference); // value to store editor.commit(); ``` You can also use other methods like storing the activity state in database. Note Android also contains a package called `android.preference`. The package defines classes to implement application preferences UI. To see some more examples check Android's [Data Storage](http://developer.android.com/intl/de/guide/topics/data/data-storage.html#pref) post on developers site.
Hi Pranay if you created before your preference with the same name in other activity or app you will have problems reading the same preference change to MODE\_WORLD\_READABLE ``` getSharedPreferences(MYPREF,Activity.MODE_WORLD_READABLE); ``` or ``` getSharedPreferences(MYPREF,1); ```
74,065,222
I am trying to decode the JSON string into a single element. Below is my code. It is returning null as a result. ``` var topOfHead = landmarks.Landmark[10]; string jsonString = topOfHead.ToString(); //Json in String - tophead:{ "x": 0.8063538, "y": 0.6247897, "z": -0.0117829954 } DistanceVector serialized = JsonUtility.FromJson<DistanceVector>(jsonString); //Debug.Log("Headposition: " + serialized.x); ``` DistanceVector Class ``` [SerializeField] public class DistanceVector{ public double? x{get; set;} public double? y{get; set;} public double? z{get; set;} } ``` serialized.x value is coming to zero in this case.
2022/10/14
['https://Stackoverflow.com/questions/74065222', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2722645/']
JsonUtility in Unity follows the same serialisation rules for all objects. That means you can't natively (de)serialise such things as dictionaries. It also means you can't (de)serialise properties or nullables. To get around this, you'd have to modify your code: ```cs [Serializable] public class DistanceVector { public double x; public double y; public double z; } ``` The class should aso be decorated with the `[Serializable]` attribute if you'd like to Unity to also serialise it through the Inspector. I assume that the following comment doesn't actually include the 'tophead' string in your Json? ``` //Json in String - tophead:{ "x": 0.8063538, "y": 0.6247897, "z": -0.0117829954 } ``` If Json DOES include 'tophead', are you able to remove it? That 'tophead' is considered an element of its own otherwise, and as such you'd need to deserialise an item that contains its own field of type `DistanceVector`. For example: ```cs [Serializable] public class Container { public DistanceVector tophead; } var tophead = JsonUtility.FromJson<Container>(jsonString).tophead; ``` JsonUtility will then also require the Json format to be: ``` { "tophead":{ "x": 0.8063538, "y": 0.6247897, "z": -0.0117829954 } } ``` The alternative is to use a different Json Serialiser such as Newtonsoft.Json or System.Text.Json (my preference).
Don't use the "?" because it is detecting the current variable as a nullable and it returns a null value. Instead of this `public double? x{get; set;}`, replace it with this `public double x{get; set;}`
251,783
ASP.Net is Active Server Pages using .Net Framework [Wikipedia](http://en.wikipedia.org/wiki/ASP.NET) says > > It was first released in January 2002 with version 1.0 of the .NET Framework, and is the successor to Microsoft's Active Server Pages (ASP) technology. > > > While answering [this](https://stackoverflow.com/questions/22589245/difference-between-mvc-5-project-and-web-api-project/25036611#25036611) question following thought came to me – why Microsoft named it’s Web API as “ASP.Net Web API”. There are no `Pages` involved in Web API. Then why do some people call it as “Active Server Pages .Net Web Api” ? I believe there are some `fundamental features` of ASP.Net shared with Web API. So what are they? Another observation - why is the tag in `programmers` naming it as "asp.net-mvc-web-api"? **Reference**: 1. [ScottGu's Blog- ASP.NET Web API](http://weblogs.asp.net/scottgu/asp-net-web-api-part-1)
2014/07/31
['https://softwareengineering.stackexchange.com/questions/251783', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/58676/']
Because it's part of the ASP.NET framework. Sure, ASP used to stand for "Active Server Pages" but it's really grown to be beyond that now. I've never heard anyone call it "Active Server Pages .Net Web Api", and I would be confused if they did.
While their earlier attempts at .Net API were under the WCF namespaces (we wont go into asmx services, they just failed) people found it much easier to use MVC controller classes and route patterns to do rest style APIs and WCF was always a bit awkward at simple rest as it was designed around a bunch of complex soap or binary use cases like replacing remoting. Many use cases for APIs shifted toward sites and services consuming them and keeping the API in a completely separate app was tedious, so over time the WebAPI style apis have moved closer and closer to being the same thing, in the same namespaces and event model and MVC controllers. If you were working in the guts of security or httpmodules at time time the designation of which event model you were stuck with was a very important detail in what you needed to implement manually to accomplish a task. Saying that they are part of the ASP pattern was important before the push to unify those namespaces. The active server pages name itself goes back to the mid 90's and was mostly a designation between pages that did something through script versus cbi-bin where dlls just took over the whole process. If you ignore the original meaning of the name and look at it as a category that has evolved over the course of almost 20 years it does make some sense.
251,783
ASP.Net is Active Server Pages using .Net Framework [Wikipedia](http://en.wikipedia.org/wiki/ASP.NET) says > > It was first released in January 2002 with version 1.0 of the .NET Framework, and is the successor to Microsoft's Active Server Pages (ASP) technology. > > > While answering [this](https://stackoverflow.com/questions/22589245/difference-between-mvc-5-project-and-web-api-project/25036611#25036611) question following thought came to me – why Microsoft named it’s Web API as “ASP.Net Web API”. There are no `Pages` involved in Web API. Then why do some people call it as “Active Server Pages .Net Web Api” ? I believe there are some `fundamental features` of ASP.Net shared with Web API. So what are they? Another observation - why is the tag in `programmers` naming it as "asp.net-mvc-web-api"? **Reference**: 1. [ScottGu's Blog- ASP.NET Web API](http://weblogs.asp.net/scottgu/asp-net-web-api-part-1)
2014/07/31
['https://softwareengineering.stackexchange.com/questions/251783', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/58676/']
As you probably know, Web API used to be a part of WCF and NOT part of the ASP.NET family. Microsoft tried to develop the technology under the WCF Web API moniker for several years, but eventually decided that they were probably trying to fit a square peg in a round hole. I think that makes sense. After all, WCF always does seems to be more "Service" oriented (I don't like to use that term, but I can't think of a better term), while Web API seems to lean more to the RESTful end of things. So adding it to the ASP.NET family makes a lot of sense to me, as the ASP.NET family relates to everything Microsoft is doing that involves HTTP/Web. Try not to take the ASP.NET name too seriously, as the original ASP name was conceived in 2000. Think of it more as the .NET stack for building full-fledged web applications, whether that involves web pages or not.
While their earlier attempts at .Net API were under the WCF namespaces (we wont go into asmx services, they just failed) people found it much easier to use MVC controller classes and route patterns to do rest style APIs and WCF was always a bit awkward at simple rest as it was designed around a bunch of complex soap or binary use cases like replacing remoting. Many use cases for APIs shifted toward sites and services consuming them and keeping the API in a completely separate app was tedious, so over time the WebAPI style apis have moved closer and closer to being the same thing, in the same namespaces and event model and MVC controllers. If you were working in the guts of security or httpmodules at time time the designation of which event model you were stuck with was a very important detail in what you needed to implement manually to accomplish a task. Saying that they are part of the ASP pattern was important before the push to unify those namespaces. The active server pages name itself goes back to the mid 90's and was mostly a designation between pages that did something through script versus cbi-bin where dlls just took over the whole process. If you ignore the original meaning of the name and look at it as a category that has evolved over the course of almost 20 years it does make some sense.
865,710
I observed huge difference between following two scenarios for copying a file: 1. Copying a file into a new file. 2. Copying a file in an existing file and overwriting it. I expect both operations take the same amount of time to complete. But the first scenario is much faster in practice. I tried this on two different file systems, getting the same result. Any idea why the first scenario is much faster? **Example in Linux:** ``` $ dd bs=1024 count=1000000 if=/dev/zero of=dummyfile.txt 1000000+0 records in 1000000+0 records out 1024000000 bytes (1.0 GB) copied, 7.45639 s, 137 MB/s $ while [ "1" == "1" ]; do time cp dummyfile.txt dummyfile2.txt ; rm dummyfile2.txt ; done real 0m0.850s user 0m0.003s sys 0m0.847s real 0m0.778s user 0m0.000s sys 0m0.776s real 0m0.775s user 0m0.004s sys 0m0.772s real 0m0.775s user 0m0.003s sys 0m0.770s real 0m0.776s user 0m0.008s sys 0m0.766s ^C $ rm dummyfile2.txt -f $ while [ "1" == "1" ]; do time cp dummyfile.txt dummyfile2.txt ; done real 0m0.839s user 0m0.003s sys 0m0.834s real 0m6.056s user 0m0.005s sys 0m1.683s real 0m6.614s user 0m0.002s sys 0m1.405s real 0m6.858s user 0m0.003s sys 0m1.436s ``` **EDIT:** test is performed on an SSD disk. I observed the same trend on HDD, but the gap is lower than SDD (2-3X). Following page explains why SSDs are much slower than HDDs in overwrite: [Trim (computing) Wikipedia page](http://en.wikipedia.org/wiki/Trim_(computing))
2015/01/16
['https://superuser.com/questions/865710', 'https://superuser.com', 'https://superuser.com/users/173093/']
Actually the physical copying takes the same time. But the ext4 filesystem driver close() waits before data are really written when the operation is done on an existing i-node and it does not wait for write operation if it is done on a new node. I did some experiments and realized that it is the ext4 feature. I have not seen such a difference with copying on btrfs, zfs, ext3, ext. How can I say that the close is the time consuming operation? *strace* provides the information: ``` $ strace -tt -T cp bigfile newfile ... 14:36:41.985437 open("bigfile", O_RDONLY) = 3 <0.000009> 14:36:41.985466 fstat(3, {st_mode=S_IFREG|0664, st_size=647608649, ...}) = 0 <0.000007> 14:36:41.985495 open("newfile", O_WRONLY|O_CREAT|O_EXCL, 0664) = 4 <0.000086> 14:36:41.985602 fstat(4, {st_mode=S_IFREG|0664, st_size=0, ...}) = 0 <0.000007> 14:36:41.985633 fadvise64(3, 0, 0, POSIX_FADV_SEQUENTIAL) = 0 <0.000008> ... a lot of reads and writes 14:36:43.584223 close(4) = 0 <0.000009> 14:36:43.584248 close(3) = 0 <0.000008> ... $ strace -tt -T cp bigfile existingfile ... 14:36:52.393034 open("bigfile", O_RDONLY) = 3 <0.000010> 14:36:52.393071 fstat(3, {st_mode=S_IFREG|0664, st_size=647608649, ...}) = 0 <0.000009> 14:36:52.393104 open("existingfile", O_WRONLY|O_TRUNC) = 4 <0.097058> 14:36:52.490211 fstat(4, {st_mode=S_IFREG|0664, st_size=0, ...}) = 0 <0.000007> 14:36:52.490278 fadvise64(3, 0, 0, POSIX_FADV_SEQUENTIAL) = 0 <0.000009> ... a lot of reads and writes 14:36:54.047408 close(4) = 0 <5.346015> 14:36:59.393466 close(3) = 0 <0.000011> ... ``` Note that the close(4) takes more than 5 seconds whereas in case of copying to the existing file and it is immediate when a new file is created. I run *iostat* to check what the system doing. The read of the bigfile was executed before the test to avoid file system cache effect. ``` # iostat sda 1 100 Device: tps kB_read/s kB_wrtn/s kB_read kB_wrtn sda 0.00 0.00 0.00 0 0 sda 0.00 0.00 0.00 0 0 --------------- copy to a new file starts here ----------------------- sda 24.00 0.00 8340.00 0 8340 sda 174.00 8.00 86596.00 8 86596 sda 170.00 0.00 86020.00 0 86020 --------------- copy to a new file finishes here --------------------- sda 177.00 4.00 90112.00 4 90112 sda 176.00 4.00 89600.00 4 89600 sda 166.00 0.00 84992.00 0 84992 sda 161.00 4.00 81920.00 4 81920 sda 157.00 0.00 78888.00 0 78888 sda 52.00 0.00 26224.00 0 26224 sda 0.00 0.00 0.00 0 0 sda 0.00 0.00 0.00 0 0 sda 0.00 0.00 0.00 0 0 --------------- copy to the existing file starts here ---------------- sda 12.00 0.00 4128.00 0 4128 sda 172.00 4.00 87040.00 4 87040 sda 180.00 4.00 91648.00 4 91648 sda 175.00 0.00 89600.00 0 89600 sda 173.00 4.00 88064.00 4 88064 sda 168.00 4.00 83532.00 4 83532 sda 159.00 0.00 81408.00 0 81408 sda 181.00 4.00 92160.00 4 92160 sda 30.00 0.00 14960.00 0 14960 --------------- copy to the existing file finishes here -------------- sda 0.00 0.00 0.00 0 0 sda 3.00 0.00 28.00 0 28 ``` Note the copying to a new file finishes before data is written and the write operation continues some although the cp is done from user point of view.
Overwriting takes a seek operation... The file's permissions must be read in order to know if you can overwrite it(which may or may not be an issue depending on your file system). Also the file must be truncated. This requires the drive to seek to the position where the file is.. Copying into a new file generates new permissions and uses the closest available free blocks to write and does not need a seek. Look into "copy-on-write" file systems(Like ZFS) that don't do this..
865,710
I observed huge difference between following two scenarios for copying a file: 1. Copying a file into a new file. 2. Copying a file in an existing file and overwriting it. I expect both operations take the same amount of time to complete. But the first scenario is much faster in practice. I tried this on two different file systems, getting the same result. Any idea why the first scenario is much faster? **Example in Linux:** ``` $ dd bs=1024 count=1000000 if=/dev/zero of=dummyfile.txt 1000000+0 records in 1000000+0 records out 1024000000 bytes (1.0 GB) copied, 7.45639 s, 137 MB/s $ while [ "1" == "1" ]; do time cp dummyfile.txt dummyfile2.txt ; rm dummyfile2.txt ; done real 0m0.850s user 0m0.003s sys 0m0.847s real 0m0.778s user 0m0.000s sys 0m0.776s real 0m0.775s user 0m0.004s sys 0m0.772s real 0m0.775s user 0m0.003s sys 0m0.770s real 0m0.776s user 0m0.008s sys 0m0.766s ^C $ rm dummyfile2.txt -f $ while [ "1" == "1" ]; do time cp dummyfile.txt dummyfile2.txt ; done real 0m0.839s user 0m0.003s sys 0m0.834s real 0m6.056s user 0m0.005s sys 0m1.683s real 0m6.614s user 0m0.002s sys 0m1.405s real 0m6.858s user 0m0.003s sys 0m1.436s ``` **EDIT:** test is performed on an SSD disk. I observed the same trend on HDD, but the gap is lower than SDD (2-3X). Following page explains why SSDs are much slower than HDDs in overwrite: [Trim (computing) Wikipedia page](http://en.wikipedia.org/wiki/Trim_(computing))
2015/01/16
['https://superuser.com/questions/865710', 'https://superuser.com', 'https://superuser.com/users/173093/']
I believe it's ext4's `auto_da_alloc` behavior that makes this difference. [see ext4 kernel doc](https://www.kernel.org/doc/html/latest/admin-guide/ext4.html) @Zaboj Campula 's answer show us that close() a truncated file would block until written data got "forced to disk". ext4 auto detected this replace-by-truncate use pattern. likewise, if you rename (mv) your new created file as some existing file, you will find that the rename() syscall will block for some time. that's the replace-by-rename use pattern.
Overwriting takes a seek operation... The file's permissions must be read in order to know if you can overwrite it(which may or may not be an issue depending on your file system). Also the file must be truncated. This requires the drive to seek to the position where the file is.. Copying into a new file generates new permissions and uses the closest available free blocks to write and does not need a seek. Look into "copy-on-write" file systems(Like ZFS) that don't do this..
865,710
I observed huge difference between following two scenarios for copying a file: 1. Copying a file into a new file. 2. Copying a file in an existing file and overwriting it. I expect both operations take the same amount of time to complete. But the first scenario is much faster in practice. I tried this on two different file systems, getting the same result. Any idea why the first scenario is much faster? **Example in Linux:** ``` $ dd bs=1024 count=1000000 if=/dev/zero of=dummyfile.txt 1000000+0 records in 1000000+0 records out 1024000000 bytes (1.0 GB) copied, 7.45639 s, 137 MB/s $ while [ "1" == "1" ]; do time cp dummyfile.txt dummyfile2.txt ; rm dummyfile2.txt ; done real 0m0.850s user 0m0.003s sys 0m0.847s real 0m0.778s user 0m0.000s sys 0m0.776s real 0m0.775s user 0m0.004s sys 0m0.772s real 0m0.775s user 0m0.003s sys 0m0.770s real 0m0.776s user 0m0.008s sys 0m0.766s ^C $ rm dummyfile2.txt -f $ while [ "1" == "1" ]; do time cp dummyfile.txt dummyfile2.txt ; done real 0m0.839s user 0m0.003s sys 0m0.834s real 0m6.056s user 0m0.005s sys 0m1.683s real 0m6.614s user 0m0.002s sys 0m1.405s real 0m6.858s user 0m0.003s sys 0m1.436s ``` **EDIT:** test is performed on an SSD disk. I observed the same trend on HDD, but the gap is lower than SDD (2-3X). Following page explains why SSDs are much slower than HDDs in overwrite: [Trim (computing) Wikipedia page](http://en.wikipedia.org/wiki/Trim_(computing))
2015/01/16
['https://superuser.com/questions/865710', 'https://superuser.com', 'https://superuser.com/users/173093/']
Actually the physical copying takes the same time. But the ext4 filesystem driver close() waits before data are really written when the operation is done on an existing i-node and it does not wait for write operation if it is done on a new node. I did some experiments and realized that it is the ext4 feature. I have not seen such a difference with copying on btrfs, zfs, ext3, ext. How can I say that the close is the time consuming operation? *strace* provides the information: ``` $ strace -tt -T cp bigfile newfile ... 14:36:41.985437 open("bigfile", O_RDONLY) = 3 <0.000009> 14:36:41.985466 fstat(3, {st_mode=S_IFREG|0664, st_size=647608649, ...}) = 0 <0.000007> 14:36:41.985495 open("newfile", O_WRONLY|O_CREAT|O_EXCL, 0664) = 4 <0.000086> 14:36:41.985602 fstat(4, {st_mode=S_IFREG|0664, st_size=0, ...}) = 0 <0.000007> 14:36:41.985633 fadvise64(3, 0, 0, POSIX_FADV_SEQUENTIAL) = 0 <0.000008> ... a lot of reads and writes 14:36:43.584223 close(4) = 0 <0.000009> 14:36:43.584248 close(3) = 0 <0.000008> ... $ strace -tt -T cp bigfile existingfile ... 14:36:52.393034 open("bigfile", O_RDONLY) = 3 <0.000010> 14:36:52.393071 fstat(3, {st_mode=S_IFREG|0664, st_size=647608649, ...}) = 0 <0.000009> 14:36:52.393104 open("existingfile", O_WRONLY|O_TRUNC) = 4 <0.097058> 14:36:52.490211 fstat(4, {st_mode=S_IFREG|0664, st_size=0, ...}) = 0 <0.000007> 14:36:52.490278 fadvise64(3, 0, 0, POSIX_FADV_SEQUENTIAL) = 0 <0.000009> ... a lot of reads and writes 14:36:54.047408 close(4) = 0 <5.346015> 14:36:59.393466 close(3) = 0 <0.000011> ... ``` Note that the close(4) takes more than 5 seconds whereas in case of copying to the existing file and it is immediate when a new file is created. I run *iostat* to check what the system doing. The read of the bigfile was executed before the test to avoid file system cache effect. ``` # iostat sda 1 100 Device: tps kB_read/s kB_wrtn/s kB_read kB_wrtn sda 0.00 0.00 0.00 0 0 sda 0.00 0.00 0.00 0 0 --------------- copy to a new file starts here ----------------------- sda 24.00 0.00 8340.00 0 8340 sda 174.00 8.00 86596.00 8 86596 sda 170.00 0.00 86020.00 0 86020 --------------- copy to a new file finishes here --------------------- sda 177.00 4.00 90112.00 4 90112 sda 176.00 4.00 89600.00 4 89600 sda 166.00 0.00 84992.00 0 84992 sda 161.00 4.00 81920.00 4 81920 sda 157.00 0.00 78888.00 0 78888 sda 52.00 0.00 26224.00 0 26224 sda 0.00 0.00 0.00 0 0 sda 0.00 0.00 0.00 0 0 sda 0.00 0.00 0.00 0 0 --------------- copy to the existing file starts here ---------------- sda 12.00 0.00 4128.00 0 4128 sda 172.00 4.00 87040.00 4 87040 sda 180.00 4.00 91648.00 4 91648 sda 175.00 0.00 89600.00 0 89600 sda 173.00 4.00 88064.00 4 88064 sda 168.00 4.00 83532.00 4 83532 sda 159.00 0.00 81408.00 0 81408 sda 181.00 4.00 92160.00 4 92160 sda 30.00 0.00 14960.00 0 14960 --------------- copy to the existing file finishes here -------------- sda 0.00 0.00 0.00 0 0 sda 3.00 0.00 28.00 0 28 ``` Note the copying to a new file finishes before data is written and the write operation continues some although the cp is done from user point of view.
I believe it's ext4's `auto_da_alloc` behavior that makes this difference. [see ext4 kernel doc](https://www.kernel.org/doc/html/latest/admin-guide/ext4.html) @Zaboj Campula 's answer show us that close() a truncated file would block until written data got "forced to disk". ext4 auto detected this replace-by-truncate use pattern. likewise, if you rename (mv) your new created file as some existing file, you will find that the rename() syscall will block for some time. that's the replace-by-rename use pattern.
13,976,550
Let's say you want to create an ASP.NET web app. You *think* it will always just be a web app (with regular and mobile pages) but you never know. It's possible someday you might want to have an iPhone, iPad, Android, or whatever app as a client. If there is a 0% chance of this, you'd package your business layer as DLLs and reference them from your client. If there's a 1% or greater chance of those other front-end apps in the future, you'd package your business layer in WCF and expose via http (i.e. service oriented architecture (SOA), software as a service that any client can consume regardless of platform). * **DLL pro:** speed/performance. * **DLL con:** Only Microsoft clients can consume and must have DLL with client. That also means if DLL embedded with client app, then long distance to take data to business tier to process and then return. * **WCF pro:** Extensibility.. any client can consume. * **WCF con:** speed/performance. Software architecture is all about finding the right balance of performance and flexibility. I guess you'd have to go WCF in this case as an insurance policy?
2012/12/20
['https://Stackoverflow.com/questions/13976550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1761600/']
You don't have to go with WCF. If the need arises and you need to expose your BLL's functionality to other non-microsoft types, then you can create a new WCF service. Inside this new service, you can create wrapper methods in your ServiceContract that expose your DLL's methods, etc. So, you can just create your DLL and create a service for it in the future if a need arises.
To my mind you could use [ASP.NET Web API](http://www.asp.net/web-api) (or at least to add it to your list). You can create web site that will call REST api and it will be available from native apps too. Check next articles for more information: * [Introduction to the ASP.NET Web API](http://stephenwalther.com/archive/2012/03/05/introduction-to-the-asp-net-web-api.aspx) * [ASP.NET WebAPI: Getting Started with MVC4 and WebAPI](http://www.codeproject.com/Articles/344078/ASP-NET-WebAPI-Getting-Started-with-MVC4-and-WebAP)
13,976,550
Let's say you want to create an ASP.NET web app. You *think* it will always just be a web app (with regular and mobile pages) but you never know. It's possible someday you might want to have an iPhone, iPad, Android, or whatever app as a client. If there is a 0% chance of this, you'd package your business layer as DLLs and reference them from your client. If there's a 1% or greater chance of those other front-end apps in the future, you'd package your business layer in WCF and expose via http (i.e. service oriented architecture (SOA), software as a service that any client can consume regardless of platform). * **DLL pro:** speed/performance. * **DLL con:** Only Microsoft clients can consume and must have DLL with client. That also means if DLL embedded with client app, then long distance to take data to business tier to process and then return. * **WCF pro:** Extensibility.. any client can consume. * **WCF con:** speed/performance. Software architecture is all about finding the right balance of performance and flexibility. I guess you'd have to go WCF in this case as an insurance policy?
2012/12/20
['https://Stackoverflow.com/questions/13976550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1761600/']
You don't have to go with WCF. If the need arises and you need to expose your BLL's functionality to other non-microsoft types, then you can create a new WCF service. Inside this new service, you can create wrapper methods in your ServiceContract that expose your DLL's methods, etc. So, you can just create your DLL and create a service for it in the future if a need arises.
Two options come to mind * Define coarse-grained public methods in your BLL that are stateless. If/when you wish to run as a WCF service you can easily wrap your library. * Or implement as WCF and host locally The second option is better suited for a proof-of-concept. A good description is at <http://msdn.microsoft.com/en-us/library/bb332338.aspx>
34,263,306
I want to convert currency from INR to USD in php, here is my code I've tried so far. But its not working. What am i missing? ```html function currency($from_Currency,$to_Currency,$amount) { $amount = urlencode($amount); $from_Currency = urlencode($from_Currency); $to_Currency = urlencode($to_Currency); $url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency"; $ch = curl_init(); $timeout = 0; curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $rawdata = curl_exec($ch); curl_close($ch); $data = explode('"', $rawdata); $data = explode('"', $data['3']); $var = $data[0]; return round($var,3); } $amount=130; $from='INR'; $to='USD'; echo currency($from,$to,$amount); ```
2015/12/14
['https://Stackoverflow.com/questions/34263306', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
As google changed the URL to ``` https://www.google.com/finance/converter?a ``` So the fix i found is below. ``` $amount = 1.00; $from_Currency = 'USD'; $to_Currency = 'INR'; $amount = urlencode($amount); $from_Currency = urlencode($from_Currency); $to_Currency = urlencode($to_Currency); $get = file_get_contents("https://www.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency"); $get = explode("<span class=bld>",$get); $get = explode("</span>",$get[1]); echo $converted_amount = preg_replace("/[^0-9\.]/", null, $get[0]); ``` Original source: [Google currency converter API - will it shut down with iGoogle?](https://stackoverflow.com/questions/17773898/google-currency-converter-api-will-it-shut-down-with-igoogle)
Google have been change currency converter `API` So you can get it using : ``` function currency($from_Currency,$to_Currency,$amount) { $amount = urlencode($amount); $from_Currency = urlencode($from_Currency); $to_Currency = urlencode($to_Currency); $get_amount = file_get_contents("https://www.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency"); $get_amount = explode("<span class=bld>",$get_amount); $get_amount = explode("</span>",$get_amount[1]); $converted_amount = preg_replace("/[^0-9\.]/", null, $get_amount[0]); return $converted_amount; } $amount=130; $from='INR'; $to='USD'; echo currency($from,$to,$amount); ```
34,263,306
I want to convert currency from INR to USD in php, here is my code I've tried so far. But its not working. What am i missing? ```html function currency($from_Currency,$to_Currency,$amount) { $amount = urlencode($amount); $from_Currency = urlencode($from_Currency); $to_Currency = urlencode($to_Currency); $url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency"; $ch = curl_init(); $timeout = 0; curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $rawdata = curl_exec($ch); curl_close($ch); $data = explode('"', $rawdata); $data = explode('"', $data['3']); $var = $data[0]; return round($var,3); } $amount=130; $from='INR'; $to='USD'; echo currency($from,$to,$amount); ```
2015/12/14
['https://Stackoverflow.com/questions/34263306', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
As google changed the URL to ``` https://www.google.com/finance/converter?a ``` So the fix i found is below. ``` $amount = 1.00; $from_Currency = 'USD'; $to_Currency = 'INR'; $amount = urlencode($amount); $from_Currency = urlencode($from_Currency); $to_Currency = urlencode($to_Currency); $get = file_get_contents("https://www.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency"); $get = explode("<span class=bld>",$get); $get = explode("</span>",$get[1]); echo $converted_amount = preg_replace("/[^0-9\.]/", null, $get[0]); ``` Original source: [Google currency converter API - will it shut down with iGoogle?](https://stackoverflow.com/questions/17773898/google-currency-converter-api-will-it-shut-down-with-igoogle)
Although both answers above are correct, they use explode instead of regex which is slower(relatively). ``` function currency($from_Currency,$to_Currency,$amount) { $amount = urlencode($amount); $from_Currency = urlencode($from_Currency); $to_Currency = urlencode($to_Currency); $url = "http://www.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency"; $ch = curl_init(); $timeout = 0; curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $rawdata = curl_exec($ch); curl_close($ch); $regularExpression = '#\<span class=bld\>(.+?)\<\/span\>#s'; preg_match($regularExpression, $rawdata, $finalData); echo $finalData[0]; } $amount=130; $from='INR'; $to='USD'; echo currency($from,$to,$amount); ``` Try this code and let us know which one works faster, so that other users can benefit. Cheers
34,263,306
I want to convert currency from INR to USD in php, here is my code I've tried so far. But its not working. What am i missing? ```html function currency($from_Currency,$to_Currency,$amount) { $amount = urlencode($amount); $from_Currency = urlencode($from_Currency); $to_Currency = urlencode($to_Currency); $url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency"; $ch = curl_init(); $timeout = 0; curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $rawdata = curl_exec($ch); curl_close($ch); $data = explode('"', $rawdata); $data = explode('"', $data['3']); $var = $data[0]; return round($var,3); } $amount=130; $from='INR'; $to='USD'; echo currency($from,$to,$amount); ```
2015/12/14
['https://Stackoverflow.com/questions/34263306', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
As google changed the URL to ``` https://www.google.com/finance/converter?a ``` So the fix i found is below. ``` $amount = 1.00; $from_Currency = 'USD'; $to_Currency = 'INR'; $amount = urlencode($amount); $from_Currency = urlencode($from_Currency); $to_Currency = urlencode($to_Currency); $get = file_get_contents("https://www.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency"); $get = explode("<span class=bld>",$get); $get = explode("</span>",$get[1]); echo $converted_amount = preg_replace("/[^0-9\.]/", null, $get[0]); ``` Original source: [Google currency converter API - will it shut down with iGoogle?](https://stackoverflow.com/questions/17773898/google-currency-converter-api-will-it-shut-down-with-igoogle)
``` <?php // change amount according to your needs $amount =1; // change From Currency according to your needs $from_Curr ='USD'; // change To Currency according to your needs $to_Curr ="BHD"; $converted_currency=currencyConverter($from_Curr, $to_Curr, $amount); // Print outout echo $converted_currency; function currencyConverter($from_Currency,$to_Currency,$amount) { // <!-- Currency Coverter // Develop By Punit Kathiriya $from_Currency = urlencode($from_Currency); $to_Currency = urlencode($to_Currency); $get = file_get_contents("https://finance.google.com/finance/converter?a=1&from=$from_Currency&to=$to_Currency"); $get = explode("<span class=bld>",$get); $get = explode("</span>",$get[1]); $converted_currency = preg_replace("/[^0-9\.]/", null, $get[0]); return $converted_currency; // 14/10/2017 11:16 A.M. } ?> ```
34,263,306
I want to convert currency from INR to USD in php, here is my code I've tried so far. But its not working. What am i missing? ```html function currency($from_Currency,$to_Currency,$amount) { $amount = urlencode($amount); $from_Currency = urlencode($from_Currency); $to_Currency = urlencode($to_Currency); $url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency"; $ch = curl_init(); $timeout = 0; curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $rawdata = curl_exec($ch); curl_close($ch); $data = explode('"', $rawdata); $data = explode('"', $data['3']); $var = $data[0]; return round($var,3); } $amount=130; $from='INR'; $to='USD'; echo currency($from,$to,$amount); ```
2015/12/14
['https://Stackoverflow.com/questions/34263306', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
Google have been change currency converter `API` So you can get it using : ``` function currency($from_Currency,$to_Currency,$amount) { $amount = urlencode($amount); $from_Currency = urlencode($from_Currency); $to_Currency = urlencode($to_Currency); $get_amount = file_get_contents("https://www.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency"); $get_amount = explode("<span class=bld>",$get_amount); $get_amount = explode("</span>",$get_amount[1]); $converted_amount = preg_replace("/[^0-9\.]/", null, $get_amount[0]); return $converted_amount; } $amount=130; $from='INR'; $to='USD'; echo currency($from,$to,$amount); ```
Although both answers above are correct, they use explode instead of regex which is slower(relatively). ``` function currency($from_Currency,$to_Currency,$amount) { $amount = urlencode($amount); $from_Currency = urlencode($from_Currency); $to_Currency = urlencode($to_Currency); $url = "http://www.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency"; $ch = curl_init(); $timeout = 0; curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $rawdata = curl_exec($ch); curl_close($ch); $regularExpression = '#\<span class=bld\>(.+?)\<\/span\>#s'; preg_match($regularExpression, $rawdata, $finalData); echo $finalData[0]; } $amount=130; $from='INR'; $to='USD'; echo currency($from,$to,$amount); ``` Try this code and let us know which one works faster, so that other users can benefit. Cheers
34,263,306
I want to convert currency from INR to USD in php, here is my code I've tried so far. But its not working. What am i missing? ```html function currency($from_Currency,$to_Currency,$amount) { $amount = urlencode($amount); $from_Currency = urlencode($from_Currency); $to_Currency = urlencode($to_Currency); $url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency"; $ch = curl_init(); $timeout = 0; curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $rawdata = curl_exec($ch); curl_close($ch); $data = explode('"', $rawdata); $data = explode('"', $data['3']); $var = $data[0]; return round($var,3); } $amount=130; $from='INR'; $to='USD'; echo currency($from,$to,$amount); ```
2015/12/14
['https://Stackoverflow.com/questions/34263306', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
Google have been change currency converter `API` So you can get it using : ``` function currency($from_Currency,$to_Currency,$amount) { $amount = urlencode($amount); $from_Currency = urlencode($from_Currency); $to_Currency = urlencode($to_Currency); $get_amount = file_get_contents("https://www.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency"); $get_amount = explode("<span class=bld>",$get_amount); $get_amount = explode("</span>",$get_amount[1]); $converted_amount = preg_replace("/[^0-9\.]/", null, $get_amount[0]); return $converted_amount; } $amount=130; $from='INR'; $to='USD'; echo currency($from,$to,$amount); ```
``` <?php // change amount according to your needs $amount =1; // change From Currency according to your needs $from_Curr ='USD'; // change To Currency according to your needs $to_Curr ="BHD"; $converted_currency=currencyConverter($from_Curr, $to_Curr, $amount); // Print outout echo $converted_currency; function currencyConverter($from_Currency,$to_Currency,$amount) { // <!-- Currency Coverter // Develop By Punit Kathiriya $from_Currency = urlencode($from_Currency); $to_Currency = urlencode($to_Currency); $get = file_get_contents("https://finance.google.com/finance/converter?a=1&from=$from_Currency&to=$to_Currency"); $get = explode("<span class=bld>",$get); $get = explode("</span>",$get[1]); $converted_currency = preg_replace("/[^0-9\.]/", null, $get[0]); return $converted_currency; // 14/10/2017 11:16 A.M. } ?> ```
34,263,306
I want to convert currency from INR to USD in php, here is my code I've tried so far. But its not working. What am i missing? ```html function currency($from_Currency,$to_Currency,$amount) { $amount = urlencode($amount); $from_Currency = urlencode($from_Currency); $to_Currency = urlencode($to_Currency); $url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency"; $ch = curl_init(); $timeout = 0; curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $rawdata = curl_exec($ch); curl_close($ch); $data = explode('"', $rawdata); $data = explode('"', $data['3']); $var = $data[0]; return round($var,3); } $amount=130; $from='INR'; $to='USD'; echo currency($from,$to,$amount); ```
2015/12/14
['https://Stackoverflow.com/questions/34263306', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
``` <?php // change amount according to your needs $amount =1; // change From Currency according to your needs $from_Curr ='USD'; // change To Currency according to your needs $to_Curr ="BHD"; $converted_currency=currencyConverter($from_Curr, $to_Curr, $amount); // Print outout echo $converted_currency; function currencyConverter($from_Currency,$to_Currency,$amount) { // <!-- Currency Coverter // Develop By Punit Kathiriya $from_Currency = urlencode($from_Currency); $to_Currency = urlencode($to_Currency); $get = file_get_contents("https://finance.google.com/finance/converter?a=1&from=$from_Currency&to=$to_Currency"); $get = explode("<span class=bld>",$get); $get = explode("</span>",$get[1]); $converted_currency = preg_replace("/[^0-9\.]/", null, $get[0]); return $converted_currency; // 14/10/2017 11:16 A.M. } ?> ```
Although both answers above are correct, they use explode instead of regex which is slower(relatively). ``` function currency($from_Currency,$to_Currency,$amount) { $amount = urlencode($amount); $from_Currency = urlencode($from_Currency); $to_Currency = urlencode($to_Currency); $url = "http://www.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency"; $ch = curl_init(); $timeout = 0; curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $rawdata = curl_exec($ch); curl_close($ch); $regularExpression = '#\<span class=bld\>(.+?)\<\/span\>#s'; preg_match($regularExpression, $rawdata, $finalData); echo $finalData[0]; } $amount=130; $from='INR'; $to='USD'; echo currency($from,$to,$amount); ``` Try this code and let us know which one works faster, so that other users can benefit. Cheers
17,077,190
I'm trying to pass a PHP variable to Javascript like this.. ``` var url = <?php echo $urlArray[0]; ?>; ``` The contents of $urlArray[0] is a string from a json decoded array > > "baby" > > > When I run the code I get the error.. > > Uncaught ReferenceError: baby is not defined > > >
2013/06/12
['https://Stackoverflow.com/questions/17077190', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1714301/']
``` var url = "<?php echo $urlArray[0]; ?>"; ``` you forgot the quotes. If you need to export more complicated data structure, you may need [json\_encode](http://php.net/manual/en/function.json-encode.php). This might be helpful if exporting arrays and/or objects.
`json_encode` is your friend - use to wrap anything you're trying to pass to javascript. <http://php.net/manual/en/function.json-encode.php> ``` var url = <?php echo json_encode($urlArray[0]); ?>; ```
66,714,870
I'm really struggling with my code and cannot find a way to make it work. I need to check whether my array exists or its length is not 0 and then if there is an object with a specific value in it. If so then update it. If not then add it. Please see my code below: ``` const originals = []; if (!originals || originals.length === 0) { originals.push({ "name": "Michael", "age": 21, "gender": "male" }); } else { for (i = 0; i < originals.length; i++) { if (originals[i].name !== "Michael") { originals.push({ "name": "Michael", "age": 21, "gender": "male" }); } if (originals[i].name == "Michael" && originals[i].age == 21) { originals[i].age = 22; } } console.log(originals); } ``` Many thanks for your help in advance.
2021/03/19
['https://Stackoverflow.com/questions/66714870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1647297/']
Use the `find()` method to look for an element with the name you want. If it's found, update it, otherwise add the new element. There's no need to check the length of the array. If the array is empty, `find()` won't find it. ``` let mike = originals.find(({name}) => name == 'Michael'); if (mike) { if (mike.age == 21) { mike.age = 22; } } else { originals.push({ "name": "Michael", "age": 21, "gender": "male" }); } ``` This solution assumes names are unique. If there can be multiple `Michael` entries, you can use `filter()` instead of `find()` to return all of them.
The simple solution is below with help of amazing supporters on StackOverflow. Thank you all ```js const originals = [{ "name": "Michael", "age": 21, "gender": "male" }]; if (!originals || originals.length === 0) { originals.push({ "name": "Michael", "age": 21, "gender": "male" }); } else { for (i = 0; i < originals.length; i++) { if (originals[i].name !== "Michaels") { originals.push({ "name": "Michaels", "age": 22, "gender": "male" }); } if (originals[i].name == "Michael" && originals[i].age == 21) { originals[i].age = 24; } } } console.log(originals); ```
66,714,870
I'm really struggling with my code and cannot find a way to make it work. I need to check whether my array exists or its length is not 0 and then if there is an object with a specific value in it. If so then update it. If not then add it. Please see my code below: ``` const originals = []; if (!originals || originals.length === 0) { originals.push({ "name": "Michael", "age": 21, "gender": "male" }); } else { for (i = 0; i < originals.length; i++) { if (originals[i].name !== "Michael") { originals.push({ "name": "Michael", "age": 21, "gender": "male" }); } if (originals[i].name == "Michael" && originals[i].age == 21) { originals[i].age = 22; } } console.log(originals); } ``` Many thanks for your help in advance.
2021/03/19
['https://Stackoverflow.com/questions/66714870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1647297/']
Use the `find()` method to look for an element with the name you want. If it's found, update it, otherwise add the new element. There's no need to check the length of the array. If the array is empty, `find()` won't find it. ``` let mike = originals.find(({name}) => name == 'Michael'); if (mike) { if (mike.age == 21) { mike.age = 22; } } else { originals.push({ "name": "Michael", "age": 21, "gender": "male" }); } ``` This solution assumes names are unique. If there can be multiple `Michael` entries, you can use `filter()` instead of `find()` to return all of them.
Reading between the lines what I think you want to do is: * If "Michael" is in the array. Then his age should be updated to 21, if he is 22 years old. * If "Michael" is not in the array. Then add Michael with an age of 21. There are some odd things in your code which makes no sense to me. For example you are checking for "Michael" in the array each time when iterating the array. This would mean that you insert a "Michael" for each entry that is not named "Michael". That doesn't make sense, does it? I think this is what you want: ```js function addOrUpdateMichael(array) { const michael = array.find((x) => x.name == "Michael"); if (!michael) { array.push({ "name": "Michael", "age": 21, "gender": "male" }); } else if (michael.age == 22) { michael.age = 21; } return array; } const testArray1 = []; console.log(addOrUpdateMichael(testArray1)); const testArray2 = [{ "name": "Michael", "age": 21, "gender": "male" }, { "name": "Tony", "age": 18, "gender": "male" }]; console.log(addOrUpdateMichael(testArray2)); const testArray3 = [{ "name": "Michael", "age": 22, "gender": "male" }, { "name": "Bob", "age": 36, "gender": "male" }]; console.log(addOrUpdateMichael(testArray3)); ```
66,714,870
I'm really struggling with my code and cannot find a way to make it work. I need to check whether my array exists or its length is not 0 and then if there is an object with a specific value in it. If so then update it. If not then add it. Please see my code below: ``` const originals = []; if (!originals || originals.length === 0) { originals.push({ "name": "Michael", "age": 21, "gender": "male" }); } else { for (i = 0; i < originals.length; i++) { if (originals[i].name !== "Michael") { originals.push({ "name": "Michael", "age": 21, "gender": "male" }); } if (originals[i].name == "Michael" && originals[i].age == 21) { originals[i].age = 22; } } console.log(originals); } ``` Many thanks for your help in advance.
2021/03/19
['https://Stackoverflow.com/questions/66714870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1647297/']
Use the `find()` method to look for an element with the name you want. If it's found, update it, otherwise add the new element. There's no need to check the length of the array. If the array is empty, `find()` won't find it. ``` let mike = originals.find(({name}) => name == 'Michael'); if (mike) { if (mike.age == 21) { mike.age = 22; } } else { originals.push({ "name": "Michael", "age": 21, "gender": "male" }); } ``` This solution assumes names are unique. If there can be multiple `Michael` entries, you can use `filter()` instead of `find()` to return all of them.
Here is my quick solution to this issue: From my perspective its a good idea to address a new array to contain temporary data. The easiest way to describe what I mean follows in the code snippet. Code Snippet (For-Loop) ----------------------- ``` var originalsStack=[]; function PushToOriginalStack() { for (i=0; i < originals.length; i++) { if (originals[i].name != "Samantha") { originalsStack.push({ "name": "Michael", "age": 21, "gender": "male" }); } else if (originals[i].name == "Samantha" && originals[i].age == 20) { originals[i].age = 21; originalsStack.push(originals[i]); } console.log(i); } originals = originalsStack; } PushToOriginalStack(); console.log(originals); ``` Important keep your Data handy, so you can handle the originals array. Hope I could help a bit! Cheers!
66,714,870
I'm really struggling with my code and cannot find a way to make it work. I need to check whether my array exists or its length is not 0 and then if there is an object with a specific value in it. If so then update it. If not then add it. Please see my code below: ``` const originals = []; if (!originals || originals.length === 0) { originals.push({ "name": "Michael", "age": 21, "gender": "male" }); } else { for (i = 0; i < originals.length; i++) { if (originals[i].name !== "Michael") { originals.push({ "name": "Michael", "age": 21, "gender": "male" }); } if (originals[i].name == "Michael" && originals[i].age == 21) { originals[i].age = 22; } } console.log(originals); } ``` Many thanks for your help in advance.
2021/03/19
['https://Stackoverflow.com/questions/66714870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1647297/']
Reading between the lines what I think you want to do is: * If "Michael" is in the array. Then his age should be updated to 21, if he is 22 years old. * If "Michael" is not in the array. Then add Michael with an age of 21. There are some odd things in your code which makes no sense to me. For example you are checking for "Michael" in the array each time when iterating the array. This would mean that you insert a "Michael" for each entry that is not named "Michael". That doesn't make sense, does it? I think this is what you want: ```js function addOrUpdateMichael(array) { const michael = array.find((x) => x.name == "Michael"); if (!michael) { array.push({ "name": "Michael", "age": 21, "gender": "male" }); } else if (michael.age == 22) { michael.age = 21; } return array; } const testArray1 = []; console.log(addOrUpdateMichael(testArray1)); const testArray2 = [{ "name": "Michael", "age": 21, "gender": "male" }, { "name": "Tony", "age": 18, "gender": "male" }]; console.log(addOrUpdateMichael(testArray2)); const testArray3 = [{ "name": "Michael", "age": 22, "gender": "male" }, { "name": "Bob", "age": 36, "gender": "male" }]; console.log(addOrUpdateMichael(testArray3)); ```
The simple solution is below with help of amazing supporters on StackOverflow. Thank you all ```js const originals = [{ "name": "Michael", "age": 21, "gender": "male" }]; if (!originals || originals.length === 0) { originals.push({ "name": "Michael", "age": 21, "gender": "male" }); } else { for (i = 0; i < originals.length; i++) { if (originals[i].name !== "Michaels") { originals.push({ "name": "Michaels", "age": 22, "gender": "male" }); } if (originals[i].name == "Michael" && originals[i].age == 21) { originals[i].age = 24; } } } console.log(originals); ```
66,714,870
I'm really struggling with my code and cannot find a way to make it work. I need to check whether my array exists or its length is not 0 and then if there is an object with a specific value in it. If so then update it. If not then add it. Please see my code below: ``` const originals = []; if (!originals || originals.length === 0) { originals.push({ "name": "Michael", "age": 21, "gender": "male" }); } else { for (i = 0; i < originals.length; i++) { if (originals[i].name !== "Michael") { originals.push({ "name": "Michael", "age": 21, "gender": "male" }); } if (originals[i].name == "Michael" && originals[i].age == 21) { originals[i].age = 22; } } console.log(originals); } ``` Many thanks for your help in advance.
2021/03/19
['https://Stackoverflow.com/questions/66714870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1647297/']
Here is my quick solution to this issue: From my perspective its a good idea to address a new array to contain temporary data. The easiest way to describe what I mean follows in the code snippet. Code Snippet (For-Loop) ----------------------- ``` var originalsStack=[]; function PushToOriginalStack() { for (i=0; i < originals.length; i++) { if (originals[i].name != "Samantha") { originalsStack.push({ "name": "Michael", "age": 21, "gender": "male" }); } else if (originals[i].name == "Samantha" && originals[i].age == 20) { originals[i].age = 21; originalsStack.push(originals[i]); } console.log(i); } originals = originalsStack; } PushToOriginalStack(); console.log(originals); ``` Important keep your Data handy, so you can handle the originals array. Hope I could help a bit! Cheers!
The simple solution is below with help of amazing supporters on StackOverflow. Thank you all ```js const originals = [{ "name": "Michael", "age": 21, "gender": "male" }]; if (!originals || originals.length === 0) { originals.push({ "name": "Michael", "age": 21, "gender": "male" }); } else { for (i = 0; i < originals.length; i++) { if (originals[i].name !== "Michaels") { originals.push({ "name": "Michaels", "age": 22, "gender": "male" }); } if (originals[i].name == "Michael" && originals[i].age == 21) { originals[i].age = 24; } } } console.log(originals); ```
66,714,870
I'm really struggling with my code and cannot find a way to make it work. I need to check whether my array exists or its length is not 0 and then if there is an object with a specific value in it. If so then update it. If not then add it. Please see my code below: ``` const originals = []; if (!originals || originals.length === 0) { originals.push({ "name": "Michael", "age": 21, "gender": "male" }); } else { for (i = 0; i < originals.length; i++) { if (originals[i].name !== "Michael") { originals.push({ "name": "Michael", "age": 21, "gender": "male" }); } if (originals[i].name == "Michael" && originals[i].age == 21) { originals[i].age = 22; } } console.log(originals); } ``` Many thanks for your help in advance.
2021/03/19
['https://Stackoverflow.com/questions/66714870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1647297/']
Reading between the lines what I think you want to do is: * If "Michael" is in the array. Then his age should be updated to 21, if he is 22 years old. * If "Michael" is not in the array. Then add Michael with an age of 21. There are some odd things in your code which makes no sense to me. For example you are checking for "Michael" in the array each time when iterating the array. This would mean that you insert a "Michael" for each entry that is not named "Michael". That doesn't make sense, does it? I think this is what you want: ```js function addOrUpdateMichael(array) { const michael = array.find((x) => x.name == "Michael"); if (!michael) { array.push({ "name": "Michael", "age": 21, "gender": "male" }); } else if (michael.age == 22) { michael.age = 21; } return array; } const testArray1 = []; console.log(addOrUpdateMichael(testArray1)); const testArray2 = [{ "name": "Michael", "age": 21, "gender": "male" }, { "name": "Tony", "age": 18, "gender": "male" }]; console.log(addOrUpdateMichael(testArray2)); const testArray3 = [{ "name": "Michael", "age": 22, "gender": "male" }, { "name": "Bob", "age": 36, "gender": "male" }]; console.log(addOrUpdateMichael(testArray3)); ```
Here is my quick solution to this issue: From my perspective its a good idea to address a new array to contain temporary data. The easiest way to describe what I mean follows in the code snippet. Code Snippet (For-Loop) ----------------------- ``` var originalsStack=[]; function PushToOriginalStack() { for (i=0; i < originals.length; i++) { if (originals[i].name != "Samantha") { originalsStack.push({ "name": "Michael", "age": 21, "gender": "male" }); } else if (originals[i].name == "Samantha" && originals[i].age == 20) { originals[i].age = 21; originalsStack.push(originals[i]); } console.log(i); } originals = originalsStack; } PushToOriginalStack(); console.log(originals); ``` Important keep your Data handy, so you can handle the originals array. Hope I could help a bit! Cheers!
45,374,668
I am acquiring data from a microcontroller via UDP. Each packet is a hex string, and I need to split it into equal-sized chunks to do some processing afterwards. However, since the packets are relatively large (about 700 chars each), the time it takes to split one into chunks is larger than the time between packet arrival. This introduces latency and half of the data is lost. I cannot use TCP/IP, because the system needs to operate in real time. How can I multiprocess the following line (can it even be done): ``` list_of_chunks = [packet[i:i+n] for i in range(0, len(packet), 16)] ```
2017/07/28
['https://Stackoverflow.com/questions/45374668', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8382085/']
You can check whether the callable is convertible to `std::function<T(T)>`: ``` template<class T, class F> std::enable_if_t<std::is_convertible<F, std::function<T(T)>>::value, T> f(T v, F fn) { return fn(v); } ```
Make deducible blocks the compiler from trying tomdeduce that argument. Which seems like a poor choice of name; that is usually called `block_deduction` or something. The easiest way to include the signature is a comment: ``` template <class T, class F /*T(T) signature*/> T f(T val, F fc) { return fc(val); } ``` wherever you want it. If we want compiler enforcing, we can block deduction and type erase like you did in your question. Another choice: ``` template<class Sig, class F, class=void> struct can_call:std::false_type{}; template<class R, class...Args, class F> struct can_call<R(Args...),F,std::enable_if_t< std::is_convertible<std::result_of_t<F(Args...)>,R>{} >>:std::true_type{}; template<class...Args, class F> struct can_call<void(Args...),F,std::void_t< std::result_of_t<F(Args...)>,R>{} >>:std::true_type{}; ``` that defines `can_call<Sig, F>` which is true if and only if you can call F in a context compatible with `Sig`. ``` template <class T, class F /*T(T) signature*/> std::enable_if_t<can_call<T(T),F&>{}, T> T f(T val, F fc) { return fc(val); } ``` and now `F` is checked at overload resolution time to ensure it is compatible. I used some C++14 and C++17 `std::void_t`. `void_t` is easy to write in C++11, and easy to find on SO. There may be typos; on phone.
48,375,282
Given a `Flux` or a `Mono` from project reactor is a there a way to get the Flux or Mono to print out what the operator chain looks like. For example given the code below. ``` Fulx flux = Flux.just("a","b","c") .map( v -> v.toUpperCase()) .log(); ``` Is there some way to get the flux to print out a list of all the operators that are chained inside in the processing pipeline? Some nice ascii formatted text or a marble diagram? printTheFlux(flux) should make a nice printout that show the structure of all the operators from the example above. I am not expecting to produce the code in the lambda's just a way to see what operators are chained together.
2018/01/22
['https://Stackoverflow.com/questions/48375282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/438319/']
There is partial building blocks for doing this with the `Scannable` interface: ``` public String textRepresentation(Flux<?> flux) { Scannable sc = Scannable.from(flux); //scan the last operator in the chain and ask if it knows its parents List<String> names = sc.parents().map(Scannable::operatorName) .collect(Collectors.toList()); //as it traverses the chain from bottom to top, we need to reverse the order Collections.reverse(names); //need to also add the last operator names.add(sc.operatorName()); return names.toString(); } @Test public void textRepresentationTest() { Flux flux = Flux.just("a","b","c") .map( v -> v.toUpperCase()) .log(); System.out.println(textRepresentation(flux)); } ``` Prints ``` [map, log] ``` Not all operators fully support it though (as you can see, the `just` source doesn't for instance).
Nice suggestion! However, waiting for it, we can just have something like : ``` Disposable flux = Flux.just("a", "b", "c") .map(String::toUpperCase) .doOnNext(FluxUtil::print) .subscribe(); ``` Where `FluxUtil::print` is just a static method that you can write with different ways. Here is the complete code works for me: ``` public class FluxUtil { private static String s = ""; public static void main(String[] args) { Disposable flux = Flux.just("a", "b", "c") .map(String::toUpperCase) .doOnNext(FluxUtil::print) .subscribe(); } private static Object print(Object o) { s = !s.isEmpty() ? s.concat("->") : s; s = s.concat(o.toString()); System.out.println(s); return o; } } ```
34,831,973
I have a josn file I'm working with that contains multiple json objects in a single file. R is unable to read the file as a whole. But since each object occurs at regular intervals, I would like to iteratively read a fixed number of lines into R. There are a number of SO questions on reading single lines into R but I have been unable to extend these solutions to a fixed number of lines. For my problem I need to read 16 lines into R at a time (eg 1-16, 17-32 etc) I have tried using a loop but can't seem to get the syntax right: ``` ## File file <- "results.json" ## Create connection con <- file(description=file, open="r") ## Loop over a file connection for(i in 1:1000) { tmp <- scan(file=con, nlines=16, quiet=TRUE) data[i] <- fromJSON(tmp) } ``` The file contains over 1000 objects of this form: ``` { "object": [ [ "a", 0 ], [ "b", 2 ], [ "c", 2 ] ] } ```
2016/01/16
['https://Stackoverflow.com/questions/34831973', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4530884/']
Why not just use a case statement? ``` CASE WHEN r.Id IS NULL THEN 0 ELSE 1 END ``` Change the 0 and 1 to whatever you want for false and true.
You should clarify what SQL language you are actually using, but an answer can be provided anyway: ``` CREATE PROCEDURE [dbo].[TournamentsWithLoggedUser] @user nvarchar(128) AS BEGIN SELECT t.Id, t.Info, -- this works in SQL Server CAST ((CASE WHEN r.UserId IS NOT NULL THEN 1 ELSE 0 END) AS BIT) AS IsRegistered FROM Tournaments as t LEFT JOIN Registrations as r ON t.Id = r.TournamentId where r.UserId IS NULL OR r.UserId = @user -- this should not be required RETURN ``` END However, there is a problem with the logic: `@user` is not nullable, so your procedure gives the impression that it looks data for a single user. However, your OR operator allows to select all records from unregistered users united with the record for the particular provided user (if exists).
34,831,973
I have a josn file I'm working with that contains multiple json objects in a single file. R is unable to read the file as a whole. But since each object occurs at regular intervals, I would like to iteratively read a fixed number of lines into R. There are a number of SO questions on reading single lines into R but I have been unable to extend these solutions to a fixed number of lines. For my problem I need to read 16 lines into R at a time (eg 1-16, 17-32 etc) I have tried using a loop but can't seem to get the syntax right: ``` ## File file <- "results.json" ## Create connection con <- file(description=file, open="r") ## Loop over a file connection for(i in 1:1000) { tmp <- scan(file=con, nlines=16, quiet=TRUE) data[i] <- fromJSON(tmp) } ``` The file contains over 1000 objects of this form: ``` { "object": [ [ "a", 0 ], [ "b", 2 ], [ "c", 2 ] ] } ```
2016/01/16
['https://Stackoverflow.com/questions/34831973', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4530884/']
You are looking for this query ``` SELECT t.id, t.info, Cast (CASE WHEN r.userid IS NOT NULL THEN 1 ELSE 0 END AS BIT) AS IsRegistered FROM tournaments AS t LEFT JOIN registrations AS r ON t.id = r.tournamentid AND r.userid = @user ```
You should clarify what SQL language you are actually using, but an answer can be provided anyway: ``` CREATE PROCEDURE [dbo].[TournamentsWithLoggedUser] @user nvarchar(128) AS BEGIN SELECT t.Id, t.Info, -- this works in SQL Server CAST ((CASE WHEN r.UserId IS NOT NULL THEN 1 ELSE 0 END) AS BIT) AS IsRegistered FROM Tournaments as t LEFT JOIN Registrations as r ON t.Id = r.TournamentId where r.UserId IS NULL OR r.UserId = @user -- this should not be required RETURN ``` END However, there is a problem with the logic: `@user` is not nullable, so your procedure gives the impression that it looks data for a single user. However, your OR operator allows to select all records from unregistered users united with the record for the particular provided user (if exists).
34,831,973
I have a josn file I'm working with that contains multiple json objects in a single file. R is unable to read the file as a whole. But since each object occurs at regular intervals, I would like to iteratively read a fixed number of lines into R. There are a number of SO questions on reading single lines into R but I have been unable to extend these solutions to a fixed number of lines. For my problem I need to read 16 lines into R at a time (eg 1-16, 17-32 etc) I have tried using a loop but can't seem to get the syntax right: ``` ## File file <- "results.json" ## Create connection con <- file(description=file, open="r") ## Loop over a file connection for(i in 1:1000) { tmp <- scan(file=con, nlines=16, quiet=TRUE) data[i] <- fromJSON(tmp) } ``` The file contains over 1000 objects of this form: ``` { "object": [ [ "a", 0 ], [ "b", 2 ], [ "c", 2 ] ] } ```
2016/01/16
['https://Stackoverflow.com/questions/34831973', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4530884/']
``` SELECT t.Id, t.Info, -- this works in SQL Server CAST ((CASE WHEN r.UserId IS NOT NULL THEN 1 ELSE 0 END) AS BIT) AS IsRegistered FROM Tournaments as t LEFT JOIN Registrations as r ON t.Id = r.TournamentId where (r.UserId = '' OR r.UserId = @user) ``` -- i think this one is help for you...
You should clarify what SQL language you are actually using, but an answer can be provided anyway: ``` CREATE PROCEDURE [dbo].[TournamentsWithLoggedUser] @user nvarchar(128) AS BEGIN SELECT t.Id, t.Info, -- this works in SQL Server CAST ((CASE WHEN r.UserId IS NOT NULL THEN 1 ELSE 0 END) AS BIT) AS IsRegistered FROM Tournaments as t LEFT JOIN Registrations as r ON t.Id = r.TournamentId where r.UserId IS NULL OR r.UserId = @user -- this should not be required RETURN ``` END However, there is a problem with the logic: `@user` is not nullable, so your procedure gives the impression that it looks data for a single user. However, your OR operator allows to select all records from unregistered users united with the record for the particular provided user (if exists).
39,191,276
I was trying to create a shortest-possible code for a puzzle, and the question came to mind trying to do something like this: `zip(l=[1,2,3,4,5],l[1:])` So I was wondering, is there a way to produce a value, assign it to a variable and use that variable on the very same line/function call? EDIT:To clarify things, I am aware that this thing is not recommended nor good nor does it yield faster results. Also, the essence of the question is assignment and reusing of the same variable in the same function call. The list is produced using input, the static list here is for the example only. In a situation like this, I would like to avoid repeating the same task twice while I have already produced the result somewhere.
2016/08/28
['https://Stackoverflow.com/questions/39191276', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1774080/']
Here is one hack, but not pythonic. Actually since all you need is creating an object in global namespace you can simply update the namespace by your intended object. ``` >>> zip(globals().update(a=[1, 2, 3]) or a, a[1:]) [(1, 2), (2, 3)] ``` Since the `update()` attribute returns None, its logical `or` with the object would be the object itself.
If this is a code golf thing so it **must** be a single statement, then this works in Python 2: ``` print[zip(l,l[1:])for l in[[1,2,3,4,5]]][0] ``` **output** ``` [(1, 2), (2, 3), (3, 4), (4, 5)] ``` Otherwise, ``` l=[1,2,3,4,5];print zip(l,l[1:]) ``` is shorter, and **far** more sensible than the list comprehension abuse shown above. Many languages in the C family permit assignment to variables inside expressions. This can be convenient but it has also led to numerous bugs, and most modern compilers will generate warnings if an assignment is detected inside an `if` condition (for example). It was an intentional design decision to not allow that sort of thing in Python. Thus a Python assignment statement is *not* an expression, and so it doesn't have a value. BTW, the Python data model is quite different to that of many other languages. [Python doesn't really have variables](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables) that are containers for values, it has objects that may be bound to names. --- Note that in Python 3 `zip` returns an iterator, not a list, so if you want to produce a list you'd need to wrap the `zip` call with `list()`.
39,191,276
I was trying to create a shortest-possible code for a puzzle, and the question came to mind trying to do something like this: `zip(l=[1,2,3,4,5],l[1:])` So I was wondering, is there a way to produce a value, assign it to a variable and use that variable on the very same line/function call? EDIT:To clarify things, I am aware that this thing is not recommended nor good nor does it yield faster results. Also, the essence of the question is assignment and reusing of the same variable in the same function call. The list is produced using input, the static list here is for the example only. In a situation like this, I would like to avoid repeating the same task twice while I have already produced the result somewhere.
2016/08/28
['https://Stackoverflow.com/questions/39191276', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1774080/']
Here is one hack, but not pythonic. Actually since all you need is creating an object in global namespace you can simply update the namespace by your intended object. ``` >>> zip(globals().update(a=[1, 2, 3]) or a, a[1:]) [(1, 2), (2, 3)] ``` Since the `update()` attribute returns None, its logical `or` with the object would be the object itself.
You can use lambdas and default arguments to code golf this. Stressing that this shouldn't be used in production code, but just demonstrating what is possible in python. ``` (lambda l=[1, 2, 3]: zip(l, l[1:]))() ```
39,191,276
I was trying to create a shortest-possible code for a puzzle, and the question came to mind trying to do something like this: `zip(l=[1,2,3,4,5],l[1:])` So I was wondering, is there a way to produce a value, assign it to a variable and use that variable on the very same line/function call? EDIT:To clarify things, I am aware that this thing is not recommended nor good nor does it yield faster results. Also, the essence of the question is assignment and reusing of the same variable in the same function call. The list is produced using input, the static list here is for the example only. In a situation like this, I would like to avoid repeating the same task twice while I have already produced the result somewhere.
2016/08/28
['https://Stackoverflow.com/questions/39191276', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1774080/']
Here is one hack, but not pythonic. Actually since all you need is creating an object in global namespace you can simply update the namespace by your intended object. ``` >>> zip(globals().update(a=[1, 2, 3]) or a, a[1:]) [(1, 2), (2, 3)] ``` Since the `update()` attribute returns None, its logical `or` with the object would be the object itself.
Of course, you can always do this: ``` l = range(1, 6); zip(l, l[1:]) ``` but I guess that's not what you wanted. :-) There is a relatively clean way ``` (lambda l: zip(l, l[1:]))(range(1, 6)) ``` BTW that function is defined in [itertools recipes](https://docs.python.org/3.6/library/itertools.html#itertools-recipes) as pairwise, so `pairwise(range(1, 6))` is probably the most direct way. You only need to write an import hook that imports Python functions from web pages. :-D And there is a nice convoluted way ``` next(zip(l, l[1:]) for l in [range(1, 6)]) ``` If you want more ideas, just say so. :-)
39,191,276
I was trying to create a shortest-possible code for a puzzle, and the question came to mind trying to do something like this: `zip(l=[1,2,3,4,5],l[1:])` So I was wondering, is there a way to produce a value, assign it to a variable and use that variable on the very same line/function call? EDIT:To clarify things, I am aware that this thing is not recommended nor good nor does it yield faster results. Also, the essence of the question is assignment and reusing of the same variable in the same function call. The list is produced using input, the static list here is for the example only. In a situation like this, I would like to avoid repeating the same task twice while I have already produced the result somewhere.
2016/08/28
['https://Stackoverflow.com/questions/39191276', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1774080/']
If this is a code golf thing so it **must** be a single statement, then this works in Python 2: ``` print[zip(l,l[1:])for l in[[1,2,3,4,5]]][0] ``` **output** ``` [(1, 2), (2, 3), (3, 4), (4, 5)] ``` Otherwise, ``` l=[1,2,3,4,5];print zip(l,l[1:]) ``` is shorter, and **far** more sensible than the list comprehension abuse shown above. Many languages in the C family permit assignment to variables inside expressions. This can be convenient but it has also led to numerous bugs, and most modern compilers will generate warnings if an assignment is detected inside an `if` condition (for example). It was an intentional design decision to not allow that sort of thing in Python. Thus a Python assignment statement is *not* an expression, and so it doesn't have a value. BTW, the Python data model is quite different to that of many other languages. [Python doesn't really have variables](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables) that are containers for values, it has objects that may be bound to names. --- Note that in Python 3 `zip` returns an iterator, not a list, so if you want to produce a list you'd need to wrap the `zip` call with `list()`.
Of course, you can always do this: ``` l = range(1, 6); zip(l, l[1:]) ``` but I guess that's not what you wanted. :-) There is a relatively clean way ``` (lambda l: zip(l, l[1:]))(range(1, 6)) ``` BTW that function is defined in [itertools recipes](https://docs.python.org/3.6/library/itertools.html#itertools-recipes) as pairwise, so `pairwise(range(1, 6))` is probably the most direct way. You only need to write an import hook that imports Python functions from web pages. :-D And there is a nice convoluted way ``` next(zip(l, l[1:]) for l in [range(1, 6)]) ``` If you want more ideas, just say so. :-)
39,191,276
I was trying to create a shortest-possible code for a puzzle, and the question came to mind trying to do something like this: `zip(l=[1,2,3,4,5],l[1:])` So I was wondering, is there a way to produce a value, assign it to a variable and use that variable on the very same line/function call? EDIT:To clarify things, I am aware that this thing is not recommended nor good nor does it yield faster results. Also, the essence of the question is assignment and reusing of the same variable in the same function call. The list is produced using input, the static list here is for the example only. In a situation like this, I would like to avoid repeating the same task twice while I have already produced the result somewhere.
2016/08/28
['https://Stackoverflow.com/questions/39191276', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1774080/']
You can use lambdas and default arguments to code golf this. Stressing that this shouldn't be used in production code, but just demonstrating what is possible in python. ``` (lambda l=[1, 2, 3]: zip(l, l[1:]))() ```
Of course, you can always do this: ``` l = range(1, 6); zip(l, l[1:]) ``` but I guess that's not what you wanted. :-) There is a relatively clean way ``` (lambda l: zip(l, l[1:]))(range(1, 6)) ``` BTW that function is defined in [itertools recipes](https://docs.python.org/3.6/library/itertools.html#itertools-recipes) as pairwise, so `pairwise(range(1, 6))` is probably the most direct way. You only need to write an import hook that imports Python functions from web pages. :-D And there is a nice convoluted way ``` next(zip(l, l[1:]) for l in [range(1, 6)]) ``` If you want more ideas, just say so. :-)
78,863
I work in Company A and I'm kind of the star there (I feel it is mainly due to political reasons). Recently, I received an offer from Company B and I decided to accept it. HR department in my current company pushed me to review my decision and propose conditions under which I would like to stay at company. I feel that offer from Company B is much better for my career (project is more interesting, company is also a better suit for me), but I don't want to burn bridges. How can I respond?
2016/11/01
['https://workplace.stackexchange.com/questions/78863', 'https://workplace.stackexchange.com', 'https://workplace.stackexchange.com/users/-1/']
First of all, you don't have to tell Company A anything except the last date you'll be working for them. However, you *could* say something to the effect of > > I see this as a personal growth opportunity and a chance to experience different corporate cultures and different ways of doing things. I've thoroughly enjoyed my time at Company A (*don't say this if it isn't true!*), and may consider working here again some time. > > > The idea is to spin this as "some years from now I'll be more valuable to you if I have this experience than if I stay here" - kind of like taking a really long sabbatical. Just don't be specific
You just have to spin up a bunch of nonsense that you probably don't mean. Something like, "While I am grateful for the opportunities that were presented to me during my time here - I feel that at this juncture its best for all parties if I move on" Then say something about how you will do all you can to transfer knowledge and help in the transition prior to your departure Then in your exit interview you say a bunch of nice things and leave.
78,863
I work in Company A and I'm kind of the star there (I feel it is mainly due to political reasons). Recently, I received an offer from Company B and I decided to accept it. HR department in my current company pushed me to review my decision and propose conditions under which I would like to stay at company. I feel that offer from Company B is much better for my career (project is more interesting, company is also a better suit for me), but I don't want to burn bridges. How can I respond?
2016/11/01
['https://workplace.stackexchange.com/questions/78863', 'https://workplace.stackexchange.com', 'https://workplace.stackexchange.com/users/-1/']
> > I decided to accept it. > > > If you've already made your decision and accepted the other offer, it's OK to say that. > > I have already accepted the offer from Company B and thus cannot consider any counter offer. My last day will be XX/XX/XXXX. > > > The expectation is that once a job offer is accepted (in writing), that that's it. You wouldn't accept an offer and keep interviewing or keep negotiating the terms so it shouldn't offend your current employer that you aren't going back on your word to Company B. It isn't burning a bridge to be honest here.
You just have to spin up a bunch of nonsense that you probably don't mean. Something like, "While I am grateful for the opportunities that were presented to me during my time here - I feel that at this juncture its best for all parties if I move on" Then say something about how you will do all you can to transfer knowledge and help in the transition prior to your departure Then in your exit interview you say a bunch of nice things and leave.
78,863
I work in Company A and I'm kind of the star there (I feel it is mainly due to political reasons). Recently, I received an offer from Company B and I decided to accept it. HR department in my current company pushed me to review my decision and propose conditions under which I would like to stay at company. I feel that offer from Company B is much better for my career (project is more interesting, company is also a better suit for me), but I don't want to burn bridges. How can I respond?
2016/11/01
['https://workplace.stackexchange.com/questions/78863', 'https://workplace.stackexchange.com', 'https://workplace.stackexchange.com/users/-1/']
If you're leaving your current employer, there's obviously some reason. In any situation, your best bet is going to be to outline those reasons and state that those are what are motivating you towards accepting the new position. The key here is you need to be specific, rather than giving vague reasons like 'the new opportunity will be better for my career'. If you can give them a concise set of points, and the company knows they can't offer you the same thing, a good company will wish you luck and let you know to keep them in mind if the new position turns out to not be everything you thought it was. If you give them a vague statement about career opportunity, the company will come back with a title change and/or salary increase and continue to pressure you about staying. If the reason you're leaving is for more interesting projects and career advancement, you have to tell them that. Tell them where you envision yourself in 5 years, and highlight how the new position will help you get there. If they come back with a salary increase as their counter-offer, you can tell them that you appreciate their salary offer, but it doesn't address why you're interested in the new opportunity. If the reason you're leaving is for salary, make sure to point out not only the better salary but also how you got to the point of not getting paid as much as you'd like to. I have plenty of friends who have received job offers for extra money, and received 'competitive' counter-offers from their employer. After accepting however, when raises and bonuses come around they get told 'well we already gave you such a generous pay increase to stay with us, so we aren't giving you a raise this year' or 'your bonus is lower this year because after your raise it's not in our budget to give you a large bonus this year'. So if the company comes back with a big pay increase to try to get you to stay, you have to point out to them that you're leaving because you're unhappy with the promotion/raise/bonus structure at the company, not your current salary rate. Basically, whatever you tell them, make sure its honest. If you don't like your projects and company politics, and you tell them that you love the company but you're leaving for a higher salary, don't be surprised if the company comes back with more money. Then, when you turn down the counter offer, they'll have sentiments along the lines of "Well what the heck man?? Do you know how many hoops we had to jump through to get you this offer? We thought you really wanted to stay with us. You told us you would stay if we matched your offer and now you're not going to?". If you're genuine and honest with your employer about why you're leaving, a good employer will understand.
You just have to spin up a bunch of nonsense that you probably don't mean. Something like, "While I am grateful for the opportunities that were presented to me during my time here - I feel that at this juncture its best for all parties if I move on" Then say something about how you will do all you can to transfer knowledge and help in the transition prior to your departure Then in your exit interview you say a bunch of nice things and leave.
78,863
I work in Company A and I'm kind of the star there (I feel it is mainly due to political reasons). Recently, I received an offer from Company B and I decided to accept it. HR department in my current company pushed me to review my decision and propose conditions under which I would like to stay at company. I feel that offer from Company B is much better for my career (project is more interesting, company is also a better suit for me), but I don't want to burn bridges. How can I respond?
2016/11/01
['https://workplace.stackexchange.com/questions/78863', 'https://workplace.stackexchange.com', 'https://workplace.stackexchange.com/users/-1/']
First of all, you don't have to tell Company A anything except the last date you'll be working for them. However, you *could* say something to the effect of > > I see this as a personal growth opportunity and a chance to experience different corporate cultures and different ways of doing things. I've thoroughly enjoyed my time at Company A (*don't say this if it isn't true!*), and may consider working here again some time. > > > The idea is to spin this as "some years from now I'll be more valuable to you if I have this experience than if I stay here" - kind of like taking a really long sabbatical. Just don't be specific
The best thing here is to put it back on the company. > > I am not comfortable trying to define what sort of offer I would be > comfortable requesting. I would entertain an offer by the company if > it feels that I am under-compensated currently, or should be advanced to > higher position, and consider it appropriately. > > > This gets the onus of action off of you, and places it it back on the company. If they make you an offer great, you can consider it. But as you said you are looking at more than just compensation. At the same time there might be a number possible that the company could offer you that might make you reconsider. Either way it should solve your problem of not wanting to burn bridges.
78,863
I work in Company A and I'm kind of the star there (I feel it is mainly due to political reasons). Recently, I received an offer from Company B and I decided to accept it. HR department in my current company pushed me to review my decision and propose conditions under which I would like to stay at company. I feel that offer from Company B is much better for my career (project is more interesting, company is also a better suit for me), but I don't want to burn bridges. How can I respond?
2016/11/01
['https://workplace.stackexchange.com/questions/78863', 'https://workplace.stackexchange.com', 'https://workplace.stackexchange.com/users/-1/']
First of all, you don't have to tell Company A anything except the last date you'll be working for them. However, you *could* say something to the effect of > > I see this as a personal growth opportunity and a chance to experience different corporate cultures and different ways of doing things. I've thoroughly enjoyed my time at Company A (*don't say this if it isn't true!*), and may consider working here again some time. > > > The idea is to spin this as "some years from now I'll be more valuable to you if I have this experience than if I stay here" - kind of like taking a really long sabbatical. Just don't be specific
> > I decided to accept it. > > > If you've already made your decision and accepted the other offer, it's OK to say that. > > I have already accepted the offer from Company B and thus cannot consider any counter offer. My last day will be XX/XX/XXXX. > > > The expectation is that once a job offer is accepted (in writing), that that's it. You wouldn't accept an offer and keep interviewing or keep negotiating the terms so it shouldn't offend your current employer that you aren't going back on your word to Company B. It isn't burning a bridge to be honest here.
78,863
I work in Company A and I'm kind of the star there (I feel it is mainly due to political reasons). Recently, I received an offer from Company B and I decided to accept it. HR department in my current company pushed me to review my decision and propose conditions under which I would like to stay at company. I feel that offer from Company B is much better for my career (project is more interesting, company is also a better suit for me), but I don't want to burn bridges. How can I respond?
2016/11/01
['https://workplace.stackexchange.com/questions/78863', 'https://workplace.stackexchange.com', 'https://workplace.stackexchange.com/users/-1/']
First of all, you don't have to tell Company A anything except the last date you'll be working for them. However, you *could* say something to the effect of > > I see this as a personal growth opportunity and a chance to experience different corporate cultures and different ways of doing things. I've thoroughly enjoyed my time at Company A (*don't say this if it isn't true!*), and may consider working here again some time. > > > The idea is to spin this as "some years from now I'll be more valuable to you if I have this experience than if I stay here" - kind of like taking a really long sabbatical. Just don't be specific
If you're leaving your current employer, there's obviously some reason. In any situation, your best bet is going to be to outline those reasons and state that those are what are motivating you towards accepting the new position. The key here is you need to be specific, rather than giving vague reasons like 'the new opportunity will be better for my career'. If you can give them a concise set of points, and the company knows they can't offer you the same thing, a good company will wish you luck and let you know to keep them in mind if the new position turns out to not be everything you thought it was. If you give them a vague statement about career opportunity, the company will come back with a title change and/or salary increase and continue to pressure you about staying. If the reason you're leaving is for more interesting projects and career advancement, you have to tell them that. Tell them where you envision yourself in 5 years, and highlight how the new position will help you get there. If they come back with a salary increase as their counter-offer, you can tell them that you appreciate their salary offer, but it doesn't address why you're interested in the new opportunity. If the reason you're leaving is for salary, make sure to point out not only the better salary but also how you got to the point of not getting paid as much as you'd like to. I have plenty of friends who have received job offers for extra money, and received 'competitive' counter-offers from their employer. After accepting however, when raises and bonuses come around they get told 'well we already gave you such a generous pay increase to stay with us, so we aren't giving you a raise this year' or 'your bonus is lower this year because after your raise it's not in our budget to give you a large bonus this year'. So if the company comes back with a big pay increase to try to get you to stay, you have to point out to them that you're leaving because you're unhappy with the promotion/raise/bonus structure at the company, not your current salary rate. Basically, whatever you tell them, make sure its honest. If you don't like your projects and company politics, and you tell them that you love the company but you're leaving for a higher salary, don't be surprised if the company comes back with more money. Then, when you turn down the counter offer, they'll have sentiments along the lines of "Well what the heck man?? Do you know how many hoops we had to jump through to get you this offer? We thought you really wanted to stay with us. You told us you would stay if we matched your offer and now you're not going to?". If you're genuine and honest with your employer about why you're leaving, a good employer will understand.
78,863
I work in Company A and I'm kind of the star there (I feel it is mainly due to political reasons). Recently, I received an offer from Company B and I decided to accept it. HR department in my current company pushed me to review my decision and propose conditions under which I would like to stay at company. I feel that offer from Company B is much better for my career (project is more interesting, company is also a better suit for me), but I don't want to burn bridges. How can I respond?
2016/11/01
['https://workplace.stackexchange.com/questions/78863', 'https://workplace.stackexchange.com', 'https://workplace.stackexchange.com/users/-1/']
> > I decided to accept it. > > > If you've already made your decision and accepted the other offer, it's OK to say that. > > I have already accepted the offer from Company B and thus cannot consider any counter offer. My last day will be XX/XX/XXXX. > > > The expectation is that once a job offer is accepted (in writing), that that's it. You wouldn't accept an offer and keep interviewing or keep negotiating the terms so it shouldn't offend your current employer that you aren't going back on your word to Company B. It isn't burning a bridge to be honest here.
The best thing here is to put it back on the company. > > I am not comfortable trying to define what sort of offer I would be > comfortable requesting. I would entertain an offer by the company if > it feels that I am under-compensated currently, or should be advanced to > higher position, and consider it appropriately. > > > This gets the onus of action off of you, and places it it back on the company. If they make you an offer great, you can consider it. But as you said you are looking at more than just compensation. At the same time there might be a number possible that the company could offer you that might make you reconsider. Either way it should solve your problem of not wanting to burn bridges.
78,863
I work in Company A and I'm kind of the star there (I feel it is mainly due to political reasons). Recently, I received an offer from Company B and I decided to accept it. HR department in my current company pushed me to review my decision and propose conditions under which I would like to stay at company. I feel that offer from Company B is much better for my career (project is more interesting, company is also a better suit for me), but I don't want to burn bridges. How can I respond?
2016/11/01
['https://workplace.stackexchange.com/questions/78863', 'https://workplace.stackexchange.com', 'https://workplace.stackexchange.com/users/-1/']
If you're leaving your current employer, there's obviously some reason. In any situation, your best bet is going to be to outline those reasons and state that those are what are motivating you towards accepting the new position. The key here is you need to be specific, rather than giving vague reasons like 'the new opportunity will be better for my career'. If you can give them a concise set of points, and the company knows they can't offer you the same thing, a good company will wish you luck and let you know to keep them in mind if the new position turns out to not be everything you thought it was. If you give them a vague statement about career opportunity, the company will come back with a title change and/or salary increase and continue to pressure you about staying. If the reason you're leaving is for more interesting projects and career advancement, you have to tell them that. Tell them where you envision yourself in 5 years, and highlight how the new position will help you get there. If they come back with a salary increase as their counter-offer, you can tell them that you appreciate their salary offer, but it doesn't address why you're interested in the new opportunity. If the reason you're leaving is for salary, make sure to point out not only the better salary but also how you got to the point of not getting paid as much as you'd like to. I have plenty of friends who have received job offers for extra money, and received 'competitive' counter-offers from their employer. After accepting however, when raises and bonuses come around they get told 'well we already gave you such a generous pay increase to stay with us, so we aren't giving you a raise this year' or 'your bonus is lower this year because after your raise it's not in our budget to give you a large bonus this year'. So if the company comes back with a big pay increase to try to get you to stay, you have to point out to them that you're leaving because you're unhappy with the promotion/raise/bonus structure at the company, not your current salary rate. Basically, whatever you tell them, make sure its honest. If you don't like your projects and company politics, and you tell them that you love the company but you're leaving for a higher salary, don't be surprised if the company comes back with more money. Then, when you turn down the counter offer, they'll have sentiments along the lines of "Well what the heck man?? Do you know how many hoops we had to jump through to get you this offer? We thought you really wanted to stay with us. You told us you would stay if we matched your offer and now you're not going to?". If you're genuine and honest with your employer about why you're leaving, a good employer will understand.
The best thing here is to put it back on the company. > > I am not comfortable trying to define what sort of offer I would be > comfortable requesting. I would entertain an offer by the company if > it feels that I am under-compensated currently, or should be advanced to > higher position, and consider it appropriately. > > > This gets the onus of action off of you, and places it it back on the company. If they make you an offer great, you can consider it. But as you said you are looking at more than just compensation. At the same time there might be a number possible that the company could offer you that might make you reconsider. Either way it should solve your problem of not wanting to burn bridges.
78,863
I work in Company A and I'm kind of the star there (I feel it is mainly due to political reasons). Recently, I received an offer from Company B and I decided to accept it. HR department in my current company pushed me to review my decision and propose conditions under which I would like to stay at company. I feel that offer from Company B is much better for my career (project is more interesting, company is also a better suit for me), but I don't want to burn bridges. How can I respond?
2016/11/01
['https://workplace.stackexchange.com/questions/78863', 'https://workplace.stackexchange.com', 'https://workplace.stackexchange.com/users/-1/']
> > I decided to accept it. > > > If you've already made your decision and accepted the other offer, it's OK to say that. > > I have already accepted the offer from Company B and thus cannot consider any counter offer. My last day will be XX/XX/XXXX. > > > The expectation is that once a job offer is accepted (in writing), that that's it. You wouldn't accept an offer and keep interviewing or keep negotiating the terms so it shouldn't offend your current employer that you aren't going back on your word to Company B. It isn't burning a bridge to be honest here.
If you're leaving your current employer, there's obviously some reason. In any situation, your best bet is going to be to outline those reasons and state that those are what are motivating you towards accepting the new position. The key here is you need to be specific, rather than giving vague reasons like 'the new opportunity will be better for my career'. If you can give them a concise set of points, and the company knows they can't offer you the same thing, a good company will wish you luck and let you know to keep them in mind if the new position turns out to not be everything you thought it was. If you give them a vague statement about career opportunity, the company will come back with a title change and/or salary increase and continue to pressure you about staying. If the reason you're leaving is for more interesting projects and career advancement, you have to tell them that. Tell them where you envision yourself in 5 years, and highlight how the new position will help you get there. If they come back with a salary increase as their counter-offer, you can tell them that you appreciate their salary offer, but it doesn't address why you're interested in the new opportunity. If the reason you're leaving is for salary, make sure to point out not only the better salary but also how you got to the point of not getting paid as much as you'd like to. I have plenty of friends who have received job offers for extra money, and received 'competitive' counter-offers from their employer. After accepting however, when raises and bonuses come around they get told 'well we already gave you such a generous pay increase to stay with us, so we aren't giving you a raise this year' or 'your bonus is lower this year because after your raise it's not in our budget to give you a large bonus this year'. So if the company comes back with a big pay increase to try to get you to stay, you have to point out to them that you're leaving because you're unhappy with the promotion/raise/bonus structure at the company, not your current salary rate. Basically, whatever you tell them, make sure its honest. If you don't like your projects and company politics, and you tell them that you love the company but you're leaving for a higher salary, don't be surprised if the company comes back with more money. Then, when you turn down the counter offer, they'll have sentiments along the lines of "Well what the heck man?? Do you know how many hoops we had to jump through to get you this offer? We thought you really wanted to stay with us. You told us you would stay if we matched your offer and now you're not going to?". If you're genuine and honest with your employer about why you're leaving, a good employer will understand.
9,013,024
I am attempting to build a download accelerator for Linux. My program utilizes gevent, os, and urllib2. My program receives a URL and attempts to download the file concurrently. All of my code is valid. My only problem is that urllib2.urlopen.read() is blocking me from running the .read() function concurrently. This is the exception thats thrown at me. ``` Traceback (most recent call last): File "/usr/lib/pymodules/python2.7/gevent/greenlet.py", line 405, in run result = self._run(*self.args, **self.kwargs) File "gevent_concurrent_downloader.py", line 94, in childTasklet _tempRead = handle.read(divisor) # Read/Download part File "/usr/lib/python2.7/socket.py", line 380, in read data = self._sock.recv(left) File "/usr/lib/python2.7/httplib.py", line 561, in read s = self.fp.read(amt) File "/usr/lib/python2.7/socket.py", line 380, in read data = self._sock.recv(left) File "/usr/lib/pymodules/python2.7/gevent/socket.py", line 407, in recv wait_read(sock.fileno(), timeout=self.timeout, event=self._read_event) File "/usr/lib/pymodules/python2.7/gevent/socket.py", line 153, in wait_read assert event.arg is None, 'This event is already used by another greenlet: %r' % (event.arg, ) AssertionError: This event is already used by another greenlet: (<Greenlet at 0x2304958: childTasklet(<__main__.NewFile object at 0x22c4390>, 4595517, <addinfourl at 37154616 whose fp = <socket._fileob, 459551, 1)>, timeout('timed out',)) <Greenlet at 0x2304ea8: childTasklet(<__main__.NewFile object at 0x22c4390>,4595517, <addinfourl at 37154616 whose fp = <socket._fileob, 7, -1)failed with AssertionError ``` My program works by getting the file byte size from the URL by invoking: ``` urllib2.urlopen(URL).info().get("Content-Length") ``` and dividing the file size by a divisor and thus breaking the download process into parts. In this example i am breaking the download into 10 parts. Each greenlet runs a command in this fassion: ``` urllib2.urlopen(URL).read(offset) ``` **Here's a link to my code hosted on pastie**: <http://pastie.org/3253705> Thank you for the help! FYI: I am running on Ubuntu 11.10.
2012/01/26
['https://Stackoverflow.com/questions/9013024', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1113071/']
You're trying to read a response to a single request from different greenlets. If you'd like to download the same file using *several* concurrent connections then you could use [`Range` http header](https://www.rfc-editor.org/rfc/rfc2616#section-14.35) if the server supports it (you get 206 status instead of 200 for the request with Range header). See [`HTTPRangeHandler`](http://yum.baseurl.org/gitweb?p=urlgrabber.git;a=blob;f=urlgrabber/byterange.py;h=8eeaeda0fe2bb636ca5c8e37d9d77905f1a5d5f1;hb=HEAD).
the argument to `read` is a number of bytes, not an offset. It seems gevent will let you call urllib asynchronously, but not let you access the same resource from multiple greenlets. Furthermore, since it is using wait\_read, the effect will still be a synchronous, sequential read from the file (The complete opposite of what you wanted to achieve). I'd suggest you might need to go lower than, or use a different library from, urllib2.
13,542,805
I currently convert an integer to a string for display to the screen, but wish to maintain 4 digits - i.e 10 = "0010". What is the best way of going from an integer of 10 to a string of "0010"? This is in C# and .NET 4. Cheers!
2012/11/24
['https://Stackoverflow.com/questions/13542805', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1299105/']
``` int num = 1; // pad with 0 up to 4 places string str = num.ToString("D4"); ```
``` var str = 10.ToString("0000"); ```
13,542,805
I currently convert an integer to a string for display to the screen, but wish to maintain 4 digits - i.e 10 = "0010". What is the best way of going from an integer of 10 to a string of "0010"? This is in C# and .NET 4. Cheers!
2012/11/24
['https://Stackoverflow.com/questions/13542805', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1299105/']
``` var str = 10.ToString("0000"); ```
You can try :- ``` string str = num.ToString("D8"); //padding with 8 zero's ``` Check this [link](http://msdn.microsoft.com/en-us/library/dd260048.aspx)
13,542,805
I currently convert an integer to a string for display to the screen, but wish to maintain 4 digits - i.e 10 = "0010". What is the best way of going from an integer of 10 to a string of "0010"? This is in C# and .NET 4. Cheers!
2012/11/24
['https://Stackoverflow.com/questions/13542805', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1299105/']
``` int num = 1; // pad with 0 up to 4 places string str = num.ToString("D4"); ```
You can try :- ``` string str = num.ToString("D8"); //padding with 8 zero's ``` Check this [link](http://msdn.microsoft.com/en-us/library/dd260048.aspx)
62,152,528
I have a small snipped of code, which just produces a function to get the current directory for either Windows or Linux platform: ``` #include <stdio.h> /* defines FILENAME_MAX */ #include <string> #ifdef WINDOWS #include <direct.h> #define GetCurrentDir _getcwd #else #include <unistd.h> #define GetCurrentDir getcwd #endif std::string getcwd(){ char mCurrentPath[FILENAME_MAX]; GetCurrentDir(mCurrentPath, sizeof(mCurrentPath)); return *(new std::string (mCurrentPath)); } ``` This is all great and working; however, I'd like to make the `getcwd()` function inside the namespace, `fUtils`, hence I did this: ``` #include <stdio.h> /* defines FILENAME_MAX */ #include <string> #ifdef WINDOWS #include <direct.h> #define GetCurrentDir _getcwd #else #include <unistd.h> #define GetCurrentDir getcwd #endif namespace fUtils{ std::string getcwd(){ char mCurrentPath[FILENAME_MAX]; GetCurrentDir(mCurrentPath, sizeof(mCurrentPath)); return *(new std::string (mCurrentPath)); } } ``` But this gives an error in `VSCode` which says: > > `no matching function for call to 'getcwd'` > > > What mistake am I making in this? If this isn't how I put the function to the namespace `fUtils`, then how should I put it into the namespace?
2020/06/02
['https://Stackoverflow.com/questions/62152528', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9007093/']
Your `fUtils::getcwd()` function is attempting to call *itself* when the `GetCurrentDir` macro is evaluated (to `getcwd`), and this results in a function that expects no argument but is being given two arguments. To resolve this, add the global namespace operator (`::`) in the definitions for `GetCurrentDir`, as follows: ```cpp #ifdef WINDOWS #include <direct.h> #define GetCurrentDir ::_getcwd #else #include <unistd.h> #define GetCurrentDir ::getcwd #endif ``` Then, in your function body, it is clear to the compiler that your aren't looking for a 'recursive' (and invalid) call.
Use of macros in such context is invitation to problems in future. Just wrap those functions with own API and all problems will be resolved. Header file: ```cpp #include <string> namepsace fUtils { std::string getcwd(); } ``` Then you can have platform specific cpp files, Windows: ```cpp namepsace fUtils { std::string getcwd() { char mCurrentPath[FILENAME_MAX]; ::_getcwd(mCurrentPath, sizeof(mCurrentPath)); return {mCurrentPath}; } } ``` Mac version is obvious. You also can use this macros inside single cpp file and this way contain them there if you do not what to do larger clean up. Side notes: ----------- * there is `boost::filesystem` which has such api also use of `boost::filesystem::path` is quite handy * C++17 introduces `std::filesystem`, but it is not well supported yet (for example MacOS) * if you wrap this functionality in classes you will open your way for better testing (mocks).
52,327,462
I am creating a chat app, for which I need to check each of my contact list members if they are registered with my app and show the registered members list in my app. Currently I am calling an API to check every number one by one. In case of 800 contacts it is getting called 800 times. I know this is not best way to do it. So, can some one please help me out and suggest me to do it in better way? Below is my code: ``` func createContactNumbersArray() { for i in 0...self.objects.count-1 { let contact:CNContact! = self.objects[i] if contact.phoneNumbers.count > 0 { for j in 0...contact.phoneNumbers.count-1 { print((contact.phoneNumbers[j].value).value(forKey: "digits")!) let tappedContactMobileNumber = (contact.phoneNumbers[j].value).value(forKey: "digits") let phoneNo = self.separateISDCodeMobileNo(mobileNo:tappedContactMobileNumber as! String) contactNumbersArray.append(phoneNo.1) } } } callGetAppUserDetailService(mobileNumber: self.contactNumbersArray[currentIndex] as! String) } ``` I am doing this whole process in the background and refreshing the member list on front in current scenario. I want to make the whole process as fast as Whatsapp.
2018/09/14
['https://Stackoverflow.com/questions/52327462', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7257122/']
In fact,you can do little on client. The normal way is: Server provide an interface that support check a phonenumber array, and return the phonenumbers has registered on server.
I think you need to save user's phone number to your database when user registers your app. Then you can find out contacts which have already used your chat app.
52,327,462
I am creating a chat app, for which I need to check each of my contact list members if they are registered with my app and show the registered members list in my app. Currently I am calling an API to check every number one by one. In case of 800 contacts it is getting called 800 times. I know this is not best way to do it. So, can some one please help me out and suggest me to do it in better way? Below is my code: ``` func createContactNumbersArray() { for i in 0...self.objects.count-1 { let contact:CNContact! = self.objects[i] if contact.phoneNumbers.count > 0 { for j in 0...contact.phoneNumbers.count-1 { print((contact.phoneNumbers[j].value).value(forKey: "digits")!) let tappedContactMobileNumber = (contact.phoneNumbers[j].value).value(forKey: "digits") let phoneNo = self.separateISDCodeMobileNo(mobileNo:tappedContactMobileNumber as! String) contactNumbersArray.append(phoneNo.1) } } } callGetAppUserDetailService(mobileNumber: self.contactNumbersArray[currentIndex] as! String) } ``` I am doing this whole process in the background and refreshing the member list on front in current scenario. I want to make the whole process as fast as Whatsapp.
2018/09/14
['https://Stackoverflow.com/questions/52327462', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7257122/']
There is no way to do it without back-end modifications. So you need to work closely with your back-end engineer and build an API for this. Here is an advise how you can build this API: To have 2 APIs: 1) Upload the whole user address book to the back-end in a single request, something like: ``` let addressBook = NSMutableOrderedSet() let contact1 = AddressBookContact() contact1.name = "Jony Ive" contact1.phone = "1-800-300-2000" addressBook.add(contact1) let contact2 = AddressBookContact() contact2.name = "Steve Why" contact2.phone = "412739123123" addressBook.add(contact2) let deviceUDID = nil Request.uploadAddressBook(withUdid: deviceUDID, addressBook: addressBook, force: false, successBlock: { (updates) in }) { (error) in } ``` 2) As a next step - retrieve a list of already registered users with phones from your address book, something like this: ``` let deviceUDID = nil Request.registeredUsersFromAddressBook(withUdid: nil, successBlock: { (users) in }) { (error) in } ``` so now you can show it in UI Found this example here <https://developers.connectycube.com/ios/address-book>
I think you need to save user's phone number to your database when user registers your app. Then you can find out contacts which have already used your chat app.
52,327,462
I am creating a chat app, for which I need to check each of my contact list members if they are registered with my app and show the registered members list in my app. Currently I am calling an API to check every number one by one. In case of 800 contacts it is getting called 800 times. I know this is not best way to do it. So, can some one please help me out and suggest me to do it in better way? Below is my code: ``` func createContactNumbersArray() { for i in 0...self.objects.count-1 { let contact:CNContact! = self.objects[i] if contact.phoneNumbers.count > 0 { for j in 0...contact.phoneNumbers.count-1 { print((contact.phoneNumbers[j].value).value(forKey: "digits")!) let tappedContactMobileNumber = (contact.phoneNumbers[j].value).value(forKey: "digits") let phoneNo = self.separateISDCodeMobileNo(mobileNo:tappedContactMobileNumber as! String) contactNumbersArray.append(phoneNo.1) } } } callGetAppUserDetailService(mobileNumber: self.contactNumbersArray[currentIndex] as! String) } ``` I am doing this whole process in the background and refreshing the member list on front in current scenario. I want to make the whole process as fast as Whatsapp.
2018/09/14
['https://Stackoverflow.com/questions/52327462', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7257122/']
There is no way to do it without back-end modifications. So you need to work closely with your back-end engineer and build an API for this. Here is an advise how you can build this API: To have 2 APIs: 1) Upload the whole user address book to the back-end in a single request, something like: ``` let addressBook = NSMutableOrderedSet() let contact1 = AddressBookContact() contact1.name = "Jony Ive" contact1.phone = "1-800-300-2000" addressBook.add(contact1) let contact2 = AddressBookContact() contact2.name = "Steve Why" contact2.phone = "412739123123" addressBook.add(contact2) let deviceUDID = nil Request.uploadAddressBook(withUdid: deviceUDID, addressBook: addressBook, force: false, successBlock: { (updates) in }) { (error) in } ``` 2) As a next step - retrieve a list of already registered users with phones from your address book, something like this: ``` let deviceUDID = nil Request.registeredUsersFromAddressBook(withUdid: nil, successBlock: { (users) in }) { (error) in } ``` so now you can show it in UI Found this example here <https://developers.connectycube.com/ios/address-book>
In fact,you can do little on client. The normal way is: Server provide an interface that support check a phonenumber array, and return the phonenumbers has registered on server.
44,725
Здесь прямая речь находится внутри авторских слов, но, по моему, нет определенных указаний на ее введение авторскими словами. В связи с этим вопрос: нужно ли двоеточие после слова "замешательство" или можно ограничиться точкой? Женщина, вероятно, поняла моё замешательство: «Ваше платье несколько испачкалось. Вы можете взять любое из тех, что висят в гардеробе. Супруг и сын были вынуждены отъехать по делам, а мы с Лизонькой будем рады, если Вы согласитесь присоединиться к нашему чаепитию. Засим позвольте мне оставить вас». Варвара Андреевна поднялась и вышла, закрыв за собой массивную белую дверь с золочёной ручкой в форме чуть приоткрывшегося бутона лилии.
2014/12/25
['https://rus.stackexchange.com/questions/44725', 'https://rus.stackexchange.com', 'https://rus.stackexchange.com/users/4012/']
2 Перед прямой речью, следующей за авторскими словами, ставится двоеточие... 3 Если прямая речь начинается с абзаца, то двоеточие после предшествующих авторских слов ставится не всегда. <http://www.evartist.narod.ru/text1/52.htm> §119. Прямая речь после авторских слов
Конечно,Аленка, это слова автора. В этом случае глаголы "говорения" (помню нечто подобное у Розенталя) подразумеваются.Он посмотрел на меня (и спросил): "Это ты сделал?". В Вашем предложении "Женщина поняла мое замешательство (и сказала): "Ваше платье несколько испачкалось"
44,725
Здесь прямая речь находится внутри авторских слов, но, по моему, нет определенных указаний на ее введение авторскими словами. В связи с этим вопрос: нужно ли двоеточие после слова "замешательство" или можно ограничиться точкой? Женщина, вероятно, поняла моё замешательство: «Ваше платье несколько испачкалось. Вы можете взять любое из тех, что висят в гардеробе. Супруг и сын были вынуждены отъехать по делам, а мы с Лизонькой будем рады, если Вы согласитесь присоединиться к нашему чаепитию. Засим позвольте мне оставить вас». Варвара Андреевна поднялась и вышла, закрыв за собой массивную белую дверь с золочёной ручкой в форме чуть приоткрывшегося бутона лилии.
2014/12/25
['https://rus.stackexchange.com/questions/44725', 'https://rus.stackexchange.com', 'https://rus.stackexchange.com/users/4012/']
2 Перед прямой речью, следующей за авторскими словами, ставится двоеточие... 3 Если прямая речь начинается с абзаца, то двоеточие после предшествующих авторских слов ставится не всегда. <http://www.evartist.narod.ru/text1/52.htm> §119. Прямая речь после авторских слов
Если прямая речь начинается с абзаца, то двоеточие после предшествующих слов автора ставится не всегда: > > двоеточие ставится, если слова автора содержат глагол со значением речи-мысли (говорить, сказать, рассказать, заметить, обратиться, воскликнуть, закричать, прошептать, спросить, спрашивать, ответить, вставить, прервать, заговорить, начать, продолжать, подтвердить, пояснить, согласиться, поддакнуть, напомнить, посоветовать, упрекнуть, решить, подумать и т. п.) либо существительное, близкое по значению или образованию к глаголам речи-мысли (вопрос, ответ, слова, восклицание, голос, шёпот, звук, крик, мысль и т. п.). ***Д.Э. Розенталь.Справочник по русскому языку: орфография и пунктуация.*** > > > ***Как отметил Виктор, здесь подразумеваются глаголы речи-мысли, поэтому после слов автора нужно двоеточие.***
44,725
Здесь прямая речь находится внутри авторских слов, но, по моему, нет определенных указаний на ее введение авторскими словами. В связи с этим вопрос: нужно ли двоеточие после слова "замешательство" или можно ограничиться точкой? Женщина, вероятно, поняла моё замешательство: «Ваше платье несколько испачкалось. Вы можете взять любое из тех, что висят в гардеробе. Супруг и сын были вынуждены отъехать по делам, а мы с Лизонькой будем рады, если Вы согласитесь присоединиться к нашему чаепитию. Засим позвольте мне оставить вас». Варвара Андреевна поднялась и вышла, закрыв за собой массивную белую дверь с золочёной ручкой в форме чуть приоткрывшегося бутона лилии.
2014/12/25
['https://rus.stackexchange.com/questions/44725', 'https://rus.stackexchange.com', 'https://rus.stackexchange.com/users/4012/']
2 Перед прямой речью, следующей за авторскими словами, ставится двоеточие... 3 Если прямая речь начинается с абзаца, то двоеточие после предшествующих авторских слов ставится не всегда. <http://www.evartist.narod.ru/text1/52.htm> §119. Прямая речь после авторских слов
Розенталь пишет на этот счет: "Двоеточие ставится также и в тех случаях, когда в авторских словах нет глаголов речи или заменяющих их глаголов с указанными выше значениями, но ситуация показывает, что вводится прямая речь, например: ...А тот ему: «Этот дом наш общий» (Чехов)".
67,678
If someone wanted to sign a 12 month rental contract and, being over 70 and single, wanted that contract to terminate upon death of the renter so the landlord would not have right to claim payment from the estate for the remaining contract period and also required the landlord to release any personal belongings to heirs or executor. How might this be treated under Florida law?
2021/07/13
['https://law.stackexchange.com/questions/67678', 'https://law.stackexchange.com', 'https://law.stackexchange.com/users/39019/']
It would be treated like a residential lease with whatever legal terms were agreed ---------------------------------------------------------------------------------- The first term may need some careful drafting to comply with any minimum notice law Florida has. So a term that gave the estate the option to give 30 days notice or something similar. The second term is unnecessary - you can’t keep other people’s stuff even if they owe you money.
> > What specific legal statement might one request to include in a 12 month rental contract so that the rental contract terminates upon renter's death? > > > There is a risk that formulating an isolated statement or provision without us knowing other relevant clauses of the proposed draft might be superseded by those other clauses. The terms you have in mind seem to be "*The death of the renter terminates the contract and gives the landlord no entitlement to remedies against the tenant's estate for what would otherwise constitute breach or early termination of contract*". However, it is unclear from your description whether such terms would conflict with other language in the draft. For instance, somewhere the draft might encompass tenant's successors or heirs, which would defeat the argument that the lease is of a *strictly personal nature*. See [*In re Estate of Conklin*, 116 Ill.App.3 426, 428 (1983)](https://www.leagle.com/decision/1983542116illapp3d4261481): > > In [*Warnecke v. Estate of Rabenau* (Mo. App. 1963), 367 S.W.2d > 15](https://www.leagle.com/decision/1963382367sw2d151379), the lease was for office space to be used for the specific > purpose of the business of the lessee, a public accountant; the term > "lessee" was defined to include servants, employees, and clients, but > did not include successors, assigns, heirs, or personal > representative. The Missouri court concluded that the terms of the > lease made it personal to the lessee and thus terminated on his death. > The court acknowledged the general rule that death does not ordinarily > terminate the lease. [...] Two later Missouri cases [...] [were] > residential leases were involved and provided that they were binding > upon the heirs, executors, administrators, successors and assigns of > both parties. The court held that this language was clear and > unambiguous and that the leases were not personal. > > > Florida law does not appear to have statutory or case law that would lead to a different conclusion. *Warnecke* portrays that "*[t]he lease provided that the leased premises were to be used and occupied as office for certified public accountants, but for no other purpose"*". With this in mind, making sure that the lease identifies you as *the only tenant* would, *inter alia*, prevent the landlord from taking advantage of some principle akin to [*Goldenbaum v. Delorenzo*, No. 08-1127 (U.S. Dist. Court, N.J., Dec. 2010)](https://www.leagle.com/decision/infdco20101213747) ("*[t]he legislation was designed to protect residential tenants against unfair and arbitrary evictions by limiting the bases for their removal*"). That principle protects residential tenants, yet it might favor the landlord in the sense that a court ought not to disregard his "good faith adherence" to said legislative principle.
18,897,410
I'm using Liferay 6.1.20 and my Portlet is using the Liferay Mail Service to send an E-Mail via the in Liferay configured SMTP-Server. My Question is now: is it possible to check whether the SMTP-Server is available or is it possbile to check whether the E-Mail was successfully sent? If the SMTP-Server is not available I want to give an output to the User. Actually I only see the following line in the server console: ``` 14:06:47,679 WARN [liferay/mail-1][MailEngine:560] Failed to connect to a valid mail server. Please make sure one is properly configured. Could not connect to SMTP host: localhost, port: 25 ``` I hope someone can give me a solution for that. Thanks!
2013/09/19
['https://Stackoverflow.com/questions/18897410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2343286/']
basically there are two problems which prevent you to discover if any failure occurred when sending e-mails with MailServiceUtil service. Firstly messages are sent asynchronously over Liferay message bus, so the user gets faster response but you never know if anything failed on the way. Secondly messages eventually get to MailEngine where all exceptions get caught and are only written to the log. So, I suggest you to override MailEngine class with ext-plugin (it's in util-java) to handle exceptions differently and then use it directly from your plugin instead of MailServiceUtil which only pushes all to the message bus.
Since Liferay 6.2, if you set *mail.throws.exception.on.failure=true* in your portal-ext.properties file, the MailEngine class will also throw a `com.liferay.util.mail.MailEngineException` on errors, instead of just logging.
18,897,410
I'm using Liferay 6.1.20 and my Portlet is using the Liferay Mail Service to send an E-Mail via the in Liferay configured SMTP-Server. My Question is now: is it possible to check whether the SMTP-Server is available or is it possbile to check whether the E-Mail was successfully sent? If the SMTP-Server is not available I want to give an output to the User. Actually I only see the following line in the server console: ``` 14:06:47,679 WARN [liferay/mail-1][MailEngine:560] Failed to connect to a valid mail server. Please make sure one is properly configured. Could not connect to SMTP host: localhost, port: 25 ``` I hope someone can give me a solution for that. Thanks!
2013/09/19
['https://Stackoverflow.com/questions/18897410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2343286/']
basically there are two problems which prevent you to discover if any failure occurred when sending e-mails with MailServiceUtil service. Firstly messages are sent asynchronously over Liferay message bus, so the user gets faster response but you never know if anything failed on the way. Secondly messages eventually get to MailEngine where all exceptions get caught and are only written to the log. So, I suggest you to override MailEngine class with ext-plugin (it's in util-java) to handle exceptions differently and then use it directly from your plugin instead of MailServiceUtil which only pushes all to the message bus.
A really old question, but as I kept arriving here, I am leaving this to anyone that may need (tested on 7.3). We can test if the mail flow is normal with the following Groovy script: ``` import com.liferay.mail.kernel.service.MailServiceUtil import javax.mail.* import javax.mail.internet.* import com.liferay.mail.kernel.model.MailMessage; def from = new InternetAddress("[email protected]") def to = new InternetAddress ("[email protected]") def mail = new MailMessage(from, to, "subject", "test message", false) MailServiceUtil.sendEmail(mail) ``` And, as mentioned in the other answer, the property to view exceptions is still valid. ``` mail.throws.exception.on.failure=true ```
18,897,410
I'm using Liferay 6.1.20 and my Portlet is using the Liferay Mail Service to send an E-Mail via the in Liferay configured SMTP-Server. My Question is now: is it possible to check whether the SMTP-Server is available or is it possbile to check whether the E-Mail was successfully sent? If the SMTP-Server is not available I want to give an output to the User. Actually I only see the following line in the server console: ``` 14:06:47,679 WARN [liferay/mail-1][MailEngine:560] Failed to connect to a valid mail server. Please make sure one is properly configured. Could not connect to SMTP host: localhost, port: 25 ``` I hope someone can give me a solution for that. Thanks!
2013/09/19
['https://Stackoverflow.com/questions/18897410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2343286/']
Since Liferay 6.2, if you set *mail.throws.exception.on.failure=true* in your portal-ext.properties file, the MailEngine class will also throw a `com.liferay.util.mail.MailEngineException` on errors, instead of just logging.
A really old question, but as I kept arriving here, I am leaving this to anyone that may need (tested on 7.3). We can test if the mail flow is normal with the following Groovy script: ``` import com.liferay.mail.kernel.service.MailServiceUtil import javax.mail.* import javax.mail.internet.* import com.liferay.mail.kernel.model.MailMessage; def from = new InternetAddress("[email protected]") def to = new InternetAddress ("[email protected]") def mail = new MailMessage(from, to, "subject", "test message", false) MailServiceUtil.sendEmail(mail) ``` And, as mentioned in the other answer, the property to view exceptions is still valid. ``` mail.throws.exception.on.failure=true ```
31,361
Anyone every purchase / use hardware from <http://SiliconMechanics.com>? Their prices seem to be unbeatable. So I'm curious to know how reliable their servers are. **Also, who do you recommend to buy the best bang for your buck on rack servers?**
2009/06/25
['https://serverfault.com/questions/31361', 'https://serverfault.com', 'https://serverfault.com/users/-1/']
For the love of the flying spaghetti monster; don't ever pay retail. We just did a large purchase from Dell for a bunch of servers, an EMC CX4 SAN, switches, load ballancers, etc. With full Microsoft licensing we paid easily 30-40% off the original quotes. It's all about having a good sales rep, and being able to negotiate when them and get them to work the partners for the best possible deals.
I have a Silicon Mechanics rack mount that I bought used. It is a dual socket Opteron system with a 3ware raid controller and I have had no hardware problems with it. A friend bought some used on Ebay and those have worked without hardware issues. My former employer has a dozen Silicon Mechanics boxes that they use for Test and Production. The only problems those boxes every had were software issues with our own code. If I were looking for new servers, I would put them high on the list of vendors to get quotes from.
31,361
Anyone every purchase / use hardware from <http://SiliconMechanics.com>? Their prices seem to be unbeatable. So I'm curious to know how reliable their servers are. **Also, who do you recommend to buy the best bang for your buck on rack servers?**
2009/06/25
['https://serverfault.com/questions/31361', 'https://serverfault.com', 'https://serverfault.com/users/-1/']
I have a Silicon Mechanics rack mount that I bought used. It is a dual socket Opteron system with a 3ware raid controller and I have had no hardware problems with it. A friend bought some used on Ebay and those have worked without hardware issues. My former employer has a dozen Silicon Mechanics boxes that they use for Test and Production. The only problems those boxes every had were software issues with our own code. If I were looking for new servers, I would put them high on the list of vendors to get quotes from.
I've used a variety of vendors over the years and I always come back to Dell. Their build quality is hard to beat. For important servers, I love the fact that I can call them up and say "it won't boot" and 90 minutes later a guy shows up with a box full of parts and begins swapping them out until it works. Fried motherboard on a production mail server. Total downtime: 2 hours. (Yes, it should've been redundant. It wasn't.)
31,361
Anyone every purchase / use hardware from <http://SiliconMechanics.com>? Their prices seem to be unbeatable. So I'm curious to know how reliable their servers are. **Also, who do you recommend to buy the best bang for your buck on rack servers?**
2009/06/25
['https://serverfault.com/questions/31361', 'https://serverfault.com', 'https://serverfault.com/users/-1/']
We've (company I work for) used Silicon Mechanics for a while. Probably >20 servers from them, many of them with weird requirements, from low-end stuff (single-CPU, single-disk web servers) to multi-core, multi-CPU 16-disk DB servers, to weird stuff like telephony servers. We even got some Windows XP(!) servers from them fairly recently, no problems at all. Almost all of it has worked perfectly with no problems. We've only ever had problems with three machines (one had a bad HDD backplane, found with intense testing on arrival, one had some RAM fail after the better part of a year, and the other was just Western Digital's lovely quality control), and their support (we just have the standard warranty) has been excellent.
I bought 3 servers from them probably 3 years ago. 2 servers had the (cheap plastic) rabbit ears break off almost immediately. One server was RMA'd. In terms of operations and not cheap plastic case addons, they've been reliable machines. I've heard their quality has improved from the models I bought.
31,361
Anyone every purchase / use hardware from <http://SiliconMechanics.com>? Their prices seem to be unbeatable. So I'm curious to know how reliable their servers are. **Also, who do you recommend to buy the best bang for your buck on rack servers?**
2009/06/25
['https://serverfault.com/questions/31361', 'https://serverfault.com', 'https://serverfault.com/users/-1/']
We've (company I work for) used Silicon Mechanics for a while. Probably >20 servers from them, many of them with weird requirements, from low-end stuff (single-CPU, single-disk web servers) to multi-core, multi-CPU 16-disk DB servers, to weird stuff like telephony servers. We even got some Windows XP(!) servers from them fairly recently, no problems at all. Almost all of it has worked perfectly with no problems. We've only ever had problems with three machines (one had a bad HDD backplane, found with intense testing on arrival, one had some RAM fail after the better part of a year, and the other was just Western Digital's lovely quality control), and their support (we just have the standard warranty) has been excellent.
I've used a variety of vendors over the years and I always come back to Dell. Their build quality is hard to beat. For important servers, I love the fact that I can call them up and say "it won't boot" and 90 minutes later a guy shows up with a box full of parts and begins swapping them out until it works. Fried motherboard on a production mail server. Total downtime: 2 hours. (Yes, it should've been redundant. It wasn't.)
31,361
Anyone every purchase / use hardware from <http://SiliconMechanics.com>? Their prices seem to be unbeatable. So I'm curious to know how reliable their servers are. **Also, who do you recommend to buy the best bang for your buck on rack servers?**
2009/06/25
['https://serverfault.com/questions/31361', 'https://serverfault.com', 'https://serverfault.com/users/-1/']
For the love of the flying spaghetti monster; don't ever pay retail. We just did a large purchase from Dell for a bunch of servers, an EMC CX4 SAN, switches, load ballancers, etc. With full Microsoft licensing we paid easily 30-40% off the original quotes. It's all about having a good sales rep, and being able to negotiate when them and get them to work the partners for the best possible deals.
We've (company I work for) used Silicon Mechanics for a while. Probably >20 servers from them, many of them with weird requirements, from low-end stuff (single-CPU, single-disk web servers) to multi-core, multi-CPU 16-disk DB servers, to weird stuff like telephony servers. We even got some Windows XP(!) servers from them fairly recently, no problems at all. Almost all of it has worked perfectly with no problems. We've only ever had problems with three machines (one had a bad HDD backplane, found with intense testing on arrival, one had some RAM fail after the better part of a year, and the other was just Western Digital's lovely quality control), and their support (we just have the standard warranty) has been excellent.
31,361
Anyone every purchase / use hardware from <http://SiliconMechanics.com>? Their prices seem to be unbeatable. So I'm curious to know how reliable their servers are. **Also, who do you recommend to buy the best bang for your buck on rack servers?**
2009/06/25
['https://serverfault.com/questions/31361', 'https://serverfault.com', 'https://serverfault.com/users/-1/']
Fyi; [SilliconMechanics](http://siliconmechanics.com) is just reselling branded [SuperMicro](http://supermicro.com) machines at a lower cost than direct with added support and sales. Still cheaper to buy from them than elsewhere -- but their equipment does come from a bigname whitebox manufacturer.
We've (company I work for) used Silicon Mechanics for a while. Probably >20 servers from them, many of them with weird requirements, from low-end stuff (single-CPU, single-disk web servers) to multi-core, multi-CPU 16-disk DB servers, to weird stuff like telephony servers. We even got some Windows XP(!) servers from them fairly recently, no problems at all. Almost all of it has worked perfectly with no problems. We've only ever had problems with three machines (one had a bad HDD backplane, found with intense testing on arrival, one had some RAM fail after the better part of a year, and the other was just Western Digital's lovely quality control), and their support (we just have the standard warranty) has been excellent.
31,361
Anyone every purchase / use hardware from <http://SiliconMechanics.com>? Their prices seem to be unbeatable. So I'm curious to know how reliable their servers are. **Also, who do you recommend to buy the best bang for your buck on rack servers?**
2009/06/25
['https://serverfault.com/questions/31361', 'https://serverfault.com', 'https://serverfault.com/users/-1/']
For the love of the flying spaghetti monster; don't ever pay retail. We just did a large purchase from Dell for a bunch of servers, an EMC CX4 SAN, switches, load ballancers, etc. With full Microsoft licensing we paid easily 30-40% off the original quotes. It's all about having a good sales rep, and being able to negotiate when them and get them to work the partners for the best possible deals.
I've used a variety of vendors over the years and I always come back to Dell. Their build quality is hard to beat. For important servers, I love the fact that I can call them up and say "it won't boot" and 90 minutes later a guy shows up with a box full of parts and begins swapping them out until it works. Fried motherboard on a production mail server. Total downtime: 2 hours. (Yes, it should've been redundant. It wasn't.)
31,361
Anyone every purchase / use hardware from <http://SiliconMechanics.com>? Their prices seem to be unbeatable. So I'm curious to know how reliable their servers are. **Also, who do you recommend to buy the best bang for your buck on rack servers?**
2009/06/25
['https://serverfault.com/questions/31361', 'https://serverfault.com', 'https://serverfault.com/users/-1/']
For the love of the flying spaghetti monster; don't ever pay retail. We just did a large purchase from Dell for a bunch of servers, an EMC CX4 SAN, switches, load ballancers, etc. With full Microsoft licensing we paid easily 30-40% off the original quotes. It's all about having a good sales rep, and being able to negotiate when them and get them to work the partners for the best possible deals.
I bought 3 servers from them probably 3 years ago. 2 servers had the (cheap plastic) rabbit ears break off almost immediately. One server was RMA'd. In terms of operations and not cheap plastic case addons, they've been reliable machines. I've heard their quality has improved from the models I bought.
31,361
Anyone every purchase / use hardware from <http://SiliconMechanics.com>? Their prices seem to be unbeatable. So I'm curious to know how reliable their servers are. **Also, who do you recommend to buy the best bang for your buck on rack servers?**
2009/06/25
['https://serverfault.com/questions/31361', 'https://serverfault.com', 'https://serverfault.com/users/-1/']
I have a Silicon Mechanics rack mount that I bought used. It is a dual socket Opteron system with a 3ware raid controller and I have had no hardware problems with it. A friend bought some used on Ebay and those have worked without hardware issues. My former employer has a dozen Silicon Mechanics boxes that they use for Test and Production. The only problems those boxes every had were software issues with our own code. If I were looking for new servers, I would put them high on the list of vendors to get quotes from.
I bought 3 servers from them probably 3 years ago. 2 servers had the (cheap plastic) rabbit ears break off almost immediately. One server was RMA'd. In terms of operations and not cheap plastic case addons, they've been reliable machines. I've heard their quality has improved from the models I bought.
31,361
Anyone every purchase / use hardware from <http://SiliconMechanics.com>? Their prices seem to be unbeatable. So I'm curious to know how reliable their servers are. **Also, who do you recommend to buy the best bang for your buck on rack servers?**
2009/06/25
['https://serverfault.com/questions/31361', 'https://serverfault.com', 'https://serverfault.com/users/-1/']
Fyi; [SilliconMechanics](http://siliconmechanics.com) is just reselling branded [SuperMicro](http://supermicro.com) machines at a lower cost than direct with added support and sales. Still cheaper to buy from them than elsewhere -- but their equipment does come from a bigname whitebox manufacturer.
I bought 3 servers from them probably 3 years ago. 2 servers had the (cheap plastic) rabbit ears break off almost immediately. One server was RMA'd. In terms of operations and not cheap plastic case addons, they've been reliable machines. I've heard their quality has improved from the models I bought.
47,305,875
can you give me a hint how to sort the points according to x coordinates in O(nLogn)? ``` Set<Point> points = new HashSet<Point>(); points.add(new Point(9, 0)); points.add(new Point(1, 1)); points.add(new Point(5, 6)); points.add(new Point(3, 3)); points.add(new Point(2, 7)); points.add(new Point(1, 8)); points.add(new Point(6, 1)); ``` I wish I could do something like `Point[] points2 = points.toArray();` and afterwards sort it. But of course it isn´t working.
2017/11/15
['https://Stackoverflow.com/questions/47305875', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8027142/']
``` Set<Point> sortedPoints = points .stream() .sorted(Comparator.comparing(Point::getX)) .collect(Collectors.toCollection(LinkedHashSet::new)); ``` I am sure this way is better of all because: 1) on the big amount of Points you can use ``` .paralellStream() ``` to increase the performance. and 2) the notation has declarative style and looks more clear.
Any `Set` that implements `SortedSet` interface can keep elements sorted within it. `TreeSet` is a known implementation of `SortedSet`. You can pass a custom Comparator for your class in the `TreeSet` constructor in order to obtain a set sorted according to your conditions. ``` public static void main(String[] args) { SortedSet<Point> points = new TreeSet<>(new Comparator<Point>() { @Override public int compare(Point o1, Point o2) { return o1.getX()- o2.getX(); } }); points.add(new Point(9, 0)); points.add(new Point(1, 1)); points.add(new Point(5, 6)); points.add(new Point(3, 3)); points.add(new Point(2, 7)); points.add(new Point(1, 8)); points.add(new Point(6, 1)); } ``` If the comparator code looks verbose to you, you can try the new Java 8 style comparator declaration. ``` SortedSet<Point> points = new TreeSet<>(Comparator.comparing(Point::getX)); ``` Regarding the last point, if you want to obtain an array from the `Set`, you can always do that by using following: ``` Point[] points2 = points.toArray(new Point[0]); ``` But, if your sole purpose is sorting the data, this should be avoided.
174,444
Do you know of a formula or function that can calculate the real world height of a satellite image in degrees? The image is from Google Static Maps and the image uses [Mercator projection](http://en.wikipedia.org/wiki/Mercator_projection#Derivation_of_the_Mercator_projection) which makes calculating the height very difficult. I can successfully calculate the width **but I don't know of a formula to calculate the height of the satellite image in degrees.** ![enter image description here](https://i.stack.imgur.com/hTagn.png) For the above image I know this information: * Width= 400px * Height= 400px * Central mid point is: -32 Lat 151 Long * Google's zoom value is 14 This is how I calculate the width which works: ``` // The reason I use 256 is because in google the whole earth fits inside 256 pixels // when the zoom value is 0(zoom can be 0 > zoom < 25) float meshWidthDeg = (imgWidth/256f)*(360f / Math.Pow(2f,zoom)); ```
2012/07/23
['https://math.stackexchange.com/questions/174444', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/23680/']
After a quick look at the Wikipedia entry for the Mercador projection, I believe that for short distances, the horizontal and vertical scales are the same (on a printed map). Scroll down to **Formulae for distance**. Pixels are usually not square, so you have to allow for that, and it could vary between devices. There is a comment there that Google uses a variant of the Mercador.
map a matrix over the image, and find the actual coordinate points of the grid points of your matrix. fill a second matrix with calculations of the coordinate points with the information of your picture. with two values in every gridpoint you can figure out a matrix of slopes. make a list of functions using the respective slopes and actual coordinate points. find the convergence point of these functions. with the convergence point you can construct a pyramidoid from which you can find whatever angle you want.
174,444
Do you know of a formula or function that can calculate the real world height of a satellite image in degrees? The image is from Google Static Maps and the image uses [Mercator projection](http://en.wikipedia.org/wiki/Mercator_projection#Derivation_of_the_Mercator_projection) which makes calculating the height very difficult. I can successfully calculate the width **but I don't know of a formula to calculate the height of the satellite image in degrees.** ![enter image description here](https://i.stack.imgur.com/hTagn.png) For the above image I know this information: * Width= 400px * Height= 400px * Central mid point is: -32 Lat 151 Long * Google's zoom value is 14 This is how I calculate the width which works: ``` // The reason I use 256 is because in google the whole earth fits inside 256 pixels // when the zoom value is 0(zoom can be 0 > zoom < 25) float meshWidthDeg = (imgWidth/256f)*(360f / Math.Pow(2f,zoom)); ```
2012/07/23
['https://math.stackexchange.com/questions/174444', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/23680/']
After a quick look at the Wikipedia entry for the Mercador projection, I believe that for short distances, the horizontal and vertical scales are the same (on a printed map). Scroll down to **Formulae for distance**. Pixels are usually not square, so you have to allow for that, and it could vary between devices. There is a comment there that Google uses a variant of the Mercador.
If you know the location of the satellite and the time of the photo, you can measure the length of shadows to determine height of the objects casting them.