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
13,140,659
I have developed an app using Phonegap for Android and IPhone. Is there how to programm the functionality with the Phonegap Framework to share a URL to twitter and Facebook for Android and IPhone? Thanks
2012/10/30
['https://Stackoverflow.com/questions/13140659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1551880/']
This is really amazing for iOS. Its working with Phonegap Cordova 2.3 <https://github.com/bfcam/phonegap-ios-social-plugin> For Android I'm using Android Share Plugin <https://github.com/phonegap/phonegap-plugins/tree/master/Android/Share>
Currently the best cross-platform social share widget is [this one](https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin) which is also [available on PhoneGap Build!](https://build.phonegap.com/plugins/382) It not only supports sharing via the native share widget, but you can also share directly to Facebook, Twitter, Pinterest, etc.
49,191,902
I have log data and I'm trying to back-fill the data as much as possible to help improve analytics. The log data contains a SessionId, which is the SessionId created by the browser, the Name of the logged in user (if they are logged in) and a LogTime. I'm trying to get all the related sessions, sessions that are within 24 hours of each other, and get the first date of that group of sessions, the last date of that group of sessions and populate the first not null and not empty name into all the other name spaces. For instance, if I had the following data: ``` --Id SessionId Name LogTime --1 1 2018-01-01 00:00 --2 1 LargeOne 2018-01-01 12:00 --3 2 Two 2018-01-01 13:00 --4 3 NULL 2018-01-02 00:00 --5 3 2018-01-03 00:00 --6 1 One 2018-01-03 00:00 --7 2 2018-01-03 00:00 --8 2 LargeTwo 2018-01-04 00:00 --9 1 2018-01-04 00:00 ``` I would like to process the data as follows: ``` --Id SessionId Name LogTime StartTime EndTime --1 1 LargeOne 2018-01-01 00:00 2018-01-01 00:00 2018-01-01 12:00 --2 1 LargeOne 2018-01-01 12:00 2018-01-01 00:00 2018-01-01 12:00 --3 2 Two 2018-01-01 13:00 2018-01-01 13:00 2018-01-01 13:00 --4 3 NULL 2018-01-02 00:00 2018-01-02 00:00 2018-01-03 00:00 --5 3 NULL 2018-01-03 00:00 2018-01-02 00:00 2018-01-03 00:00 --6 1 One 2018-01-03 00:00 2018-01-03 00:00 2018-01-04 00:00 --7 2 LargeTwo 2018-01-03 00:00 2018-01-03 00:00 2018-01-04 00:00 --8 2 LargeTwo 2018-01-04 00:00 2018-01-03 00:00 2018-01-04 00:00 --9 1 One 2018-01-04 00:00 2018-01-03 00:00 2018-01-04 00:00 ``` Ids 1 and 2 are in the same session and in range (24 hours) of each other so they make one set, notice that the Id 1 doesn't have a name column but Id 2 does and because it's part of the same set, it back fills the name. Ids 6 and 9 are also in session 1 but is not in the 24 hour range of the first set so it makes a new set, Ids 6 and 9 are both in session 1 and even though new sessions appear between them, they are still the same session within range so they make a new set. I think that covers explaining the problem, now for my attempts at finding a solution. To find and backfill the Name, I tried to use: ``` SELECT Id,SessionId, FIRST_VALUE(Name) OVER (PARTITION BY SessionId ORDER BY CASE WHEN Name IS NULL or Name='' then 0 ELSE 1 END DESC,Id) Name, LogTime FROM #RawData ORDER BY Id ``` This produces: ``` --Id SessionId Name LogTime --1 1 LargeOne 2018-01-01 00:00 --2 1 LargeOne 2018-01-01 12:00 --3 2 Two 2018-01-01 13:00 --4 3 NULL 2018-01-02 00:00 --5 3 NULL 2018-01-03 00:00 --6 1 LargeOne 2018-01-03 00:00 --7 2 Two 2018-01-03 00:00 --8 2 Two 2018-01-04 00:00 --9 1 LargeOne 2018-01-04 00:00 ``` This almost works but it doesn't take the date ranges into consideration. So I did a lot of digging as to how to get the groups based on the SessionId and date ranges and I came up with this: ``` ;WITH ProcessTable1 AS ( SELECT Id,SessionId,Name,LogTime, PreviousLogTimeInRange = CASE WHEN LAG(LogTime, 1) OVER (partition by SessionId ORDER BY LogTime) between DATEADD(day, -1, LogTime) and LogTime THEN 0 ELSE 1 END, NextLogTimeInRange = CASE WHEN Lead(LogTime,1) OVER (partition by SessionId ORDER BY LogTime) between LogTime and DATEADD(day, 1, LogTime) THEN 0 ELSE 1 END FROM #RawData ), ProcessTable2 AS ( SELECT Id, Name, SessionId, LogTime, PreviousLogTimeInRange, NextLogTime = case when NextLogTimeInRange = 0 then LEAD(LogTime, 1) OVER (partition by SessionId ORDER BY LogTime) else LogTime end FROM ProcessTable1 WHERE 1 IN (PreviousLogTimeInRange, NextLogTimeInRange) ) SELECT Id,SessionId, FIRST_VALUE(Name) OVER (PARTITION BY SessionId ORDER BY CASE WHEN Name IS NULL or Name = '' then 0 ELSE 1 END DESC, Id) Name, LogTime, NextLogTime FROM ProcessTable2 --WHERE PreviousLogTimeInRange = 1 ORDER BY id; ``` This produces: ``` --Id SessionId Name LogTime NextLogTime --1 1 LargeOne 2018-01-01 00:00 2018-01-01 12:00 --2 1 LargeOne 2018-01-01 12:00 2018-01-01 12:00 --3 2 Two 2018-01-01 13:00 2018-01-01 13:00 --4 3 NULL 2018-01-02 00:00 2018-01-03 00:00 --5 3 NULL 2018-01-03 00:00 2018-01-03 00:00 --6 1 LargeOne 2018-01-03 00:00 2018-01-04 00:00 --7 2 Two 2018-01-03 00:00 2018-01-04 00:00 --8 2 Two 2018-01-04 00:00 2018-01-04 00:00 --9 1 LargeOne 2018-01-04 00:00 2018-01-04 00:00 ``` So close, but I still need the StartTime and to be honest I'm not 100% sure this will always do what I want. The last query was in part created from the findings on [SQL Query to group items by time, but only if near each other?](https://stackoverflow.com/questions/15818604/sql-query-to-group-items-by-time-but-only-if-near-each-other) If anyone is willing to lend a hand here, I would be eternally grateful! --Edit-- I've created some data to play with if anyone wants to give it a bash. ``` IF OBJECT_ID('tempdb..#RawData') IS NOT NULL DROP TABLE #RawData GO Create Table #RawData ( Id INT IDENTITY, SessionId INT NOT NULL, Name NVARCHAR(50) NULL, LogTime DATETIME NOT NULL ) INSERT INTO #RawData(SessionId,Name,LogTime) VALUES (1, '', '2018-01-01 00:00'), (1, 'LargeOne', '2018-01-01 12:00'), (2, 'Two', '2018-01-01 13:00'), (3, NULL, '2018-01-02 00:00'), (3, '', '2018-01-03 00:00'), (1, 'One', '2018-01-03 00:00'), (2, '', '2018-01-03 00:00'), (2, 'LargeTwo', '2018-01-04 00:00'), (1, '', '2018-01-04 00:00') SELECT * FROM #RawData ```
2018/03/09
['https://Stackoverflow.com/questions/49191902', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1070816/']
You haven't told the div how to handle the overflow caused by the width of the inner element. Add `overflow: auto`. ```css body { margin: 0; } .wrapper { background: yellow; overflow: auto; } h1 { width: 2000px; border: 2px solid red; } ``` ```html <!doctype html> <html> <body> <div class="wrapper"> <h1>Hello</h1> <p>More content</p> </div> <p>More content outside wrapper</p> </body> </html> ``` I do not believe that there is an obvious reason why adding `position: absolute` to the body *fixes* this. It does take body out of the document flow, but body is the container for all the content. So I would describe it as a quirk. We could describe body as being the initial constraint for the width of the content, the .wrapper. Being absolute removes this constraint. Actually, it likely remove the width constraint for any further elements on the page, so they will probably all expand to contain any inner content.
Yeah, you can use `width: fit-content;` [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/width) describes it as; > > **fit-content** > > The larger of: > > > * the intrinsic minimum width > * the smaller of the intrinsic preferred width and the available width > > > It works as expected; the containing element expands. But, as usual, IE lags behind and doesn't support it... **EDIT** To be clear; this specification is still in [Working Draft](https://drafts.csswg.org/css-box-3/#width-and-height) status, and as such should not be used in production environments (except if you don't care about Internet Explorer).
49,191,902
I have log data and I'm trying to back-fill the data as much as possible to help improve analytics. The log data contains a SessionId, which is the SessionId created by the browser, the Name of the logged in user (if they are logged in) and a LogTime. I'm trying to get all the related sessions, sessions that are within 24 hours of each other, and get the first date of that group of sessions, the last date of that group of sessions and populate the first not null and not empty name into all the other name spaces. For instance, if I had the following data: ``` --Id SessionId Name LogTime --1 1 2018-01-01 00:00 --2 1 LargeOne 2018-01-01 12:00 --3 2 Two 2018-01-01 13:00 --4 3 NULL 2018-01-02 00:00 --5 3 2018-01-03 00:00 --6 1 One 2018-01-03 00:00 --7 2 2018-01-03 00:00 --8 2 LargeTwo 2018-01-04 00:00 --9 1 2018-01-04 00:00 ``` I would like to process the data as follows: ``` --Id SessionId Name LogTime StartTime EndTime --1 1 LargeOne 2018-01-01 00:00 2018-01-01 00:00 2018-01-01 12:00 --2 1 LargeOne 2018-01-01 12:00 2018-01-01 00:00 2018-01-01 12:00 --3 2 Two 2018-01-01 13:00 2018-01-01 13:00 2018-01-01 13:00 --4 3 NULL 2018-01-02 00:00 2018-01-02 00:00 2018-01-03 00:00 --5 3 NULL 2018-01-03 00:00 2018-01-02 00:00 2018-01-03 00:00 --6 1 One 2018-01-03 00:00 2018-01-03 00:00 2018-01-04 00:00 --7 2 LargeTwo 2018-01-03 00:00 2018-01-03 00:00 2018-01-04 00:00 --8 2 LargeTwo 2018-01-04 00:00 2018-01-03 00:00 2018-01-04 00:00 --9 1 One 2018-01-04 00:00 2018-01-03 00:00 2018-01-04 00:00 ``` Ids 1 and 2 are in the same session and in range (24 hours) of each other so they make one set, notice that the Id 1 doesn't have a name column but Id 2 does and because it's part of the same set, it back fills the name. Ids 6 and 9 are also in session 1 but is not in the 24 hour range of the first set so it makes a new set, Ids 6 and 9 are both in session 1 and even though new sessions appear between them, they are still the same session within range so they make a new set. I think that covers explaining the problem, now for my attempts at finding a solution. To find and backfill the Name, I tried to use: ``` SELECT Id,SessionId, FIRST_VALUE(Name) OVER (PARTITION BY SessionId ORDER BY CASE WHEN Name IS NULL or Name='' then 0 ELSE 1 END DESC,Id) Name, LogTime FROM #RawData ORDER BY Id ``` This produces: ``` --Id SessionId Name LogTime --1 1 LargeOne 2018-01-01 00:00 --2 1 LargeOne 2018-01-01 12:00 --3 2 Two 2018-01-01 13:00 --4 3 NULL 2018-01-02 00:00 --5 3 NULL 2018-01-03 00:00 --6 1 LargeOne 2018-01-03 00:00 --7 2 Two 2018-01-03 00:00 --8 2 Two 2018-01-04 00:00 --9 1 LargeOne 2018-01-04 00:00 ``` This almost works but it doesn't take the date ranges into consideration. So I did a lot of digging as to how to get the groups based on the SessionId and date ranges and I came up with this: ``` ;WITH ProcessTable1 AS ( SELECT Id,SessionId,Name,LogTime, PreviousLogTimeInRange = CASE WHEN LAG(LogTime, 1) OVER (partition by SessionId ORDER BY LogTime) between DATEADD(day, -1, LogTime) and LogTime THEN 0 ELSE 1 END, NextLogTimeInRange = CASE WHEN Lead(LogTime,1) OVER (partition by SessionId ORDER BY LogTime) between LogTime and DATEADD(day, 1, LogTime) THEN 0 ELSE 1 END FROM #RawData ), ProcessTable2 AS ( SELECT Id, Name, SessionId, LogTime, PreviousLogTimeInRange, NextLogTime = case when NextLogTimeInRange = 0 then LEAD(LogTime, 1) OVER (partition by SessionId ORDER BY LogTime) else LogTime end FROM ProcessTable1 WHERE 1 IN (PreviousLogTimeInRange, NextLogTimeInRange) ) SELECT Id,SessionId, FIRST_VALUE(Name) OVER (PARTITION BY SessionId ORDER BY CASE WHEN Name IS NULL or Name = '' then 0 ELSE 1 END DESC, Id) Name, LogTime, NextLogTime FROM ProcessTable2 --WHERE PreviousLogTimeInRange = 1 ORDER BY id; ``` This produces: ``` --Id SessionId Name LogTime NextLogTime --1 1 LargeOne 2018-01-01 00:00 2018-01-01 12:00 --2 1 LargeOne 2018-01-01 12:00 2018-01-01 12:00 --3 2 Two 2018-01-01 13:00 2018-01-01 13:00 --4 3 NULL 2018-01-02 00:00 2018-01-03 00:00 --5 3 NULL 2018-01-03 00:00 2018-01-03 00:00 --6 1 LargeOne 2018-01-03 00:00 2018-01-04 00:00 --7 2 Two 2018-01-03 00:00 2018-01-04 00:00 --8 2 Two 2018-01-04 00:00 2018-01-04 00:00 --9 1 LargeOne 2018-01-04 00:00 2018-01-04 00:00 ``` So close, but I still need the StartTime and to be honest I'm not 100% sure this will always do what I want. The last query was in part created from the findings on [SQL Query to group items by time, but only if near each other?](https://stackoverflow.com/questions/15818604/sql-query-to-group-items-by-time-but-only-if-near-each-other) If anyone is willing to lend a hand here, I would be eternally grateful! --Edit-- I've created some data to play with if anyone wants to give it a bash. ``` IF OBJECT_ID('tempdb..#RawData') IS NOT NULL DROP TABLE #RawData GO Create Table #RawData ( Id INT IDENTITY, SessionId INT NOT NULL, Name NVARCHAR(50) NULL, LogTime DATETIME NOT NULL ) INSERT INTO #RawData(SessionId,Name,LogTime) VALUES (1, '', '2018-01-01 00:00'), (1, 'LargeOne', '2018-01-01 12:00'), (2, 'Two', '2018-01-01 13:00'), (3, NULL, '2018-01-02 00:00'), (3, '', '2018-01-03 00:00'), (1, 'One', '2018-01-03 00:00'), (2, '', '2018-01-03 00:00'), (2, 'LargeTwo', '2018-01-04 00:00'), (1, '', '2018-01-04 00:00') SELECT * FROM #RawData ```
2018/03/09
['https://Stackoverflow.com/questions/49191902', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1070816/']
Let's start with this: > > But the problem is, the parent **div.wrapper** does **not expand** to the > **width** of its contents – its yellow background only extends as far as > the width of the viewport. > > > By default a div is a block element and a block element takes up the **whole width** of it's parent container so your wrapper in this case has the width of the body which is the width of the screen. In addition to this we are facing an **overflow** as the child content width is bigger than the parent width and by default: > > Content is not clipped and may be rendered outside the padding box[ref](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow) > > > This explain why the background doesn't cover the `h1` as this one is **rendred outside**. To change this behavior we have two solutions: 1. We change the behavior of [overflow](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow) by specifing a value different from `visible` (the default one). By doing this you will also notice some changes to margin because you are also facing a **margin collapsing** (margin of `h1` and `p` are collpasing with the margin of `div.wrapper`). ```css body { margin: 0; } .wrapper { background: yellow; margin:10px 0; } h1 { width: 2000px; border: 2px solid red; } ``` ```html <div class="wrapper" style="overflow: auto;"> <h1>Hello</h1> <p>More content</p> </div> <div class="wrapper" style="overflow: hidden;"> <h1>Hello</h1> <p>More content</p> </div> <div class="wrapper" style="overflow: scroll;"> <h1>Hello</h1> <p>More content</p> </div> <p>More content outside wrapper</p> ``` 2. We change the display property of the element to something else than block. We can for example use `inline-block` or `inline-flex` and in this case the wrapper will fit the content of its element and he will **overflow** the body ```css body { margin: 0; } .wrapper { background: yellow; display: inline-block; } h1 { width: 2000px; border: 2px solid red; } ``` ```html <div class="wrapper"> <h1>Hello</h1> <p>More content</p> </div> <p>More content outside wrapper</p> ``` --- Concerning this: > > Why does setting body { position: absolute } fix the problem? > > > We all know what `position:absolute` means but the intresting part is this one: > > Most of the time, absolutely positioned elements that have height and > width **set to auto** are sized so **as to fit their contents**. However, > non-replaced, absolutely positioned elements can be made to fill the > available vertical space by specifying both top and bottom and leaving > height unspecified (that is, auto). They can likewise be made to fill > the available horizontal space by specifying both left and right and > leaving width as auto. [ref](https://developer.mozilla.org/en-US/docs/Web/CSS/position) > > >
You haven't told the div how to handle the overflow caused by the width of the inner element. Add `overflow: auto`. ```css body { margin: 0; } .wrapper { background: yellow; overflow: auto; } h1 { width: 2000px; border: 2px solid red; } ``` ```html <!doctype html> <html> <body> <div class="wrapper"> <h1>Hello</h1> <p>More content</p> </div> <p>More content outside wrapper</p> </body> </html> ``` I do not believe that there is an obvious reason why adding `position: absolute` to the body *fixes* this. It does take body out of the document flow, but body is the container for all the content. So I would describe it as a quirk. We could describe body as being the initial constraint for the width of the content, the .wrapper. Being absolute removes this constraint. Actually, it likely remove the width constraint for any further elements on the page, so they will probably all expand to contain any inner content.
49,191,902
I have log data and I'm trying to back-fill the data as much as possible to help improve analytics. The log data contains a SessionId, which is the SessionId created by the browser, the Name of the logged in user (if they are logged in) and a LogTime. I'm trying to get all the related sessions, sessions that are within 24 hours of each other, and get the first date of that group of sessions, the last date of that group of sessions and populate the first not null and not empty name into all the other name spaces. For instance, if I had the following data: ``` --Id SessionId Name LogTime --1 1 2018-01-01 00:00 --2 1 LargeOne 2018-01-01 12:00 --3 2 Two 2018-01-01 13:00 --4 3 NULL 2018-01-02 00:00 --5 3 2018-01-03 00:00 --6 1 One 2018-01-03 00:00 --7 2 2018-01-03 00:00 --8 2 LargeTwo 2018-01-04 00:00 --9 1 2018-01-04 00:00 ``` I would like to process the data as follows: ``` --Id SessionId Name LogTime StartTime EndTime --1 1 LargeOne 2018-01-01 00:00 2018-01-01 00:00 2018-01-01 12:00 --2 1 LargeOne 2018-01-01 12:00 2018-01-01 00:00 2018-01-01 12:00 --3 2 Two 2018-01-01 13:00 2018-01-01 13:00 2018-01-01 13:00 --4 3 NULL 2018-01-02 00:00 2018-01-02 00:00 2018-01-03 00:00 --5 3 NULL 2018-01-03 00:00 2018-01-02 00:00 2018-01-03 00:00 --6 1 One 2018-01-03 00:00 2018-01-03 00:00 2018-01-04 00:00 --7 2 LargeTwo 2018-01-03 00:00 2018-01-03 00:00 2018-01-04 00:00 --8 2 LargeTwo 2018-01-04 00:00 2018-01-03 00:00 2018-01-04 00:00 --9 1 One 2018-01-04 00:00 2018-01-03 00:00 2018-01-04 00:00 ``` Ids 1 and 2 are in the same session and in range (24 hours) of each other so they make one set, notice that the Id 1 doesn't have a name column but Id 2 does and because it's part of the same set, it back fills the name. Ids 6 and 9 are also in session 1 but is not in the 24 hour range of the first set so it makes a new set, Ids 6 and 9 are both in session 1 and even though new sessions appear between them, they are still the same session within range so they make a new set. I think that covers explaining the problem, now for my attempts at finding a solution. To find and backfill the Name, I tried to use: ``` SELECT Id,SessionId, FIRST_VALUE(Name) OVER (PARTITION BY SessionId ORDER BY CASE WHEN Name IS NULL or Name='' then 0 ELSE 1 END DESC,Id) Name, LogTime FROM #RawData ORDER BY Id ``` This produces: ``` --Id SessionId Name LogTime --1 1 LargeOne 2018-01-01 00:00 --2 1 LargeOne 2018-01-01 12:00 --3 2 Two 2018-01-01 13:00 --4 3 NULL 2018-01-02 00:00 --5 3 NULL 2018-01-03 00:00 --6 1 LargeOne 2018-01-03 00:00 --7 2 Two 2018-01-03 00:00 --8 2 Two 2018-01-04 00:00 --9 1 LargeOne 2018-01-04 00:00 ``` This almost works but it doesn't take the date ranges into consideration. So I did a lot of digging as to how to get the groups based on the SessionId and date ranges and I came up with this: ``` ;WITH ProcessTable1 AS ( SELECT Id,SessionId,Name,LogTime, PreviousLogTimeInRange = CASE WHEN LAG(LogTime, 1) OVER (partition by SessionId ORDER BY LogTime) between DATEADD(day, -1, LogTime) and LogTime THEN 0 ELSE 1 END, NextLogTimeInRange = CASE WHEN Lead(LogTime,1) OVER (partition by SessionId ORDER BY LogTime) between LogTime and DATEADD(day, 1, LogTime) THEN 0 ELSE 1 END FROM #RawData ), ProcessTable2 AS ( SELECT Id, Name, SessionId, LogTime, PreviousLogTimeInRange, NextLogTime = case when NextLogTimeInRange = 0 then LEAD(LogTime, 1) OVER (partition by SessionId ORDER BY LogTime) else LogTime end FROM ProcessTable1 WHERE 1 IN (PreviousLogTimeInRange, NextLogTimeInRange) ) SELECT Id,SessionId, FIRST_VALUE(Name) OVER (PARTITION BY SessionId ORDER BY CASE WHEN Name IS NULL or Name = '' then 0 ELSE 1 END DESC, Id) Name, LogTime, NextLogTime FROM ProcessTable2 --WHERE PreviousLogTimeInRange = 1 ORDER BY id; ``` This produces: ``` --Id SessionId Name LogTime NextLogTime --1 1 LargeOne 2018-01-01 00:00 2018-01-01 12:00 --2 1 LargeOne 2018-01-01 12:00 2018-01-01 12:00 --3 2 Two 2018-01-01 13:00 2018-01-01 13:00 --4 3 NULL 2018-01-02 00:00 2018-01-03 00:00 --5 3 NULL 2018-01-03 00:00 2018-01-03 00:00 --6 1 LargeOne 2018-01-03 00:00 2018-01-04 00:00 --7 2 Two 2018-01-03 00:00 2018-01-04 00:00 --8 2 Two 2018-01-04 00:00 2018-01-04 00:00 --9 1 LargeOne 2018-01-04 00:00 2018-01-04 00:00 ``` So close, but I still need the StartTime and to be honest I'm not 100% sure this will always do what I want. The last query was in part created from the findings on [SQL Query to group items by time, but only if near each other?](https://stackoverflow.com/questions/15818604/sql-query-to-group-items-by-time-but-only-if-near-each-other) If anyone is willing to lend a hand here, I would be eternally grateful! --Edit-- I've created some data to play with if anyone wants to give it a bash. ``` IF OBJECT_ID('tempdb..#RawData') IS NOT NULL DROP TABLE #RawData GO Create Table #RawData ( Id INT IDENTITY, SessionId INT NOT NULL, Name NVARCHAR(50) NULL, LogTime DATETIME NOT NULL ) INSERT INTO #RawData(SessionId,Name,LogTime) VALUES (1, '', '2018-01-01 00:00'), (1, 'LargeOne', '2018-01-01 12:00'), (2, 'Two', '2018-01-01 13:00'), (3, NULL, '2018-01-02 00:00'), (3, '', '2018-01-03 00:00'), (1, 'One', '2018-01-03 00:00'), (2, '', '2018-01-03 00:00'), (2, 'LargeTwo', '2018-01-04 00:00'), (1, '', '2018-01-04 00:00') SELECT * FROM #RawData ```
2018/03/09
['https://Stackoverflow.com/questions/49191902', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1070816/']
Let's start with this: > > But the problem is, the parent **div.wrapper** does **not expand** to the > **width** of its contents – its yellow background only extends as far as > the width of the viewport. > > > By default a div is a block element and a block element takes up the **whole width** of it's parent container so your wrapper in this case has the width of the body which is the width of the screen. In addition to this we are facing an **overflow** as the child content width is bigger than the parent width and by default: > > Content is not clipped and may be rendered outside the padding box[ref](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow) > > > This explain why the background doesn't cover the `h1` as this one is **rendred outside**. To change this behavior we have two solutions: 1. We change the behavior of [overflow](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow) by specifing a value different from `visible` (the default one). By doing this you will also notice some changes to margin because you are also facing a **margin collapsing** (margin of `h1` and `p` are collpasing with the margin of `div.wrapper`). ```css body { margin: 0; } .wrapper { background: yellow; margin:10px 0; } h1 { width: 2000px; border: 2px solid red; } ``` ```html <div class="wrapper" style="overflow: auto;"> <h1>Hello</h1> <p>More content</p> </div> <div class="wrapper" style="overflow: hidden;"> <h1>Hello</h1> <p>More content</p> </div> <div class="wrapper" style="overflow: scroll;"> <h1>Hello</h1> <p>More content</p> </div> <p>More content outside wrapper</p> ``` 2. We change the display property of the element to something else than block. We can for example use `inline-block` or `inline-flex` and in this case the wrapper will fit the content of its element and he will **overflow** the body ```css body { margin: 0; } .wrapper { background: yellow; display: inline-block; } h1 { width: 2000px; border: 2px solid red; } ``` ```html <div class="wrapper"> <h1>Hello</h1> <p>More content</p> </div> <p>More content outside wrapper</p> ``` --- Concerning this: > > Why does setting body { position: absolute } fix the problem? > > > We all know what `position:absolute` means but the intresting part is this one: > > Most of the time, absolutely positioned elements that have height and > width **set to auto** are sized so **as to fit their contents**. However, > non-replaced, absolutely positioned elements can be made to fill the > available vertical space by specifying both top and bottom and leaving > height unspecified (that is, auto). They can likewise be made to fill > the available horizontal space by specifying both left and right and > leaving width as auto. [ref](https://developer.mozilla.org/en-US/docs/Web/CSS/position) > > >
Yeah, you can use `width: fit-content;` [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/width) describes it as; > > **fit-content** > > The larger of: > > > * the intrinsic minimum width > * the smaller of the intrinsic preferred width and the available width > > > It works as expected; the containing element expands. But, as usual, IE lags behind and doesn't support it... **EDIT** To be clear; this specification is still in [Working Draft](https://drafts.csswg.org/css-box-3/#width-and-height) status, and as such should not be used in production environments (except if you don't care about Internet Explorer).
72,750
I want to write an Arduino code, that runs on several different Boards. The code can perform digitalRead/Write operations, but the pin number will be set from the user/outside. I want to include a check, if the selected pin exists. Is it possible, to read the amount of I/Os (digital and analog) of the Arduino the code is currently running on, to check if the users selection is in the given range? Or is it possible to check, if a certain pin number exists?
2020/02/24
['https://arduino.stackexchange.com/questions/72750', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/61344/']
It depends on the core, but most provide the macro `NUM_DIGITAL_PINS` which tells you the number of digital pins the board has. In general this doesn't equate to the actual number, but to one more than the highest number (there are boards with gaps in the pin number sequence). So you can use: ``` if (pinNumber < NUM_DIGITAL_PINS) { digitalWrite(pinNumber, HIGH); } else { Serial.println("Invalid pin number"); } ``` In tandem with that you also usually have `NUM_ANALOG_INPUTS`.
The number of the GPIO pins available depends on how the chip is wired on the Arduino Board and which microcontroller one is running on. For example, an Arduino Uno with a ATMega328p chip has 14 Digital I/O pins, whereas an Arduino Mega 2560 with a chip has 54 digital I/O pins.
10,754,359
I am posting this because i couldn't understand a bit how the boost tutorials work. I have a class whose objects are elements of a boost multi\_index container. I need to update the member variables of objects using member functions. I don't know how to do that. could you help me please. I prepared a simple example: ``` #include <string> #include <iostream> #include <boost/multi_index_container.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/ordered_index.hpp> #include<vector> using boost::multi_index::multi_index_container; using boost::multi_index::ordered_non_unique; using boost::multi_index::ordered_unique; using boost::multi_index::indexed_by; using boost::multi_index::member; class employee_entry { public: employee_entry( const std::string& first, const std::string& last, long id): first_name_(first), last_name_(last), id_(id) {} void change(){id_++;}//causing the problem std::string first_name_; std::string last_name_; std::vector<int> mySet; long id_; std::vector<int>::iterator mySet_begin() {return mySet.begin(); } }; typedef multi_index_container< employee_entry, indexed_by< ordered_unique<member<employee_entry, std::string, &employee_entry::first_name_> > , ordered_non_unique<member<employee_entry, std::string, &employee_entry::last_name_> > , ordered_non_unique<member<employee_entry, long, &employee_entry::id_> > > > employee_set; //employee set.... multi-index employee_set m_employees; int main() { using boost::multi_index::nth_index; using boost::multi_index::get; typedef nth_index<employee_set, 0>::type first_name_view; first_name_view& fnv = get<0>(m_employees); fnv.insert(employee_entry("John", "Smith", 110)); fnv.insert(employee_entry("Fudge", "Hunk", 97)); ///get employees sorted by id typedef nth_index<employee_set, 2>::type id_view; id_view& idv = get <2> (m_employees); for(id_view::reverse_iterator it = idv.rbegin(), it_end(idv.rend()); it != it_end; ++it) { std::cout << it->first_name_ <<" " << it->last_name_ << ":" << it->id_ << std::endl; it->change();//calling the troublesome function } return 0; } ``` the error generated is: ``` $c++ dr_function.cpp dr_function.cpp: In function ‘int main()’: dr_function.cpp:65:19: error: passing ‘const employee_entry’ as ‘this’ argument of ‘void employee_entry::change()’ discards qualifiers [-fpermissive] ```
2012/05/25
['https://Stackoverflow.com/questions/10754359', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/805896/']
The solution you posted won't work: at best it'll get a garbled index and at worst your app will crash. As your last index depends on `employee_entry::id_`, you just cannot change it liberally because you're implicitly breaking the index order. For this kind of stuff Boost.MultiIndex provides updating functions `replace` and `modify`, as discussed [here](http://www.boost.org/libs/multi_index/doc/tutorial/basics.html#ord_updating). In your particular case, you can call your `change` member function as follows: ``` idv.modify(idv.iterator_to(*it),boost::bind(&employee_entry::change,_1)); ``` A bit of explanation: `idv.iterator_to(*it)` is just converting your reverse iterator into a regular iterator, which is what `modify` needs. As for the `boost::bind` part, this encapsulates `&employee_entry::change` into a suitable modifying functor. This way, you let Boost.MultiIndex know about the upcoming change in `id_` and update the indices accordingly.
well, I am answering my question at least to debug the above mentioned code. My main concern was discussed and answered in the comments below the question. I the following code, I made `long id_` as `mutable` and changed `void change(){...}` to `void change()const{...}` ``` #include <string> #include <iostream> #include <boost/multi_index_container.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/ordered_index.hpp> #include<vector> using boost::multi_index::multi_index_container; using boost::multi_index::ordered_non_unique; using boost::multi_index::ordered_unique; using boost::multi_index::indexed_by; using boost::multi_index::member; class employee_entry { public: employee_entry( const std::string& first, const std::string& last, long id): first_name_(first), last_name_(last), id_(id) {} void change() const {id_++;}//causing the problem std::string first_name_; std::string last_name_; std::vector<int> mySet; mutable long id_; std::vector<int>::iterator mySet_begin() {return mySet.begin(); } }; typedef multi_index_container< employee_entry, indexed_by< ordered_unique<member<employee_entry, std::string, &employee_entry::first_name_> > , ordered_non_unique<member<employee_entry, std::string, &employee_entry::last_name_> > , ordered_non_unique<member<employee_entry, long, &employee_entry::id_> > > > employee_set; //employee set.... multi-index employee_set m_employees; int main() { using boost::multi_index::nth_index; using boost::multi_index::get; typedef nth_index<employee_set, 0>::type first_name_view; first_name_view& fnv = get<0>(m_employees); fnv.insert(employee_entry("John", "Smith", 110)); fnv.insert(employee_entry("Fudge", "Hunk", 97)); ///get employees sorted by id typedef nth_index<employee_set, 2>::type id_view; id_view& idv = get <2> (m_employees); for(id_view::reverse_iterator it = idv.rbegin(), it_end(idv.rend()); it != it_end; ++it) { std::cout << it->first_name_ <<" " << it->last_name_ << ":" << it->id_ << std::endl; it->change();//calling the troublesome function } return 0; } ```
18,997
In einem englischsprachigen philosophischen Artikel von Iris Marion Young, über den ich in einem Seminar sprechen werde, heißt ein Abschnitt "Parameters of Reasoning". Wie würde das ins Deutsche übersetzt? Alle Möglichkeiten scheinen mir zu mathematisch zu sein. In dem Text ("Responsibility and Global Justice") schlägt Young ein neues Model für persönliche und institutionelle Verantwortung vor. "Parameters of Reasoning" ist in Bezug auf dieses Model, das Young *social connection model* nennt - also nicht über *reasoning* selbst (keines logisch-theoretisches Thema). Es geht (nachdem das Model vorgeschlagen worden ist) darum, wie der *agent* (privat oder institutionell) seine Verantwortung betrachten sollte.
2015/01/06
['https://german.stackexchange.com/questions/18997', 'https://german.stackexchange.com', 'https://german.stackexchange.com/users/8769/']
Der Text ist [hier](https://books.google.de/books?id=aaNgZrMdx-UC&pg=PA144&lpg=PA144&dq=%22parameters%20of%20reasoning%22&source=bl&ots=JXHyfZL_dh&sig=beDdi6Gdmiy5U1awWf-sbba3QsI&hl=de&sa=X&ei=Z-KrVLHPEYbkUuiZgPAO&ved=0CE0Q6AEwBg#v=onepage&q=%22parameters%20of%20reasoning%22&f=false) und die vier Parameter sind: power, privilege, interest and collective ability. Diese vier Gesichtspunkte sollen zur Entscheidungsfindung beitragen. Vor diesem Hintergrund denke ich die beste Übersetzung für "parameter" ist: > > Kriterien > > > Das Wort "reasoning" ist ein bisschen ein Problem, da es sich schlecht treffend in einem Wort übersetzen lässt. Man könnte das Ganze > > Evaluationskriterien > > > nennen, aber das ist erstens klobig und zweitens zu sehr auf das "danach" fokussiert. Ich denke, es wäre am besten, eine Phrase mit einem der folgenden Wörter zu finden > > Fragestellungen, Anhaltspunkte, Fragen oder Aspekte > > > und das "reasoning" ganz raus zu lassen.
> > Die Grenzen der Vernunft > > > is my suggestion.
21,280,535
i have made a mistake of re-inventing the wheel. There are options but somehow i like the feel of this. Sorry but don't have enough rep to post an image. This is how the form looks like: SNO.-------ITEMS--------FROM--------TO---------QUANTITY // labels [ 1 ]-------[-----------▼]---[--------]----[--------]------[-------------] {NEW} {DELETE} //textboxes and buttons I've got the 'new' button click event to generate a row, and serial number to be automatic and inserted the items into the collections from Properties panel. Delete button deletes an entire row and shifts both the button up on Y position. I need to assign the value of quantity [(TO - FROM ) + 1] in the QUANTITY text boxes, for which i have the code as : ``` public void print_quant(object Sender, EventArgs e) { TextBox quanty; quanty = (TextBox)this.Controls.Find("QUANTITY" + (count), true)[0]; calculate_quant(this, e); quanty = result; } public static string result; public string calculate_quant(object sender, EventArgs e) { TextBox sfrom; sfrom = (TextBox)this.Controls.Find("SFRM" + count, true)[0]; TextBox sto; sto = (TextBox)this.Controls.Find("STO" + count, true)[0]; TextBox quan; quan = (TextBox)this.Controls.Find("QUANTITY" + count, true)[0]; //if (!string.IsNullOrEmpty(sfrom.Text) && !string.IsNullOrEmpty(sto.Text)) { int to = Convert.ToInt32(sto.Text); int from = Convert.ToInt32(sfrom.Text); int quantity = (to - from) + 1; result = quantity.ToString(); quan.Text = result; } return result; } ``` count is initialized at 1 on form load, keeps increasing with number of rows the same code works in the delete row method ``` public void delete_row(object sender, EventArgs e) //function to delete a row { TextBox snum; snum = (TextBox)this.Controls.Find("SNO"+count, true)[0]; snum.Dispose(); ...//delete other row elements } ``` please help me figure out why it doesnt work for the print\_quant / calculate\_quant methods
2014/01/22
['https://Stackoverflow.com/questions/21280535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2437356/']
Go to `FilterViewController.h` add a uiimage there `@property(nonatomic,strong)UIImage *dvImage;` Go to `FilterViewController.m` Synthesize it `@synthesize dvImage;` Go to the code Where you are calling the `FilterViewController` ``` FilterViewController *cvc = [segue destinationViewController]; UIImage *image = imageView.image; cvc.setDvImage = image; NSLog(@"segue"); ``` and then in `viewDidLoad` set `self.desktopview.image = dvImage;` Don't forgot to check the **segue identifier** Hope this helps
You can't do this because it isn't ready yet. ``` cvc.desktopview.image = image; ``` Instead you need to store it in a `UIImage` property and use it in `viewDidLoad` method of your destination view controller. Something like this in `prepareForSegue` ``` cvc.image = image; ``` and in the view controller ``` - (void)viewDidLoad { [super viewDidLoad]; self.desktopview.image = image; } ``` Edit: You need this at your view controller's header file. ``` @property (nonatomic, strong) UIImage * image; ```
21,280,535
i have made a mistake of re-inventing the wheel. There are options but somehow i like the feel of this. Sorry but don't have enough rep to post an image. This is how the form looks like: SNO.-------ITEMS--------FROM--------TO---------QUANTITY // labels [ 1 ]-------[-----------▼]---[--------]----[--------]------[-------------] {NEW} {DELETE} //textboxes and buttons I've got the 'new' button click event to generate a row, and serial number to be automatic and inserted the items into the collections from Properties panel. Delete button deletes an entire row and shifts both the button up on Y position. I need to assign the value of quantity [(TO - FROM ) + 1] in the QUANTITY text boxes, for which i have the code as : ``` public void print_quant(object Sender, EventArgs e) { TextBox quanty; quanty = (TextBox)this.Controls.Find("QUANTITY" + (count), true)[0]; calculate_quant(this, e); quanty = result; } public static string result; public string calculate_quant(object sender, EventArgs e) { TextBox sfrom; sfrom = (TextBox)this.Controls.Find("SFRM" + count, true)[0]; TextBox sto; sto = (TextBox)this.Controls.Find("STO" + count, true)[0]; TextBox quan; quan = (TextBox)this.Controls.Find("QUANTITY" + count, true)[0]; //if (!string.IsNullOrEmpty(sfrom.Text) && !string.IsNullOrEmpty(sto.Text)) { int to = Convert.ToInt32(sto.Text); int from = Convert.ToInt32(sfrom.Text); int quantity = (to - from) + 1; result = quantity.ToString(); quan.Text = result; } return result; } ``` count is initialized at 1 on form load, keeps increasing with number of rows the same code works in the delete row method ``` public void delete_row(object sender, EventArgs e) //function to delete a row { TextBox snum; snum = (TextBox)this.Controls.Find("SNO"+count, true)[0]; snum.Dispose(); ...//delete other row elements } ``` please help me figure out why it doesnt work for the print\_quant / calculate\_quant methods
2014/01/22
['https://Stackoverflow.com/questions/21280535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2437356/']
You can't do this because it isn't ready yet. ``` cvc.desktopview.image = image; ``` Instead you need to store it in a `UIImage` property and use it in `viewDidLoad` method of your destination view controller. Something like this in `prepareForSegue` ``` cvc.image = image; ``` and in the view controller ``` - (void)viewDidLoad { [super viewDidLoad]; self.desktopview.image = image; } ``` Edit: You need this at your view controller's header file. ``` @property (nonatomic, strong) UIImage * image; ```
Optimized way ``` [segue.destinationViewController setAnotherImage:yourImage]; ``` Another view controller ``` -(void)setAnotherImage:(UIImage *)happiness { //get your image here } ```
21,280,535
i have made a mistake of re-inventing the wheel. There are options but somehow i like the feel of this. Sorry but don't have enough rep to post an image. This is how the form looks like: SNO.-------ITEMS--------FROM--------TO---------QUANTITY // labels [ 1 ]-------[-----------▼]---[--------]----[--------]------[-------------] {NEW} {DELETE} //textboxes and buttons I've got the 'new' button click event to generate a row, and serial number to be automatic and inserted the items into the collections from Properties panel. Delete button deletes an entire row and shifts both the button up on Y position. I need to assign the value of quantity [(TO - FROM ) + 1] in the QUANTITY text boxes, for which i have the code as : ``` public void print_quant(object Sender, EventArgs e) { TextBox quanty; quanty = (TextBox)this.Controls.Find("QUANTITY" + (count), true)[0]; calculate_quant(this, e); quanty = result; } public static string result; public string calculate_quant(object sender, EventArgs e) { TextBox sfrom; sfrom = (TextBox)this.Controls.Find("SFRM" + count, true)[0]; TextBox sto; sto = (TextBox)this.Controls.Find("STO" + count, true)[0]; TextBox quan; quan = (TextBox)this.Controls.Find("QUANTITY" + count, true)[0]; //if (!string.IsNullOrEmpty(sfrom.Text) && !string.IsNullOrEmpty(sto.Text)) { int to = Convert.ToInt32(sto.Text); int from = Convert.ToInt32(sfrom.Text); int quantity = (to - from) + 1; result = quantity.ToString(); quan.Text = result; } return result; } ``` count is initialized at 1 on form load, keeps increasing with number of rows the same code works in the delete row method ``` public void delete_row(object sender, EventArgs e) //function to delete a row { TextBox snum; snum = (TextBox)this.Controls.Find("SNO"+count, true)[0]; snum.Dispose(); ...//delete other row elements } ``` please help me figure out why it doesnt work for the print\_quant / calculate\_quant methods
2014/01/22
['https://Stackoverflow.com/questions/21280535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2437356/']
Go to `FilterViewController.h` add a uiimage there `@property(nonatomic,strong)UIImage *dvImage;` Go to `FilterViewController.m` Synthesize it `@synthesize dvImage;` Go to the code Where you are calling the `FilterViewController` ``` FilterViewController *cvc = [segue destinationViewController]; UIImage *image = imageView.image; cvc.setDvImage = image; NSLog(@"segue"); ``` and then in `viewDidLoad` set `self.desktopview.image = dvImage;` Don't forgot to check the **segue identifier** Hope this helps
Optimized way ``` [segue.destinationViewController setAnotherImage:yourImage]; ``` Another view controller ``` -(void)setAnotherImage:(UIImage *)happiness { //get your image here } ```
21,280,535
i have made a mistake of re-inventing the wheel. There are options but somehow i like the feel of this. Sorry but don't have enough rep to post an image. This is how the form looks like: SNO.-------ITEMS--------FROM--------TO---------QUANTITY // labels [ 1 ]-------[-----------▼]---[--------]----[--------]------[-------------] {NEW} {DELETE} //textboxes and buttons I've got the 'new' button click event to generate a row, and serial number to be automatic and inserted the items into the collections from Properties panel. Delete button deletes an entire row and shifts both the button up on Y position. I need to assign the value of quantity [(TO - FROM ) + 1] in the QUANTITY text boxes, for which i have the code as : ``` public void print_quant(object Sender, EventArgs e) { TextBox quanty; quanty = (TextBox)this.Controls.Find("QUANTITY" + (count), true)[0]; calculate_quant(this, e); quanty = result; } public static string result; public string calculate_quant(object sender, EventArgs e) { TextBox sfrom; sfrom = (TextBox)this.Controls.Find("SFRM" + count, true)[0]; TextBox sto; sto = (TextBox)this.Controls.Find("STO" + count, true)[0]; TextBox quan; quan = (TextBox)this.Controls.Find("QUANTITY" + count, true)[0]; //if (!string.IsNullOrEmpty(sfrom.Text) && !string.IsNullOrEmpty(sto.Text)) { int to = Convert.ToInt32(sto.Text); int from = Convert.ToInt32(sfrom.Text); int quantity = (to - from) + 1; result = quantity.ToString(); quan.Text = result; } return result; } ``` count is initialized at 1 on form load, keeps increasing with number of rows the same code works in the delete row method ``` public void delete_row(object sender, EventArgs e) //function to delete a row { TextBox snum; snum = (TextBox)this.Controls.Find("SNO"+count, true)[0]; snum.Dispose(); ...//delete other row elements } ``` please help me figure out why it doesnt work for the print\_quant / calculate\_quant methods
2014/01/22
['https://Stackoverflow.com/questions/21280535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2437356/']
Go to `FilterViewController.h` add a uiimage there `@property(nonatomic,strong)UIImage *dvImage;` Go to `FilterViewController.m` Synthesize it `@synthesize dvImage;` Go to the code Where you are calling the `FilterViewController` ``` FilterViewController *cvc = [segue destinationViewController]; UIImage *image = imageView.image; cvc.setDvImage = image; NSLog(@"segue"); ``` and then in `viewDidLoad` set `self.desktopview.image = dvImage;` Don't forgot to check the **segue identifier** Hope this helps
`ViewDidLoad` is called only after ALL outlets are loaded, so never try to set outlet/views value in prepare segue method, as `viewDidLoad` will be called after prepare segue method. Now you can do one that create an UIImage property in `filterViewController` and set its value. and In `viewDidLoad` method set it to specfic `imageView`.
21,280,535
i have made a mistake of re-inventing the wheel. There are options but somehow i like the feel of this. Sorry but don't have enough rep to post an image. This is how the form looks like: SNO.-------ITEMS--------FROM--------TO---------QUANTITY // labels [ 1 ]-------[-----------▼]---[--------]----[--------]------[-------------] {NEW} {DELETE} //textboxes and buttons I've got the 'new' button click event to generate a row, and serial number to be automatic and inserted the items into the collections from Properties panel. Delete button deletes an entire row and shifts both the button up on Y position. I need to assign the value of quantity [(TO - FROM ) + 1] in the QUANTITY text boxes, for which i have the code as : ``` public void print_quant(object Sender, EventArgs e) { TextBox quanty; quanty = (TextBox)this.Controls.Find("QUANTITY" + (count), true)[0]; calculate_quant(this, e); quanty = result; } public static string result; public string calculate_quant(object sender, EventArgs e) { TextBox sfrom; sfrom = (TextBox)this.Controls.Find("SFRM" + count, true)[0]; TextBox sto; sto = (TextBox)this.Controls.Find("STO" + count, true)[0]; TextBox quan; quan = (TextBox)this.Controls.Find("QUANTITY" + count, true)[0]; //if (!string.IsNullOrEmpty(sfrom.Text) && !string.IsNullOrEmpty(sto.Text)) { int to = Convert.ToInt32(sto.Text); int from = Convert.ToInt32(sfrom.Text); int quantity = (to - from) + 1; result = quantity.ToString(); quan.Text = result; } return result; } ``` count is initialized at 1 on form load, keeps increasing with number of rows the same code works in the delete row method ``` public void delete_row(object sender, EventArgs e) //function to delete a row { TextBox snum; snum = (TextBox)this.Controls.Find("SNO"+count, true)[0]; snum.Dispose(); ...//delete other row elements } ``` please help me figure out why it doesnt work for the print\_quant / calculate\_quant methods
2014/01/22
['https://Stackoverflow.com/questions/21280535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2437356/']
`ViewDidLoad` is called only after ALL outlets are loaded, so never try to set outlet/views value in prepare segue method, as `viewDidLoad` will be called after prepare segue method. Now you can do one that create an UIImage property in `filterViewController` and set its value. and In `viewDidLoad` method set it to specfic `imageView`.
Optimized way ``` [segue.destinationViewController setAnotherImage:yourImage]; ``` Another view controller ``` -(void)setAnotherImage:(UIImage *)happiness { //get your image here } ```
35,481,633
I am having `Entity` Called `EY_Appliances` with Attributes `applianceId` ,`applianceName`,`watts`,`amountPerWatts`.Also i am Having Arrays like this: Prefrence.h ``` #define APPLIANCENAME_ARRAY @[@"Fridge",@"Microwave",@"Mixie",@"Roti Maker",@"Coffee Machine",@"Dish Washer",@"Wet Grinder",@"Electric Stove",@"Ceiling Fan",@"TV",@"Table Fan",@"Tubelight",@"Bulb",@"AC",@"Vacuum Cleaner",@"CFL",@"LED",@"Washing Machine",@"Toaster",@"Room Heater",@"Iron",@"Motor",@"Water Heater",@"Inverter / UPS",@"Air Cooler",@"Steamer / Air Fryer",@"Hair Dryer",@"Laptop",@"PC",@"Tablet",@"Router / Modem",@"Home Theatre",@"Projector",@"PS3/PS4/XBOX"] #define WATTS_ARRAY @[@"120",@"1000",@"700",@"30",@"167",@"810",@"180",@"150",@"75",@"120",@"75",@"40",@"60",@"1200",@"1400",@"20",@"6",@"300",@"1000",@"1600",@"1400",@"2400",@"1000",@"67",@"173",@"585",@"1026",@"15",@"150",@"4",@"4",@"17",@"240",@"10"] ``` DataAccessHandler.m ``` -(void)storeApplianceDetailsToEntity { NSManagedObjectContext *context = [self managedObjectContext]; for (int i=0; i<APPLIANCENAME_ARRAY.count; i++) { NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:@"EY_Appliances" inManagedObjectContext:context]; [object setValue: APPLIANCENAME_ARRAY[i] forKey:@"applianceId"]; [object setValue: APPLIANCENAME_ARRAY[i] forKey:@"applianceName"]; [object setValue: WATTS_ARRAY[i] forKey:@"watts"]; [object setValue: WATTS_ARRAY[i] forKey:@"amountPerWatts"]; } NSError *error = nil; if (![context save:&error]) { NSLog(@"Saving Failed with error %@", error); } NSLog(@"entityValue==>%@",context); } -(NSArray *) fetchApplianceDetailsFromEntity:(NSString *) entityName { NSManagedObjectContext *managedObjectContext = [self managedObjectContext]; NSFetchRequest *fetchRequest; NSEntityDescription *entityDescription; NSArray *array; fetchRequest = [[NSFetchRequest alloc] init]; entityDescription = [NSEntityDescription entityForName:entityName inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entityDescription]; array = [managedObjectContext executeFetchRequest:fetchRequest error:nil]; NSLog(@"arr==>>%@",array); return array; } ``` ViewController.m ``` -(void)viewDidLoad { DataAccessHandler *dataAccess=[[DataAccessHandler alloc]init]; [dataAccess storeApplianceDetailsToEntity]; NSArray *applianceData = [dataAccess fetchApplianceDetailsFromEntity:@"EY_Appliances"]; //How to print the applianceName,If i write Like this applianceData.applianceName,it shows error… } ``` 1.How to print the applianceName? 2.How to set the applianceId primaryKey and store the value for applianceId 1 to 34?
2016/02/18
['https://Stackoverflow.com/questions/35481633', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
So, I was testing with `Genymotion` because I couldn't get my hands on a device with `Android` 6.0 but now, that I've borrowed one, I've tested this code in that physical device and I was happy to notice that it works. Guess it's a `Genymotion` problem. Oh well, code's working. Thanks!
could you please use the following code and feed me back with result :- ``` import android.Manifest; import android.content.pm.PackageManager; import android.os.Build; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; /** * Id to identity READ_CONTACTS permission request. */ private static final int REQUEST_ACCESS_FINE_LOCATION = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // Sets the map type to be "hybrid" mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); // Add a marker in Sydney and move the camera LatLng sydney = new LatLng(-34, 151); mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney")); mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_ACCESS_FINE_LOCATION); } return; } mMap.setMyLocationEnabled(true); } /** * Callback received when a permissions request has been completed. */ @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_ACCESS_FINE_LOCATION) { if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { startActivity(getIntent()); finish(); } } } } ```
628,720
Inspired by a question I asked [here](https://math.stackexchange.com/questions/626927/how-a-group-represents-the-passage-of-time), I am rethinking about a question: > > Why heat equation is not time-reversible? > > > I don't know too much about PDE and physics but I guess there should be some "time arrow" in mathematics. Consider the following initial value problem: $$ \begin{cases} \Omega: (x,t) \in \mathbb{R} \times (0,+\infty) \\ u(x,0) = \delta(x) \\ u\_t - u\_{xx} = 0 \end{cases} $$ The solution is given by $$ u(x,t) = \frac{1}{\sqrt{4 \pi t}} \exp \Big( \frac{-x^2}{4t} \Big) $$ I remember from my undergraduate PDE course, it is different from elliptic equation which is time-reversible. If I substitute $t \mapsto -t$ and change the domain $\Omega$ to $\mathbb{R} \times (-\infty,0)$, the above solution will not satisfy the PDE $u\_t - u\_{xx}$. I know that we may recall second law of thermodynamics, but it is a physical law, not a mathematical theorem (or axioms). For a mathematical reason, there should be logical deduction from axioms to a "structure" that make heat equation different. What is the reason behind that? I also recall a second-order PDE on a domain $\Omega$: $$ A(x,y) u\_{xx} + 2B(x,y) u\_{xy} + C(x,y) u\_{yy} = W(u,u\_x,u\_y,x,y) $$ We say it is (i) parabolic if for all $x,y \in \Omega$, $B^2 - AC = 0$ (ii) hyperbolic if for all $x,y \in \Omega$, $B^2 - AC > 0$ (iii) elliptic if for all $x,y \in \Omega$, $B^2 - AC < 0$ Is it a pure analogy to conic section or there should be some structure behind that?
2014/01/06
['https://math.stackexchange.com/questions/628720', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/62765/']
The heat equation $u\_t-u\_{xx}=0$ is not time-reversible because it involves an odd-order derivative of $t$. Under time reversal $t\mapsto-t$, we get $u\_t\mapsto-u\_t$. So if $u(x,t)$ is a solution to the heat equation, then $u(x,-t)$ is a solution to a different equation, namely $-u\_t-u\_{xx}=0$. The only way for $u$ to solve both equations is if $u\_{xx}=0$ everywhere, which is not the case for most initial conditions of interest, such as your $\delta(x)$. By contrast, the wave equation $u\_{tt}-u\_{xx}$ is time-reversible because it involves only even-order derivatives of $t$. Under time reversal $t\mapsto-t$, we get $u\_{tt}\mapsto u\_{tt}$. So if $u(x,t)$ is a solution to the wave equation, then $u(x,-t)$ is also a solution to the wave equation.
If you start with a spatial heat distribution $u(x)$ at $t=0$, then the solution at $t > 0$ is infinitely-differentiable because it is averaged by a Gaussian, and the Gaussian couldn't be more smooth. You shouldn't expect to be able to undo such a process. This is a diffusion equation, and the speed of propagation is, essentially, infinite, which makes it physically unrealistic. Even with added viscosity, the process is irreversible. If you solve the heat equation numerically, then you can ask how the solution at a point on the grid depends on time. As you begin to answer this question, you find yourself looking at the paths back to the initial data, through the numerical algorithm, which can be thought of as the density of paths that refer to the initial data. In the limit of large number of grid points, this begins to look like a central limit problem and, hence, the Gaussian weighting of the initial data. This is definitely not a process you'd expect to reverse. Brownian motion can be used to look at this process of solution. Heat flow is a diffusion process, and the averaging should not be expeced to be reversible. Entropy is increasing.
628,720
Inspired by a question I asked [here](https://math.stackexchange.com/questions/626927/how-a-group-represents-the-passage-of-time), I am rethinking about a question: > > Why heat equation is not time-reversible? > > > I don't know too much about PDE and physics but I guess there should be some "time arrow" in mathematics. Consider the following initial value problem: $$ \begin{cases} \Omega: (x,t) \in \mathbb{R} \times (0,+\infty) \\ u(x,0) = \delta(x) \\ u\_t - u\_{xx} = 0 \end{cases} $$ The solution is given by $$ u(x,t) = \frac{1}{\sqrt{4 \pi t}} \exp \Big( \frac{-x^2}{4t} \Big) $$ I remember from my undergraduate PDE course, it is different from elliptic equation which is time-reversible. If I substitute $t \mapsto -t$ and change the domain $\Omega$ to $\mathbb{R} \times (-\infty,0)$, the above solution will not satisfy the PDE $u\_t - u\_{xx}$. I know that we may recall second law of thermodynamics, but it is a physical law, not a mathematical theorem (or axioms). For a mathematical reason, there should be logical deduction from axioms to a "structure" that make heat equation different. What is the reason behind that? I also recall a second-order PDE on a domain $\Omega$: $$ A(x,y) u\_{xx} + 2B(x,y) u\_{xy} + C(x,y) u\_{yy} = W(u,u\_x,u\_y,x,y) $$ We say it is (i) parabolic if for all $x,y \in \Omega$, $B^2 - AC = 0$ (ii) hyperbolic if for all $x,y \in \Omega$, $B^2 - AC > 0$ (iii) elliptic if for all $x,y \in \Omega$, $B^2 - AC < 0$ Is it a pure analogy to conic section or there should be some structure behind that?
2014/01/06
['https://math.stackexchange.com/questions/628720', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/62765/']
If you start with a spatial heat distribution $u(x)$ at $t=0$, then the solution at $t > 0$ is infinitely-differentiable because it is averaged by a Gaussian, and the Gaussian couldn't be more smooth. You shouldn't expect to be able to undo such a process. This is a diffusion equation, and the speed of propagation is, essentially, infinite, which makes it physically unrealistic. Even with added viscosity, the process is irreversible. If you solve the heat equation numerically, then you can ask how the solution at a point on the grid depends on time. As you begin to answer this question, you find yourself looking at the paths back to the initial data, through the numerical algorithm, which can be thought of as the density of paths that refer to the initial data. In the limit of large number of grid points, this begins to look like a central limit problem and, hence, the Gaussian weighting of the initial data. This is definitely not a process you'd expect to reverse. Brownian motion can be used to look at this process of solution. Heat flow is a diffusion process, and the averaging should not be expeced to be reversible. Entropy is increasing.
This is going to be more of a "Why I think it's not reversible" than a rigorous argument: At $t = 0$, let the temperature for a 1-dimensional homogeneous medium be piece-wise constant: $T(0,x) = 1$ for $x =< 0$ ; $T(0,x) = 3$ for $x > 0$ . For any value of x, as $t \to \infty$, $T(t,x) \to 2$ . Now, take any value of $t > 0$, and $T(t,x)$ will not, as a function of $x$, be identically equals 2. Numerically or analytically, you can run the heat diffusion equation backwards, to smaller values of t. But once you reach $t = 0$, you will regain the original discontinuity at $x = 0$. What does $T(0 - \epsilon,x)$ look like? I don't believe there is a reasonable answer to that.
628,720
Inspired by a question I asked [here](https://math.stackexchange.com/questions/626927/how-a-group-represents-the-passage-of-time), I am rethinking about a question: > > Why heat equation is not time-reversible? > > > I don't know too much about PDE and physics but I guess there should be some "time arrow" in mathematics. Consider the following initial value problem: $$ \begin{cases} \Omega: (x,t) \in \mathbb{R} \times (0,+\infty) \\ u(x,0) = \delta(x) \\ u\_t - u\_{xx} = 0 \end{cases} $$ The solution is given by $$ u(x,t) = \frac{1}{\sqrt{4 \pi t}} \exp \Big( \frac{-x^2}{4t} \Big) $$ I remember from my undergraduate PDE course, it is different from elliptic equation which is time-reversible. If I substitute $t \mapsto -t$ and change the domain $\Omega$ to $\mathbb{R} \times (-\infty,0)$, the above solution will not satisfy the PDE $u\_t - u\_{xx}$. I know that we may recall second law of thermodynamics, but it is a physical law, not a mathematical theorem (or axioms). For a mathematical reason, there should be logical deduction from axioms to a "structure" that make heat equation different. What is the reason behind that? I also recall a second-order PDE on a domain $\Omega$: $$ A(x,y) u\_{xx} + 2B(x,y) u\_{xy} + C(x,y) u\_{yy} = W(u,u\_x,u\_y,x,y) $$ We say it is (i) parabolic if for all $x,y \in \Omega$, $B^2 - AC = 0$ (ii) hyperbolic if for all $x,y \in \Omega$, $B^2 - AC > 0$ (iii) elliptic if for all $x,y \in \Omega$, $B^2 - AC < 0$ Is it a pure analogy to conic section or there should be some structure behind that?
2014/01/06
['https://math.stackexchange.com/questions/628720', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/62765/']
The heat equation $u\_t-u\_{xx}=0$ is not time-reversible because it involves an odd-order derivative of $t$. Under time reversal $t\mapsto-t$, we get $u\_t\mapsto-u\_t$. So if $u(x,t)$ is a solution to the heat equation, then $u(x,-t)$ is a solution to a different equation, namely $-u\_t-u\_{xx}=0$. The only way for $u$ to solve both equations is if $u\_{xx}=0$ everywhere, which is not the case for most initial conditions of interest, such as your $\delta(x)$. By contrast, the wave equation $u\_{tt}-u\_{xx}$ is time-reversible because it involves only even-order derivatives of $t$. Under time reversal $t\mapsto-t$, we get $u\_{tt}\mapsto u\_{tt}$. So if $u(x,t)$ is a solution to the wave equation, then $u(x,-t)$ is also a solution to the wave equation.
This is going to be more of a "Why I think it's not reversible" than a rigorous argument: At $t = 0$, let the temperature for a 1-dimensional homogeneous medium be piece-wise constant: $T(0,x) = 1$ for $x =< 0$ ; $T(0,x) = 3$ for $x > 0$ . For any value of x, as $t \to \infty$, $T(t,x) \to 2$ . Now, take any value of $t > 0$, and $T(t,x)$ will not, as a function of $x$, be identically equals 2. Numerically or analytically, you can run the heat diffusion equation backwards, to smaller values of t. But once you reach $t = 0$, you will regain the original discontinuity at $x = 0$. What does $T(0 - \epsilon,x)$ look like? I don't believe there is a reasonable answer to that.
53,432,769
I'm working with Xcode 10.1 (10B61) on an app that needs permission to use the microphone. (Almost) Every time I start the app from Xcode (in simulator) I get a system popup: > > "Appname" would like to access the microphone > "Privacy - Microphone Usage Description""> > > > It doesn't matter if I select "Don't Allow" or "OK". This message keeps popping up. How can I fix it? Update [fixed] ============== This issue seems to be fixed in Xcode 10.2
2018/11/22
['https://Stackoverflow.com/questions/53432769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2451537/']
After looking for a workaround this one seems to fix it for me: In Simulator go to Settings > Your App > Disable the Microphone Access Update: Not solving this issue but might be helpful: You can dismiss the popup via Esc key - that should be way faster than clicking a button
Another work around is to check if the app is running in the simulator and disable the audio code: ``` struct Platform { static var isSimulator: Bool { return TARGET_OS_SIMULATOR != 0 } } ```
53,432,769
I'm working with Xcode 10.1 (10B61) on an app that needs permission to use the microphone. (Almost) Every time I start the app from Xcode (in simulator) I get a system popup: > > "Appname" would like to access the microphone > "Privacy - Microphone Usage Description""> > > > It doesn't matter if I select "Don't Allow" or "OK". This message keeps popping up. How can I fix it? Update [fixed] ============== This issue seems to be fixed in Xcode 10.2
2018/11/22
['https://Stackoverflow.com/questions/53432769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2451537/']
You can get rid of this following this steps: 1. Go to "Security & Privacy" Settings on macOS. 2. Select "Microphone" on the left panel. 3. Uncheck the Xcode option on the right panel.
After looking for a workaround this one seems to fix it for me: In Simulator go to Settings > Your App > Disable the Microphone Access Update: Not solving this issue but might be helpful: You can dismiss the popup via Esc key - that should be way faster than clicking a button
53,432,769
I'm working with Xcode 10.1 (10B61) on an app that needs permission to use the microphone. (Almost) Every time I start the app from Xcode (in simulator) I get a system popup: > > "Appname" would like to access the microphone > "Privacy - Microphone Usage Description""> > > > It doesn't matter if I select "Don't Allow" or "OK". This message keeps popping up. How can I fix it? Update [fixed] ============== This issue seems to be fixed in Xcode 10.2
2018/11/22
['https://Stackoverflow.com/questions/53432769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2451537/']
### Edit: Unfortunately it looks like the following procedure is just a temporary fix. After some time the dialog started appearing again. Repeating the procedure fixes it for an additional period of time. --- I had the same problem and what helped in my case was disabling and then re-enabling microphone permissions in the the Simulator. **Steps to fix:** * go to Settings app in the Simulator * find your app settings page within the Settings app * disable microphone permission (or any other permission that is causing trouble) * re-enable microphone permissions After this procedure, the microphone permissions dialog stopped appearing every time I would run the app. **Note that I did run the app with the permissions disabled and navigated to the point where permissions are required before re-enabling them (but I don't think that's required).** Hope this helps, it did in my case.
Another work around is to check if the app is running in the simulator and disable the audio code: ``` struct Platform { static var isSimulator: Bool { return TARGET_OS_SIMULATOR != 0 } } ```
53,432,769
I'm working with Xcode 10.1 (10B61) on an app that needs permission to use the microphone. (Almost) Every time I start the app from Xcode (in simulator) I get a system popup: > > "Appname" would like to access the microphone > "Privacy - Microphone Usage Description""> > > > It doesn't matter if I select "Don't Allow" or "OK". This message keeps popping up. How can I fix it? Update [fixed] ============== This issue seems to be fixed in Xcode 10.2
2018/11/22
['https://Stackoverflow.com/questions/53432769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2451537/']
You can get rid of this following this steps: 1. Go to "Security & Privacy" Settings on macOS. 2. Select "Microphone" on the left panel. 3. Uncheck the Xcode option on the right panel.
Another work around is to check if the app is running in the simulator and disable the audio code: ``` struct Platform { static var isSimulator: Bool { return TARGET_OS_SIMULATOR != 0 } } ```
53,432,769
I'm working with Xcode 10.1 (10B61) on an app that needs permission to use the microphone. (Almost) Every time I start the app from Xcode (in simulator) I get a system popup: > > "Appname" would like to access the microphone > "Privacy - Microphone Usage Description""> > > > It doesn't matter if I select "Don't Allow" or "OK". This message keeps popping up. How can I fix it? Update [fixed] ============== This issue seems to be fixed in Xcode 10.2
2018/11/22
['https://Stackoverflow.com/questions/53432769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2451537/']
You can get rid of this following this steps: 1. Go to "Security & Privacy" Settings on macOS. 2. Select "Microphone" on the left panel. 3. Uncheck the Xcode option on the right panel.
### Edit: Unfortunately it looks like the following procedure is just a temporary fix. After some time the dialog started appearing again. Repeating the procedure fixes it for an additional period of time. --- I had the same problem and what helped in my case was disabling and then re-enabling microphone permissions in the the Simulator. **Steps to fix:** * go to Settings app in the Simulator * find your app settings page within the Settings app * disable microphone permission (or any other permission that is causing trouble) * re-enable microphone permissions After this procedure, the microphone permissions dialog stopped appearing every time I would run the app. **Note that I did run the app with the permissions disabled and navigated to the point where permissions are required before re-enabling them (but I don't think that's required).** Hope this helps, it did in my case.
3,326,042
**Problem:** Determine the number of positive integers such that: $$\Big[\frac{a}{2}\Big] + \Big[\frac{a}{3}\Big] + \Big[\frac{a}{5}\Big] = a$$ (where [x] is the greatest integer function) **Attempted solution:** The greatest integer function is essentially the floor function. The largest integer that is less than x. In order for three numbers to sum up to an integer, they can: * all be integers * one of them are integers and the remaining two add up to become an integer If a is even, then $$\Big[\frac{a}{2}\Big]$$ is also even and we could remove the floor function, since the result is an even integer. This is not possible of a is odd. Similar method can be used for the others, assuming they are divisible by 3 and divisible by 5. I am not entirely sure how to continue. I thought about replacing a with $2n$ or $2n+1$ in the two different scenarios, but I am not sure that will work since it looks like it just reduces to $a = 0$. There does not seem to be a general solution methodology for floor functions in the same way that there are for the absolute value function? The number of positive integers turns out to be 30 according to Wolfram Alpha, which is suspiciously identical to $5\*3\*2 = 30$ This would perhaps indicate that one should put the left-hand side together on the same fraction, but I am not entirely clear how this is done with floor functions.
2019/08/17
['https://math.stackexchange.com/questions/3326042', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/203291/']
$$ \frac{a}{2} + \frac{a}{3} + \frac{a}{5}-3<\Big[\frac{a}{2}\Big] + \Big[\frac{a}{3}\Big] + \Big[\frac{a}{5}\Big]=a\leq \frac{a}{2} + \frac{a}{3} + \frac{a}{5}$$
Hint: use $$x-1<[x]\leq x$$ then you get $$ \frac{a}{2} + \frac{a}{3} + \frac{a}{5}-3\leq a\leq \frac{a}{2} + \frac{a}{3} + \frac{a}{5}$$ I get 29 solutions...
3,326,042
**Problem:** Determine the number of positive integers such that: $$\Big[\frac{a}{2}\Big] + \Big[\frac{a}{3}\Big] + \Big[\frac{a}{5}\Big] = a$$ (where [x] is the greatest integer function) **Attempted solution:** The greatest integer function is essentially the floor function. The largest integer that is less than x. In order for three numbers to sum up to an integer, they can: * all be integers * one of them are integers and the remaining two add up to become an integer If a is even, then $$\Big[\frac{a}{2}\Big]$$ is also even and we could remove the floor function, since the result is an even integer. This is not possible of a is odd. Similar method can be used for the others, assuming they are divisible by 3 and divisible by 5. I am not entirely sure how to continue. I thought about replacing a with $2n$ or $2n+1$ in the two different scenarios, but I am not sure that will work since it looks like it just reduces to $a = 0$. There does not seem to be a general solution methodology for floor functions in the same way that there are for the absolute value function? The number of positive integers turns out to be 30 according to Wolfram Alpha, which is suspiciously identical to $5\*3\*2 = 30$ This would perhaps indicate that one should put the left-hand side together on the same fraction, but I am not entirely clear how this is done with floor functions.
2019/08/17
['https://math.stackexchange.com/questions/3326042', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/203291/']
Hint: use $$x-1<[x]\leq x$$ then you get $$ \frac{a}{2} + \frac{a}{3} + \frac{a}{5}-3\leq a\leq \frac{a}{2} + \frac{a}{3} + \frac{a}{5}$$ I get 29 solutions...
**Hint** Let $a=30k+r$ where $k\in \Bbb N\cup\{0\}$ and $0\le r<30$. Therefore$$31k+\Big[\frac{r}{2}\Big] + \Big[\frac{r}{3}\Big] + \Big[\frac{r}{5}\Big] = 30k+r$$or$$k+\Big[\frac{r}{2}\Big] + \Big[\frac{r}{3}\Big] + \Big[\frac{r}{5}\Big] = r$$
3,326,042
**Problem:** Determine the number of positive integers such that: $$\Big[\frac{a}{2}\Big] + \Big[\frac{a}{3}\Big] + \Big[\frac{a}{5}\Big] = a$$ (where [x] is the greatest integer function) **Attempted solution:** The greatest integer function is essentially the floor function. The largest integer that is less than x. In order for three numbers to sum up to an integer, they can: * all be integers * one of them are integers and the remaining two add up to become an integer If a is even, then $$\Big[\frac{a}{2}\Big]$$ is also even and we could remove the floor function, since the result is an even integer. This is not possible of a is odd. Similar method can be used for the others, assuming they are divisible by 3 and divisible by 5. I am not entirely sure how to continue. I thought about replacing a with $2n$ or $2n+1$ in the two different scenarios, but I am not sure that will work since it looks like it just reduces to $a = 0$. There does not seem to be a general solution methodology for floor functions in the same way that there are for the absolute value function? The number of positive integers turns out to be 30 according to Wolfram Alpha, which is suspiciously identical to $5\*3\*2 = 30$ This would perhaps indicate that one should put the left-hand side together on the same fraction, but I am not entirely clear how this is done with floor functions.
2019/08/17
['https://math.stackexchange.com/questions/3326042', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/203291/']
Hint: use $$x-1<[x]\leq x$$ then you get $$ \frac{a}{2} + \frac{a}{3} + \frac{a}{5}-3\leq a\leq \frac{a}{2} + \frac{a}{3} + \frac{a}{5}$$ I get 29 solutions...
Sorry,I just made a mistake. I think the answer is 30. when a=2k,$k\in N$; Compared to$a\over2$+$a\over3$+$a\over5$,the left side may less $i\over3$+$j\over5$(i=0,1,2;j=0,1,2,3,4), so there are 1x3x5-1=14 numbers fitting it.(Because what the left side less will equal to($a\over2$+$a\over3$+$a\over5$-$a$) ,and i,j cannot equals to 0 at the same time as $a\neq0$) when a=2k+1,$k\in N$; Compared to$a\over2$+$a\over3$+$a\over5$,the left side may less $1\over2$+$i\over3$+$j\over5$(i=0,1,2;j=0,1,2,3,4),so there are 1x3x5=15 numbers fitting it. Above all,14+15=29 numbers.
3,326,042
**Problem:** Determine the number of positive integers such that: $$\Big[\frac{a}{2}\Big] + \Big[\frac{a}{3}\Big] + \Big[\frac{a}{5}\Big] = a$$ (where [x] is the greatest integer function) **Attempted solution:** The greatest integer function is essentially the floor function. The largest integer that is less than x. In order for three numbers to sum up to an integer, they can: * all be integers * one of them are integers and the remaining two add up to become an integer If a is even, then $$\Big[\frac{a}{2}\Big]$$ is also even and we could remove the floor function, since the result is an even integer. This is not possible of a is odd. Similar method can be used for the others, assuming they are divisible by 3 and divisible by 5. I am not entirely sure how to continue. I thought about replacing a with $2n$ or $2n+1$ in the two different scenarios, but I am not sure that will work since it looks like it just reduces to $a = 0$. There does not seem to be a general solution methodology for floor functions in the same way that there are for the absolute value function? The number of positive integers turns out to be 30 according to Wolfram Alpha, which is suspiciously identical to $5\*3\*2 = 30$ This would perhaps indicate that one should put the left-hand side together on the same fraction, but I am not entirely clear how this is done with floor functions.
2019/08/17
['https://math.stackexchange.com/questions/3326042', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/203291/']
Hint: use $$x-1<[x]\leq x$$ then you get $$ \frac{a}{2} + \frac{a}{3} + \frac{a}{5}-3\leq a\leq \frac{a}{2} + \frac{a}{3} + \frac{a}{5}$$ I get 29 solutions...
Since $$ \left\lfloor x \right\rfloor = x - \left\{ x \right\}\quad \left| {\,0 \le \left\{ x \right\} < 1} \right. $$ then the equation becomes $$ \eqalign{ & 0 = \left\lfloor {{a \over 2}} \right\rfloor + \left\lfloor {{a \over 3}} \right\rfloor + \left\lfloor {{a \over 5}} \right\rfloor - a = \cr & = {a \over 2} + {a \over 3} + {a \over 5} - a - \left\{ {{a \over 2}} \right\} - \left\{ {{a \over 3}} \right\} - \left\{ {{a \over 5}} \right\} = \cr & = {a \over {30}} - \left\{ {{a \over 2}} \right\} - \left\{ {{a \over 3}} \right\} - \left\{ {{a \over 5}} \right\} \cr} $$ Actually, for integral $a$, we have $$ \left\{ {{a \over 2}} \right\} \le {1 \over 2},\quad \left\{ {{a \over 3}} \right\} \le {2 \over 3},\quad \left\{ {{a \over 5}} \right\} \le {4 \over 5} $$ so a first result we get $$ {a \over {30}} = \left\{ {{a \over 2}} \right\} + \left\{ {{a \over 3}} \right\} + \left\{ {{a \over 5}} \right\}\quad \Rightarrow \quad 0 \le a < 90 $$ Consider values of $a$ which are multiples of the three factors $$ \eqalign{ & {{2b} \over {30}} = \left\{ {{{2b} \over 3}} \right\} + \left\{ {{{2b} \over 5}} \right\} \le \left\{ {{2 \over 3}} \right\} + \left\{ {{4 \over 5}} \right\} = {{22} \over {15}}\quad \Rightarrow \quad 0 \le a\_{\,mult2} \le 44 \cr & {{3c} \over {30}} = \left\{ {{{3c} \over 2}} \right\} + \left\{ {{{3c} \over 5}} \right\} \le \left\{ {{1 \over 2}} \right\} + \left\{ {{3 \over 5}} \right\} = {{11} \over {10}}\quad \Rightarrow \quad 0 \le a\_{\,mult3} \le 33 \cr & {{5d} \over {30}} = \left\{ {{{5d} \over 2}} \right\} + \left\{ {{{5d} \over 3}} \right\} \le \left\{ {{1 \over 2}} \right\} + \left\{ {{2 \over 3}} \right\} = {5 \over 6}\quad \Rightarrow \quad 0 \le a\_{\,mult5} \le 25 \cr} $$ which means that you can do some sieving in testing the values of $a$ from $0$ to $59$.
3,326,042
**Problem:** Determine the number of positive integers such that: $$\Big[\frac{a}{2}\Big] + \Big[\frac{a}{3}\Big] + \Big[\frac{a}{5}\Big] = a$$ (where [x] is the greatest integer function) **Attempted solution:** The greatest integer function is essentially the floor function. The largest integer that is less than x. In order for three numbers to sum up to an integer, they can: * all be integers * one of them are integers and the remaining two add up to become an integer If a is even, then $$\Big[\frac{a}{2}\Big]$$ is also even and we could remove the floor function, since the result is an even integer. This is not possible of a is odd. Similar method can be used for the others, assuming they are divisible by 3 and divisible by 5. I am not entirely sure how to continue. I thought about replacing a with $2n$ or $2n+1$ in the two different scenarios, but I am not sure that will work since it looks like it just reduces to $a = 0$. There does not seem to be a general solution methodology for floor functions in the same way that there are for the absolute value function? The number of positive integers turns out to be 30 according to Wolfram Alpha, which is suspiciously identical to $5\*3\*2 = 30$ This would perhaps indicate that one should put the left-hand side together on the same fraction, but I am not entirely clear how this is done with floor functions.
2019/08/17
['https://math.stackexchange.com/questions/3326042', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/203291/']
$$ \frac{a}{2} + \frac{a}{3} + \frac{a}{5}-3<\Big[\frac{a}{2}\Big] + \Big[\frac{a}{3}\Big] + \Big[\frac{a}{5}\Big]=a\leq \frac{a}{2} + \frac{a}{3} + \frac{a}{5}$$
**Hint** Let $a=30k+r$ where $k\in \Bbb N\cup\{0\}$ and $0\le r<30$. Therefore$$31k+\Big[\frac{r}{2}\Big] + \Big[\frac{r}{3}\Big] + \Big[\frac{r}{5}\Big] = 30k+r$$or$$k+\Big[\frac{r}{2}\Big] + \Big[\frac{r}{3}\Big] + \Big[\frac{r}{5}\Big] = r$$
3,326,042
**Problem:** Determine the number of positive integers such that: $$\Big[\frac{a}{2}\Big] + \Big[\frac{a}{3}\Big] + \Big[\frac{a}{5}\Big] = a$$ (where [x] is the greatest integer function) **Attempted solution:** The greatest integer function is essentially the floor function. The largest integer that is less than x. In order for three numbers to sum up to an integer, they can: * all be integers * one of them are integers and the remaining two add up to become an integer If a is even, then $$\Big[\frac{a}{2}\Big]$$ is also even and we could remove the floor function, since the result is an even integer. This is not possible of a is odd. Similar method can be used for the others, assuming they are divisible by 3 and divisible by 5. I am not entirely sure how to continue. I thought about replacing a with $2n$ or $2n+1$ in the two different scenarios, but I am not sure that will work since it looks like it just reduces to $a = 0$. There does not seem to be a general solution methodology for floor functions in the same way that there are for the absolute value function? The number of positive integers turns out to be 30 according to Wolfram Alpha, which is suspiciously identical to $5\*3\*2 = 30$ This would perhaps indicate that one should put the left-hand side together on the same fraction, but I am not entirely clear how this is done with floor functions.
2019/08/17
['https://math.stackexchange.com/questions/3326042', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/203291/']
$$ \frac{a}{2} + \frac{a}{3} + \frac{a}{5}-3<\Big[\frac{a}{2}\Big] + \Big[\frac{a}{3}\Big] + \Big[\frac{a}{5}\Big]=a\leq \frac{a}{2} + \frac{a}{3} + \frac{a}{5}$$
Sorry,I just made a mistake. I think the answer is 30. when a=2k,$k\in N$; Compared to$a\over2$+$a\over3$+$a\over5$,the left side may less $i\over3$+$j\over5$(i=0,1,2;j=0,1,2,3,4), so there are 1x3x5-1=14 numbers fitting it.(Because what the left side less will equal to($a\over2$+$a\over3$+$a\over5$-$a$) ,and i,j cannot equals to 0 at the same time as $a\neq0$) when a=2k+1,$k\in N$; Compared to$a\over2$+$a\over3$+$a\over5$,the left side may less $1\over2$+$i\over3$+$j\over5$(i=0,1,2;j=0,1,2,3,4),so there are 1x3x5=15 numbers fitting it. Above all,14+15=29 numbers.
3,326,042
**Problem:** Determine the number of positive integers such that: $$\Big[\frac{a}{2}\Big] + \Big[\frac{a}{3}\Big] + \Big[\frac{a}{5}\Big] = a$$ (where [x] is the greatest integer function) **Attempted solution:** The greatest integer function is essentially the floor function. The largest integer that is less than x. In order for three numbers to sum up to an integer, they can: * all be integers * one of them are integers and the remaining two add up to become an integer If a is even, then $$\Big[\frac{a}{2}\Big]$$ is also even and we could remove the floor function, since the result is an even integer. This is not possible of a is odd. Similar method can be used for the others, assuming they are divisible by 3 and divisible by 5. I am not entirely sure how to continue. I thought about replacing a with $2n$ or $2n+1$ in the two different scenarios, but I am not sure that will work since it looks like it just reduces to $a = 0$. There does not seem to be a general solution methodology for floor functions in the same way that there are for the absolute value function? The number of positive integers turns out to be 30 according to Wolfram Alpha, which is suspiciously identical to $5\*3\*2 = 30$ This would perhaps indicate that one should put the left-hand side together on the same fraction, but I am not entirely clear how this is done with floor functions.
2019/08/17
['https://math.stackexchange.com/questions/3326042', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/203291/']
$$ \frac{a}{2} + \frac{a}{3} + \frac{a}{5}-3<\Big[\frac{a}{2}\Big] + \Big[\frac{a}{3}\Big] + \Big[\frac{a}{5}\Big]=a\leq \frac{a}{2} + \frac{a}{3} + \frac{a}{5}$$
Since $$ \left\lfloor x \right\rfloor = x - \left\{ x \right\}\quad \left| {\,0 \le \left\{ x \right\} < 1} \right. $$ then the equation becomes $$ \eqalign{ & 0 = \left\lfloor {{a \over 2}} \right\rfloor + \left\lfloor {{a \over 3}} \right\rfloor + \left\lfloor {{a \over 5}} \right\rfloor - a = \cr & = {a \over 2} + {a \over 3} + {a \over 5} - a - \left\{ {{a \over 2}} \right\} - \left\{ {{a \over 3}} \right\} - \left\{ {{a \over 5}} \right\} = \cr & = {a \over {30}} - \left\{ {{a \over 2}} \right\} - \left\{ {{a \over 3}} \right\} - \left\{ {{a \over 5}} \right\} \cr} $$ Actually, for integral $a$, we have $$ \left\{ {{a \over 2}} \right\} \le {1 \over 2},\quad \left\{ {{a \over 3}} \right\} \le {2 \over 3},\quad \left\{ {{a \over 5}} \right\} \le {4 \over 5} $$ so a first result we get $$ {a \over {30}} = \left\{ {{a \over 2}} \right\} + \left\{ {{a \over 3}} \right\} + \left\{ {{a \over 5}} \right\}\quad \Rightarrow \quad 0 \le a < 90 $$ Consider values of $a$ which are multiples of the three factors $$ \eqalign{ & {{2b} \over {30}} = \left\{ {{{2b} \over 3}} \right\} + \left\{ {{{2b} \over 5}} \right\} \le \left\{ {{2 \over 3}} \right\} + \left\{ {{4 \over 5}} \right\} = {{22} \over {15}}\quad \Rightarrow \quad 0 \le a\_{\,mult2} \le 44 \cr & {{3c} \over {30}} = \left\{ {{{3c} \over 2}} \right\} + \left\{ {{{3c} \over 5}} \right\} \le \left\{ {{1 \over 2}} \right\} + \left\{ {{3 \over 5}} \right\} = {{11} \over {10}}\quad \Rightarrow \quad 0 \le a\_{\,mult3} \le 33 \cr & {{5d} \over {30}} = \left\{ {{{5d} \over 2}} \right\} + \left\{ {{{5d} \over 3}} \right\} \le \left\{ {{1 \over 2}} \right\} + \left\{ {{2 \over 3}} \right\} = {5 \over 6}\quad \Rightarrow \quad 0 \le a\_{\,mult5} \le 25 \cr} $$ which means that you can do some sieving in testing the values of $a$ from $0$ to $59$.
654,064
If I have some servers set to static high performance mode, is there a way to generate a report on what power savings mode would have done, if it were enabled? I am looking to generate reports of the form, on this day we used this many kWh that we didn't really need to, summed across the estate. Or an alternate method to do this?
2014/12/21
['https://serverfault.com/questions/654064', 'https://serverfault.com', 'https://serverfault.com/users/58037/']
I'm unaware of any current server that holds this data and provides estimates based on it's history, nor any upcoming servers that do so. The only way to get close to a real answer would be to test it yourself with a power meter over a period of time with both settings. That said I buy HP servers and their 'balanced' power profile is expected to save at least 15% of power draw over their 'maximum performance' option.
Measure it on typical servers and calculate that on this base. And/or ask your hardware manufactorer. Recent servers should be equipped with online power consumption measurement means and even statistics. (e.g. Dell PowerEdge x9xx or Rxxx models)
1,514,342
Is there a way to tell R# to apply different naming strategy for property backing fields (\_camelCase) vs class instance fields (camelCase)? Reason: I want my dependencies to be named just a any other variable. Especially if the type of the field is the same as the field name. For example ``` private readonly MetaService metaService; ```
2009/10/03
['https://Stackoverflow.com/questions/1514342', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/103682/']
No, I don't know of a way to do this. Frankly, I don't understand the distinction. 1. A private instance field may later be used as the backing field for a property. Would you then feel it necessary to change the name of that field? 2. The property may become disused and may then be removed. Do you then want to rename the field? It would no longer be a backing field.
The naming convention for a property backing field should be the same as that for a class instance field. The only difference between the two is that one can be manipulated or accessed from the outside. If you feel the need to make a distinction, add a comment.
19,552,059
I'm trying to write my own apply function using variate template. Here is the code I have: ``` template<typename...> struct types{ }; template<typename T, typename... Args> struct Func{ template<typename F, typanem... Types> T call(F f, std::tuple<Types...>& params, Args... args){ return _call(f, params, types<Types...>{}, args...); } template<typename F, typename Tuple, typename Head, typename... Tail, typename... Args> T _call(F f, Tuple& t, types<Head, Tail...>, Args&&... args){ _call(f, t, types<Tail...>{}, std::forward<Args>(args)..., std::get<sizeof...(Arg)>(t).DrawSample())); } T _call(F f, Tuple& t, types<>, Args... vs){ return f(vs...) } }; ``` I can compile and run the above code without any difficulty. Now I want to make the function call(...) being invoked lazily. In other words, I can first construct the function by passing in all parameters needed for the computation: ``` int getMax(float f1, float f2, float f3){ if(f1 >= f2 && f1 >= f3){ return 1; } if(f2 >= f1 && f2 >= f3){ return 2; } if(f3 >= f1 && f3 >= f2){ return 3; } } Func<int> func; //Gaussian(mu, sd) is an object which can generate random values based on Gaussian //distribution described with mu(mean) and sd(standard deviation). Gaussian *g1 = Gaussian(0.3, 0.2); Gaussian *g2 = Gaussian(0.2, 0.3); Gaussian *g3 = Gaussian(0.3, 0.3); func.setCall(getMax, std::make_tuple(*g1, *g2, *g3); cout<<func.DrawSample(); ``` After constructing the function, I hope to get the result of the getMax() function lazily each time I make a query for func.DrawSample(). Under the hood, perhaps DrawSample() calls call(...). However, is there anyway for me to change the code above in order to create a setCall(...) whose purpose is to store everything needed for later function calls? Please let me know if my question is still unclear. Thanks a lot for your help!
2013/10/23
['https://Stackoverflow.com/questions/19552059', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2913077/']
Your problem is, that without braces, the `if` applies *only* to the following statement: ``` if (q >= 0) e[q] = w; r[q] = w; // <---- here you get ArrayIndexOutOfBound Exception ``` add braces like: ``` if (q >= 0){ e[q] = w; r[q] = w; } ```
Put the opening and closing braces for the if condition.
19,552,059
I'm trying to write my own apply function using variate template. Here is the code I have: ``` template<typename...> struct types{ }; template<typename T, typename... Args> struct Func{ template<typename F, typanem... Types> T call(F f, std::tuple<Types...>& params, Args... args){ return _call(f, params, types<Types...>{}, args...); } template<typename F, typename Tuple, typename Head, typename... Tail, typename... Args> T _call(F f, Tuple& t, types<Head, Tail...>, Args&&... args){ _call(f, t, types<Tail...>{}, std::forward<Args>(args)..., std::get<sizeof...(Arg)>(t).DrawSample())); } T _call(F f, Tuple& t, types<>, Args... vs){ return f(vs...) } }; ``` I can compile and run the above code without any difficulty. Now I want to make the function call(...) being invoked lazily. In other words, I can first construct the function by passing in all parameters needed for the computation: ``` int getMax(float f1, float f2, float f3){ if(f1 >= f2 && f1 >= f3){ return 1; } if(f2 >= f1 && f2 >= f3){ return 2; } if(f3 >= f1 && f3 >= f2){ return 3; } } Func<int> func; //Gaussian(mu, sd) is an object which can generate random values based on Gaussian //distribution described with mu(mean) and sd(standard deviation). Gaussian *g1 = Gaussian(0.3, 0.2); Gaussian *g2 = Gaussian(0.2, 0.3); Gaussian *g3 = Gaussian(0.3, 0.3); func.setCall(getMax, std::make_tuple(*g1, *g2, *g3); cout<<func.DrawSample(); ``` After constructing the function, I hope to get the result of the getMax() function lazily each time I make a query for func.DrawSample(). Under the hood, perhaps DrawSample() calls call(...). However, is there anyway for me to change the code above in order to create a setCall(...) whose purpose is to store everything needed for later function calls? Please let me know if my question is still unclear. Thanks a lot for your help!
2013/10/23
['https://Stackoverflow.com/questions/19552059', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2913077/']
Your problem is, that without braces, the `if` applies *only* to the following statement: ``` if (q >= 0) e[q] = w; r[q] = w; // <---- here you get ArrayIndexOutOfBound Exception ``` add braces like: ``` if (q >= 0){ e[q] = w; r[q] = w; } ```
Error is happening in following line: r[q] = w; As this out of if block, value of q is `-1` which is causing the error. Move it into if block: ``` if (q >= 0){ e[q] = w; r[q] = w; } ``` Cheers !!
19,552,059
I'm trying to write my own apply function using variate template. Here is the code I have: ``` template<typename...> struct types{ }; template<typename T, typename... Args> struct Func{ template<typename F, typanem... Types> T call(F f, std::tuple<Types...>& params, Args... args){ return _call(f, params, types<Types...>{}, args...); } template<typename F, typename Tuple, typename Head, typename... Tail, typename... Args> T _call(F f, Tuple& t, types<Head, Tail...>, Args&&... args){ _call(f, t, types<Tail...>{}, std::forward<Args>(args)..., std::get<sizeof...(Arg)>(t).DrawSample())); } T _call(F f, Tuple& t, types<>, Args... vs){ return f(vs...) } }; ``` I can compile and run the above code without any difficulty. Now I want to make the function call(...) being invoked lazily. In other words, I can first construct the function by passing in all parameters needed for the computation: ``` int getMax(float f1, float f2, float f3){ if(f1 >= f2 && f1 >= f3){ return 1; } if(f2 >= f1 && f2 >= f3){ return 2; } if(f3 >= f1 && f3 >= f2){ return 3; } } Func<int> func; //Gaussian(mu, sd) is an object which can generate random values based on Gaussian //distribution described with mu(mean) and sd(standard deviation). Gaussian *g1 = Gaussian(0.3, 0.2); Gaussian *g2 = Gaussian(0.2, 0.3); Gaussian *g3 = Gaussian(0.3, 0.3); func.setCall(getMax, std::make_tuple(*g1, *g2, *g3); cout<<func.DrawSample(); ``` After constructing the function, I hope to get the result of the getMax() function lazily each time I make a query for func.DrawSample(). Under the hood, perhaps DrawSample() calls call(...). However, is there anyway for me to change the code above in order to create a setCall(...) whose purpose is to store everything needed for later function calls? Please let me know if my question is still unclear. Thanks a lot for your help!
2013/10/23
['https://Stackoverflow.com/questions/19552059', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2913077/']
Your problem is, that without braces, the `if` applies *only* to the following statement: ``` if (q >= 0) e[q] = w; r[q] = w; // <---- here you get ArrayIndexOutOfBound Exception ``` add braces like: ``` if (q >= 0){ e[q] = w; r[q] = w; } ```
You call method Ext with parameter `q` with value `-1`. Then you accesing the `r[q] = w;` with -1 which is not defined (array of size 5 is defined on index 0-4). Why you accesing that? ``` if (q >= 0) e[q] = w; r[q] = w; ``` This means that if-statement is only compared for the `e[q] = w;` If you want to have all the code covered by if-statement, you need add braces. If no braces are in if-statement, only the first task is connected to that if : ``` if (q >= 0){ e[q] = w; r[q] = w; } ```
19,552,059
I'm trying to write my own apply function using variate template. Here is the code I have: ``` template<typename...> struct types{ }; template<typename T, typename... Args> struct Func{ template<typename F, typanem... Types> T call(F f, std::tuple<Types...>& params, Args... args){ return _call(f, params, types<Types...>{}, args...); } template<typename F, typename Tuple, typename Head, typename... Tail, typename... Args> T _call(F f, Tuple& t, types<Head, Tail...>, Args&&... args){ _call(f, t, types<Tail...>{}, std::forward<Args>(args)..., std::get<sizeof...(Arg)>(t).DrawSample())); } T _call(F f, Tuple& t, types<>, Args... vs){ return f(vs...) } }; ``` I can compile and run the above code without any difficulty. Now I want to make the function call(...) being invoked lazily. In other words, I can first construct the function by passing in all parameters needed for the computation: ``` int getMax(float f1, float f2, float f3){ if(f1 >= f2 && f1 >= f3){ return 1; } if(f2 >= f1 && f2 >= f3){ return 2; } if(f3 >= f1 && f3 >= f2){ return 3; } } Func<int> func; //Gaussian(mu, sd) is an object which can generate random values based on Gaussian //distribution described with mu(mean) and sd(standard deviation). Gaussian *g1 = Gaussian(0.3, 0.2); Gaussian *g2 = Gaussian(0.2, 0.3); Gaussian *g3 = Gaussian(0.3, 0.3); func.setCall(getMax, std::make_tuple(*g1, *g2, *g3); cout<<func.DrawSample(); ``` After constructing the function, I hope to get the result of the getMax() function lazily each time I make a query for func.DrawSample(). Under the hood, perhaps DrawSample() calls call(...). However, is there anyway for me to change the code above in order to create a setCall(...) whose purpose is to store everything needed for later function calls? Please let me know if my question is still unclear. Thanks a lot for your help!
2013/10/23
['https://Stackoverflow.com/questions/19552059', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2913077/']
Put the opening and closing braces for the if condition.
Error is happening in following line: r[q] = w; As this out of if block, value of q is `-1` which is causing the error. Move it into if block: ``` if (q >= 0){ e[q] = w; r[q] = w; } ``` Cheers !!
19,552,059
I'm trying to write my own apply function using variate template. Here is the code I have: ``` template<typename...> struct types{ }; template<typename T, typename... Args> struct Func{ template<typename F, typanem... Types> T call(F f, std::tuple<Types...>& params, Args... args){ return _call(f, params, types<Types...>{}, args...); } template<typename F, typename Tuple, typename Head, typename... Tail, typename... Args> T _call(F f, Tuple& t, types<Head, Tail...>, Args&&... args){ _call(f, t, types<Tail...>{}, std::forward<Args>(args)..., std::get<sizeof...(Arg)>(t).DrawSample())); } T _call(F f, Tuple& t, types<>, Args... vs){ return f(vs...) } }; ``` I can compile and run the above code without any difficulty. Now I want to make the function call(...) being invoked lazily. In other words, I can first construct the function by passing in all parameters needed for the computation: ``` int getMax(float f1, float f2, float f3){ if(f1 >= f2 && f1 >= f3){ return 1; } if(f2 >= f1 && f2 >= f3){ return 2; } if(f3 >= f1 && f3 >= f2){ return 3; } } Func<int> func; //Gaussian(mu, sd) is an object which can generate random values based on Gaussian //distribution described with mu(mean) and sd(standard deviation). Gaussian *g1 = Gaussian(0.3, 0.2); Gaussian *g2 = Gaussian(0.2, 0.3); Gaussian *g3 = Gaussian(0.3, 0.3); func.setCall(getMax, std::make_tuple(*g1, *g2, *g3); cout<<func.DrawSample(); ``` After constructing the function, I hope to get the result of the getMax() function lazily each time I make a query for func.DrawSample(). Under the hood, perhaps DrawSample() calls call(...). However, is there anyway for me to change the code above in order to create a setCall(...) whose purpose is to store everything needed for later function calls? Please let me know if my question is still unclear. Thanks a lot for your help!
2013/10/23
['https://Stackoverflow.com/questions/19552059', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2913077/']
Put the opening and closing braces for the if condition.
You call method Ext with parameter `q` with value `-1`. Then you accesing the `r[q] = w;` with -1 which is not defined (array of size 5 is defined on index 0-4). Why you accesing that? ``` if (q >= 0) e[q] = w; r[q] = w; ``` This means that if-statement is only compared for the `e[q] = w;` If you want to have all the code covered by if-statement, you need add braces. If no braces are in if-statement, only the first task is connected to that if : ``` if (q >= 0){ e[q] = w; r[q] = w; } ```
73,438,985
I'm trying to send an email from Google Sheets to update staff if they have filled a particular form out. The emails I need to be sent are sitting in the google sheet with the finish the form. If there are 5 emails in the sheet, I need a draught email sent to them with a link attached. I know you can send an email based on a value in a cell but I need an email sent to addresses that appear in the sheet. ***Example*** [email protected] [email protected] [email protected] *SEND LINK* The Apps Script needs to pick up those 3 emails and send the link I need them to receive.
2022/08/21
['https://Stackoverflow.com/questions/73438985', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16903576/']
### A simple Example ``` function sendEmIfTheyreThere() { const ss = SpreadsheetApp.getActive(); const sh = ss.getSheetByName("Sheet0"); const vs = sh.getDataRange().getValues(); vs.forEach((r,i)=> {//for loop using arrow notation if(r[0] && r[1] && r[2] && !r[3]) {//look for truthiness of column1,column2 and column3 and the falsiness of column4 GmailApp.sendEmail(r[0],r[1],r[3]);//send email sh.getRange(i + 1,4).setValue("SENT")//put sent into column 4 to prevent emails for this row being sent again } }); } ``` Sheet0: | TO | FROM | MESSAGE | SENT | | --- | --- | --- | --- | | comma separated emails | single email | Text | |
Since you know how to send emails to a cell, you could jam all the addresses into a cell with `textjoin`, and separate them with `;` That would setup your addresses to send to... So say in cell `C1` you could put `=TEXTJOIN(";",true,A:A)` (assuming column a has addresses). Then you would have your addresses just as a single cell with... ``` var addressesToSend = SpreadsheetApp.getActiveSheet().getRange('C1').getValue(); ``` The alternative method would be to use app scripts to create an array and then join them, but if you've never done that before, I'd go with the textjoin approach.
63,401,726
I have a line of images and when I hover over an image, I want it to enlarge and overlap the other images. The way I did it, when I move the mouse over it, the row is all disfigured: [![enter image description here](https://i.stack.imgur.com/QmNBz.png)](https://i.stack.imgur.com/QmNBz.png) [![enter image description here](https://i.stack.imgur.com/4H0v9.png)](https://i.stack.imgur.com/4H0v9.png) code: ``` <div> <p>Fotos do anúncio</p> {row.images.map((image, key) => ( <img className="imagesTable" src={image.url} /> ))} </div> ``` style: ``` .imagesTable { width: 50px !important; height: 50px !important; margin-right: 10px !important; margin-top: 5px !important; &:hover { width: 200px !important; height: 200px !important; object-fit: cover; } } ```
2020/08/13
['https://Stackoverflow.com/questions/63401726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8365573/']
As someone else has commented, the way to do this would be to use `transform:scale(2)` on `&:hover` - adjusting the number as necessary. This should avoid any layout shift, and it will be more performant than animating the width as you are currently doing. See this article: <https://pqina.nl/blog/animating-width-and-height-without-the-squish-effect/>
I did it like this and it worked: [![enter image description here](https://i.stack.imgur.com/q57W4.png)](https://i.stack.imgur.com/q57W4.png) [![enter image description here](https://i.stack.imgur.com/8Q24s.png)](https://i.stack.imgur.com/8Q24s.png) code: ``` <div> <p>Fotos do anúncio</p> <div className="images"> {row.images.map((image, key) => ( <div className="image-container"> <img src={image.url} alt="Imagem anúncio" /> </div> ))} </div> </div> ``` style: ``` .images { display: flex; overflow: hidden; transition: all 1.2s ease; margin-top: -15px; } .image-container { position: relative; display: flex; img { width: 50px; height: 50px; -moz-transition: all 0.3s; -webkit-transition: all 0.3s; transition: all 0.3s; } } .image-container:not(:nth-child(1)) { position: relative; margin-left: -15px; } .image-container:hover { z-index: 1000; img { width: 170px; height: 200px; cursor: pointer; } } ```
35,983,961
I am using `CefSharp.Wpf` to display my Angular SPA in WPF. My authentication is based on JWT tokens, which are stored in browser local storage. I call dialog with CefSharp and login (save JWT in local storage). Then, I want my c# app to be able to make api calls to protected resources of API. For that purpose I need to retrieve token from local storage and add it in request headers. But I can not find the way to get data from local storage using my client c# code. How can I implement this?
2016/03/14
['https://Stackoverflow.com/questions/35983961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2866189/']
`CEF` doesn't provide any `API` for this, so you can use `JS` or manupulate your `.localstorage` file on disk with use of `sqlLite`. I have achieved manipulation of `LocalStorage` with calling `JS` code. This article has helped a lot: <https://blog.logrocket.com/the-complete-guide-to-using-localstorage-in-javascript-apps-ba44edb53a36/> In my case ``` var _browser = new ChromiumWebBrowser(); ``` JS wrappers: ``` public void RunJavascript(string script) { //semicolumn at the end is not needed, multiple semicolons don't cause error _browser.GetMainFrame().ExecuteJavaScriptAsync(script); } public dynamic RunEvaluateJavascript(string script) { string scriptTemplate = @"(function () { return " + script + ";" + "})();"; Task<JavascriptResponse> t = _browser.GetMainFrame().EvaluateScriptAsync(scriptTemplate); t.Wait(); return t.Result.Result; } public string RunEvaluateJavascriptToString(string script) { var res = RunEvaluateJavascript(script); return res == null ? null : res.ToString(); } ``` LocalStorage functions: ``` public Dictionary<string, string> GetAllLocalStorageVariables() { dynamic res = RunEvaluateJavascript("{ ...localStorage };"); Dictionary<string, string> dictRes = null; try { var dictTmp = new Dictionary<string, object>(res); dictRes = dictTmp.ToDictionary(k => k.Key, k => k.Value.ToString()); } catch { return null; } return dictRes; } public string GetLocalStorageValue(string key) { return RunEvaluateJavascriptToString($"window.localStorage.getItem('{key}');"); } public void SetLocalStorageVariable(string key, string value) { RunJavascript($"window.localStorage.setItem('{key}', '{value}');"); } public void ClearLocalStorage() { RunJavascript("window.localStorage.clear();"); } public void RemoveLocalStorageKey(string key) { RunJavascript($"window.localStorage.removeItem('{key}');"); } ```
I also encountered this problem, which is the result of my research. First, `CEF` does not provide such a function of `API`. But we can use JavaScript object binding to realize this function. step 1:in c# Register a JavaScript object like this: ``` JavascriptObjectRepository.Register("localStorage_hook", LocalStorage); ``` Some ways to implement storage, such as ``` public object GetItem (string host, string key); ``` setp 2: in javascript Delete the original localStorage object, like this: ``` cefSharp.deleteBoundObject ('localStorage'); ``` and bind our object ``` cefSharp.bindObjectAsync('localStorage_hook'); ``` set 3: in javascrti Create a Proxy object to transfer and implement the attributes and methods of localStorage, like this: ``` localStorage = new Proxy({ get length() { return localStorage_hook.getItemsCount(location.origin); }, key: function (idx) { return localStorage_hook.getKey(location.origin, idx); }, getItem: function (key) {return localStorage_hook.getItem(location.origin, key);}, setItem: function (key, value) {return localStorage_hook.setItem(location.origin, key, value);}, removeItem: function (key) {return localStorage_hook.removeItem(location.origin, key);}, clear: function () {return localStorage_hook.clearItems(location.origin);} }, { get(obj, name) { if (obj[name]) { return obj[name]; } else { return obj.getItem(name); } }, set(obj, name, value) { obj.setItem(name, value); } }); ```
30,472,618
I am trying to check if in a square matrix there is more than one true value in all possible diagonals and anti-diagonals, and return true, otherwise false. So far I have tried as following but is not covering all possible diagonals: ``` n=8; %matrix dimension 8 x 8 diag= sum(A(1:n+1:end)); d1=diag>=2; antiDiag=sum(A(n:n-1:end)); d2=antiDiag>=2; if ~any(d1(:)) || ~any(d2(:)) res= true; else res=false; end ``` this is a false: ``` 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 ``` this is a true: ``` 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` Since these are my first steps in using Matlab, is there a specific function or a better way to achieve the result I am looking for?
2015/05/27
['https://Stackoverflow.com/questions/30472618', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2280374/']
**One approach:** ``` n=8; %// size of square matrix A = logical(randi(2,n)-1); %// Create a logical matrix of 0s and 1s d1 = sum(A(1:n+1:end)); %// sum all the values of Main diagonal d2 = sum(A(n:n-1:end-1)); %// sum all the values of Main anti-diag result = d1>=2 | d2>=2 %// result is true when any one of them is > than or = to 2 ``` **Sample run:** **Inputs:** ``` >> A A = 0 1 1 1 1 0 1 0 0 1 1 1 1 1 0 0 0 1 0 1 1 0 0 1 0 1 1 0 1 1 0 0 0 1 0 1 1 0 0 1 1 0 0 0 1 1 0 1 1 1 1 1 1 1 0 0 1 1 1 1 0 0 0 1 ``` **Output:** ``` result = 1 ``` **Note:** This approach considers only the Main diag and Main Anti-Diag (considering the example you provided). If you want for all possible diags, [the other answer from Luis Mendo](https://stackoverflow.com/a/30476454/2111163) is the way to go
Using @Santhan Salai's generating technique, we can use the `diag` function (to pull out the main diagonal of the matrix), the `fliplr` to flip over the center column and `any` to reduced to a single value. ``` n=8; %// size of square matrix A = logical(randi(2,n)-1); %// Create a logical matrix of 0s and 1s any([diag(A) ; diag(fliplr(A))]) ```
30,472,618
I am trying to check if in a square matrix there is more than one true value in all possible diagonals and anti-diagonals, and return true, otherwise false. So far I have tried as following but is not covering all possible diagonals: ``` n=8; %matrix dimension 8 x 8 diag= sum(A(1:n+1:end)); d1=diag>=2; antiDiag=sum(A(n:n-1:end)); d2=antiDiag>=2; if ~any(d1(:)) || ~any(d2(:)) res= true; else res=false; end ``` this is a false: ``` 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 ``` this is a true: ``` 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` Since these are my first steps in using Matlab, is there a specific function or a better way to achieve the result I am looking for?
2015/05/27
['https://Stackoverflow.com/questions/30472618', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2280374/']
To detect if there are more than one nonzero value in *any* diagonal or anti-diagonal (not just the main diagonal and antidiagonal): get the row and column indices of nonzero values, `ii` and `jj`; and then check if any value of `ii-jj` (diagonals) or `ii+jj` (anti-diagonals) is repeated: ``` [ii, jj] = find(A); res = (numel(unique(ii-jj)) < numel(ii)) || (numel(unique(ii+jj)) < numel(ii)); ```
**One approach:** ``` n=8; %// size of square matrix A = logical(randi(2,n)-1); %// Create a logical matrix of 0s and 1s d1 = sum(A(1:n+1:end)); %// sum all the values of Main diagonal d2 = sum(A(n:n-1:end-1)); %// sum all the values of Main anti-diag result = d1>=2 | d2>=2 %// result is true when any one of them is > than or = to 2 ``` **Sample run:** **Inputs:** ``` >> A A = 0 1 1 1 1 0 1 0 0 1 1 1 1 1 0 0 0 1 0 1 1 0 0 1 0 1 1 0 1 1 0 0 0 1 0 1 1 0 0 1 1 0 0 0 1 1 0 1 1 1 1 1 1 1 0 0 1 1 1 1 0 0 0 1 ``` **Output:** ``` result = 1 ``` **Note:** This approach considers only the Main diag and Main Anti-Diag (considering the example you provided). If you want for all possible diags, [the other answer from Luis Mendo](https://stackoverflow.com/a/30476454/2111163) is the way to go
30,472,618
I am trying to check if in a square matrix there is more than one true value in all possible diagonals and anti-diagonals, and return true, otherwise false. So far I have tried as following but is not covering all possible diagonals: ``` n=8; %matrix dimension 8 x 8 diag= sum(A(1:n+1:end)); d1=diag>=2; antiDiag=sum(A(n:n-1:end)); d2=antiDiag>=2; if ~any(d1(:)) || ~any(d2(:)) res= true; else res=false; end ``` this is a false: ``` 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 ``` this is a true: ``` 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` Since these are my first steps in using Matlab, is there a specific function or a better way to achieve the result I am looking for?
2015/05/27
['https://Stackoverflow.com/questions/30472618', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2280374/']
To detect if there are more than one nonzero value in *any* diagonal or anti-diagonal (not just the main diagonal and antidiagonal): get the row and column indices of nonzero values, `ii` and `jj`; and then check if any value of `ii-jj` (diagonals) or `ii+jj` (anti-diagonals) is repeated: ``` [ii, jj] = find(A); res = (numel(unique(ii-jj)) < numel(ii)) || (numel(unique(ii+jj)) < numel(ii)); ```
Using @Santhan Salai's generating technique, we can use the `diag` function (to pull out the main diagonal of the matrix), the `fliplr` to flip over the center column and `any` to reduced to a single value. ``` n=8; %// size of square matrix A = logical(randi(2,n)-1); %// Create a logical matrix of 0s and 1s any([diag(A) ; diag(fliplr(A))]) ```
61,823,205
I have this Elastic query: ``` "aggs":{ "GroupByDomeinRelatieCode":{ "aggs":{ "SumNettoRegelBedrag":{ "sum":{ "script": { "lang": "painless", "source": "doc['nettoRegelbedrag'].value * (100 - doc['uitgesteldeKortingsPercentage'].value) / 100 " } } } }, "terms":{ "field":"domeinRelatieCode.keyword", "size":10000 } }, "TotalSumAggragation":{ "sum":{ "script": { "lang": "painless", "source": "doc['nettoRegelbedrag'].value * (100 - doc['uitgesteldeKortingsPercentage'].value) / 100 " } } } } ``` And I need to convert it to C# Nest with object initializer. My current code: ``` var aggs = new AggregationDictionary() { { "GroupByDomeinRelatieCode" , new TermsAggregation("GroupByDomeinRelatieCode") { Field = Infer.Field<ElasticInvoiceLine>(x => x.DomeinRelatieCode.Suffix("keyword")), Size = 10000, Aggregations = new SumAggregation("SumNettoRegelBedrag", ADD SCRIPT HERE?) } }, { "TotalSumAggragation", new SumAggregation("TotalSumAggragation", ADD SCRIPT HERE?)} }; ``` I have tried to use ScriptQuery and ScriptField but the SumAggregation won't accept it. ``` var script = new ScriptQuery { Name = "UitgesteldeKorting", Script = new InlineScript("doc['nettoRegelbedrag'].value * (100 - doc['uitgesteldeKortingsPercentage'].value) / 100") { Lang = "painless" }, }; var scriptField = new ScriptField() { Script = new InlineScript("doc['nettoRegelbedrag'].value * (100 - doc['uitgesteldeKortingsPercentage'].value) / 100") { Lang = "painless" } }; ``` I don't know how to add the script part to the SumAggregations. How can I do this? Thx!
2020/05/15
['https://Stackoverflow.com/questions/61823205', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/731127/']
You can pass the script via `Script` property, like this ``` Aggregations = new SumAggregation("SumNettoRegelBedrag", null) { Script = new InlineScript("") } ``` Hope that helps.
Can you try this one? ``` { "aggs": { "GroupByDomeinRelatieCode": { "aggs": { "SumNettoRegelBedrag": { "sum": { "script": "doc['nettoRegelbedrag'].value * (100 - doc['uitgesteldeKortingsPercentage'].value) / 100 " } } }, "terms": { "field": "domeinRelatieCode.keyword", "size": 10000 } }, "TotalSumAggragation": { "sum": { "script": "doc['nettoRegelbedrag'].value * (100 - doc['uitgesteldeKortingsPercentage'].value) / 100 " } } } } ```
2,062,522
The question that I saw is as follows: > > In the Parliament of Sikinia, each member has at most three enemies. Prove that the house can be separated into two houses, so that each member has at most one enemy in his own house. > > > I built a graph where each person corresponds to a vertex and there is an edge between them if the two are enemies. Then I tried to color the vertices of the graph using two colors and remove edges that were between vertices of different colors. The goal is to arrive at a graph with max degree 1. I tried a couple of examples. It seems to workout fine, but I don't know how to prove it.
2016/12/17
['https://math.stackexchange.com/questions/2062522', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/314798/']
Split the house however you like. Let $E\_i$ be the number of enemies person $i$ has in their group, and let $E = \sum E\_i.$ For any person having more than $1$ enemy in their group, i.e. at least $2$, move them to the other group, where they will have at most $1$ enemy. This decreases $E.$ Since $E$ is always non-negative, this process must end eventually, at which point the desired configuration is reached.
I will give a counter-example for the case where the enemy relationship is not assumed to be symmetric (but is assumed to be irreflexive). Imagine four kingdoms called North, South, East, and West. Each kingdom has many citizens and a king and a pretender to the throne (actually, the pretender to the throne might be the only citizen, awkward). The enemies of each citizen are the three foreign kings. The enemies of each king are the two next counterclockwise kings (North's enemy is West and South) as well as his pretender to the throne (each king has an enemy within his own kingdom). Now let's first consider how to divide the kings. Clearly they can't go all in the same group. Also, if it is a 3-1 split, then two of the three may be happy because they hate the singleton, but the third of the three will hate the other two in the three, so a 3-1 split will not work. Now let's consider a 2-2 split, where the kingdoms pair off into two alliances. This may work for the kings, but we will need to make one observation: for either alliance, one of the king hates the other king (and possibly they both hate each other). For example, North is either paired with West or South, who North hates, or with East who hates North. Now lets consider the placement of everyone else. Everyone besides the kings (including the pretenders) hate the three other kings. So each citizen has to be in his own kings alliance (because there are two enemy kings in the other alliance). But now finally we get to a contradiction. In each alliance, there is a king who is allied with a king he hates. But then this king also hates the pretender in his own kingdom. Thus he has two people he hates. User cardboard\_box found a simplification. In addition to the other citizens besides the pretenders being unnecessary, it can actually be the case that all the pretenders are one and the same, and they don't need to hate anybody. But since he is taking the role of all the pretenders, all the kings hate him. But now which alliance can he go in? As before, both alliances have a king who hates the other king in the alliance, and all kings hate the pretender, so he cannot go in either alliance, a contradiction. Thus only five people are necessary to provide a counterexample.
2,062,522
The question that I saw is as follows: > > In the Parliament of Sikinia, each member has at most three enemies. Prove that the house can be separated into two houses, so that each member has at most one enemy in his own house. > > > I built a graph where each person corresponds to a vertex and there is an edge between them if the two are enemies. Then I tried to color the vertices of the graph using two colors and remove edges that were between vertices of different colors. The goal is to arrive at a graph with max degree 1. I tried a couple of examples. It seems to workout fine, but I don't know how to prove it.
2016/12/17
['https://math.stackexchange.com/questions/2062522', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/314798/']
Split the house however you like. Let $E\_i$ be the number of enemies person $i$ has in their group, and let $E = \sum E\_i.$ For any person having more than $1$ enemy in their group, i.e. at least $2$, move them to the other group, where they will have at most $1$ enemy. This decreases $E.$ Since $E$ is always non-negative, this process must end eventually, at which point the desired configuration is reached.
The question is ambiguous in two ways: we are not told whether being an enemy is a symmetric or asymmetric relation, nor whether the parliament has a finite or infinite number of members. I will show that the assertion is false for asymmetric relations, even in the finite case; in fact, I give an (asymmetric) example of $15$ people, each having only $2$ enemies, who can't be divided into two groups in which each member has at most one enemy. On the other hand, if the relation is symmetric, the assertion is true even in the infinite case. **An asymmetric counterexample.** There are $15$ people, call them $x\_i,y\_i,y'\_i,z\_i,z'\_i\ (i=0,1,2).$ The enemies of $x\_i$ are $y\_i,y'\_i;$ the enemies of $y\_i,y'\_i$ are $z\_i,z'\_i;$ the enemies of $z\_i,z'\_i$ are $x\_i,x\_{i+1}$ (addition modulo $3$). Let each of the $15$ people be colored red or blue. Then at least two among $x\_0,x\_1,x\_2$ have the same color; without loss of generality, suppose that $x\_0,x\_1$ are red. If either $z\_0$ or $z'\_0$ is red, then we have a red person with two red enemies; so we may assume that $z\_0,z'\_0$ are blue. If either $y\_0$ or $y'\_0$ is blue, then we have a blue person with two blue enemies; so we may assume that $y\_0,y'\_0$ are red. But then $x\_0$ is a red person with two red enemies. **The finite symmetric case.** (Already proved in the [answer](https://math.stackexchange.com/questions/2062522/each-person-has-at-most-3-enemies-in-a-group-show-that-we-can-separate-them-int/2062534#2062534) by @cats, repeated here for convenience.) If $G=(V,E)$ is a finite *undirected* graph with maximum degree at most $3,$ then the vertex set $V$ can be partitioned into two sets $V\_1,V\_2$ so that, for $i=1,2,$ each vertex in $V\_i$ has at most one neighbor (i.e. "enemy") in $V\_i.$ This can be done by choosing a partition which maximizes the number of edges with one endpoint in $\_1$ and the other in $V\_2.$ (This argument does not work if $V$ is infinite.) **The infinite symmetric case.** If $G=(V,E)$ is any (not necessarily finite) undirected graph with maximum degree at most $3,$ then the vertex set $V$ can be partitioned into two sets $V\_1,V\_2$ so that, for $i=1,2,$ each vertex in $V\_i$ has at most one neighbor in $V\_i.$ This follows from the finite case by the usual sort of compactness argument, i.e., using the fact that the [Tychonoff product](https://en.wikipedia.org/wiki/Tychonoff%27s_theorem) of any family of finite spaces is compact. **More generally,** let $k$ be a positive integer and let $d\_1,\dots,d\_k$ be nonnegative integers. If $G=(V,E)$ is any (not necessarily finite) undirected graph with maximum degree at most $d\_1+\cdots+d\_k+k-1$, then the vertex set $V$ can be partitioned into $k$ sets $V\_1,\dots,V\_k$ so that, for each $i=1,\dots,k$, each vertex in $V\_i$ has at most $d\_i$ neighbors in $V\_i$. **Proof.** We may assume that $G$ is a finite graph and that $k=2$; the general case will then follow by induction on $k$ and a compactness argument. Let $d\_1,d\_2$ be nonnegative integers, and let $G=(V,E)$ be a finite graph with maximum degree at most $d\_1+d\_2+1$. Let $\{V\_1,V\_2\}$ be a partition of $V$ which minimizes the quantity $(d\_2+1)e\_1+(d\_1+1)e\_2$ where $e\_i$ is the number of edges joining two vertices in $V\_i$. Then each vertex in $V\_i$ has at most $d\_i$ neighbors in $V\_i$.
2,062,522
The question that I saw is as follows: > > In the Parliament of Sikinia, each member has at most three enemies. Prove that the house can be separated into two houses, so that each member has at most one enemy in his own house. > > > I built a graph where each person corresponds to a vertex and there is an edge between them if the two are enemies. Then I tried to color the vertices of the graph using two colors and remove edges that were between vertices of different colors. The goal is to arrive at a graph with max degree 1. I tried a couple of examples. It seems to workout fine, but I don't know how to prove it.
2016/12/17
['https://math.stackexchange.com/questions/2062522', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/314798/']
Split the house however you like. Let $E\_i$ be the number of enemies person $i$ has in their group, and let $E = \sum E\_i.$ For any person having more than $1$ enemy in their group, i.e. at least $2$, move them to the other group, where they will have at most $1$ enemy. This decreases $E.$ Since $E$ is always non-negative, this process must end eventually, at which point the desired configuration is reached.
Let's separate it into two houses, House A and House B. If person $1$ has two or more enemies in House A, then we put him or her in House B. Then we take care of person $2$, etc. After just finitely many house changes (because we don't have infinitely many people), we can get each member to have at most one enemy in his or her house.
2,062,522
The question that I saw is as follows: > > In the Parliament of Sikinia, each member has at most three enemies. Prove that the house can be separated into two houses, so that each member has at most one enemy in his own house. > > > I built a graph where each person corresponds to a vertex and there is an edge between them if the two are enemies. Then I tried to color the vertices of the graph using two colors and remove edges that were between vertices of different colors. The goal is to arrive at a graph with max degree 1. I tried a couple of examples. It seems to workout fine, but I don't know how to prove it.
2016/12/17
['https://math.stackexchange.com/questions/2062522', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/314798/']
The question is ambiguous in two ways: we are not told whether being an enemy is a symmetric or asymmetric relation, nor whether the parliament has a finite or infinite number of members. I will show that the assertion is false for asymmetric relations, even in the finite case; in fact, I give an (asymmetric) example of $15$ people, each having only $2$ enemies, who can't be divided into two groups in which each member has at most one enemy. On the other hand, if the relation is symmetric, the assertion is true even in the infinite case. **An asymmetric counterexample.** There are $15$ people, call them $x\_i,y\_i,y'\_i,z\_i,z'\_i\ (i=0,1,2).$ The enemies of $x\_i$ are $y\_i,y'\_i;$ the enemies of $y\_i,y'\_i$ are $z\_i,z'\_i;$ the enemies of $z\_i,z'\_i$ are $x\_i,x\_{i+1}$ (addition modulo $3$). Let each of the $15$ people be colored red or blue. Then at least two among $x\_0,x\_1,x\_2$ have the same color; without loss of generality, suppose that $x\_0,x\_1$ are red. If either $z\_0$ or $z'\_0$ is red, then we have a red person with two red enemies; so we may assume that $z\_0,z'\_0$ are blue. If either $y\_0$ or $y'\_0$ is blue, then we have a blue person with two blue enemies; so we may assume that $y\_0,y'\_0$ are red. But then $x\_0$ is a red person with two red enemies. **The finite symmetric case.** (Already proved in the [answer](https://math.stackexchange.com/questions/2062522/each-person-has-at-most-3-enemies-in-a-group-show-that-we-can-separate-them-int/2062534#2062534) by @cats, repeated here for convenience.) If $G=(V,E)$ is a finite *undirected* graph with maximum degree at most $3,$ then the vertex set $V$ can be partitioned into two sets $V\_1,V\_2$ so that, for $i=1,2,$ each vertex in $V\_i$ has at most one neighbor (i.e. "enemy") in $V\_i.$ This can be done by choosing a partition which maximizes the number of edges with one endpoint in $\_1$ and the other in $V\_2.$ (This argument does not work if $V$ is infinite.) **The infinite symmetric case.** If $G=(V,E)$ is any (not necessarily finite) undirected graph with maximum degree at most $3,$ then the vertex set $V$ can be partitioned into two sets $V\_1,V\_2$ so that, for $i=1,2,$ each vertex in $V\_i$ has at most one neighbor in $V\_i.$ This follows from the finite case by the usual sort of compactness argument, i.e., using the fact that the [Tychonoff product](https://en.wikipedia.org/wiki/Tychonoff%27s_theorem) of any family of finite spaces is compact. **More generally,** let $k$ be a positive integer and let $d\_1,\dots,d\_k$ be nonnegative integers. If $G=(V,E)$ is any (not necessarily finite) undirected graph with maximum degree at most $d\_1+\cdots+d\_k+k-1$, then the vertex set $V$ can be partitioned into $k$ sets $V\_1,\dots,V\_k$ so that, for each $i=1,\dots,k$, each vertex in $V\_i$ has at most $d\_i$ neighbors in $V\_i$. **Proof.** We may assume that $G$ is a finite graph and that $k=2$; the general case will then follow by induction on $k$ and a compactness argument. Let $d\_1,d\_2$ be nonnegative integers, and let $G=(V,E)$ be a finite graph with maximum degree at most $d\_1+d\_2+1$. Let $\{V\_1,V\_2\}$ be a partition of $V$ which minimizes the quantity $(d\_2+1)e\_1+(d\_1+1)e\_2$ where $e\_i$ is the number of edges joining two vertices in $V\_i$. Then each vertex in $V\_i$ has at most $d\_i$ neighbors in $V\_i$.
I will give a counter-example for the case where the enemy relationship is not assumed to be symmetric (but is assumed to be irreflexive). Imagine four kingdoms called North, South, East, and West. Each kingdom has many citizens and a king and a pretender to the throne (actually, the pretender to the throne might be the only citizen, awkward). The enemies of each citizen are the three foreign kings. The enemies of each king are the two next counterclockwise kings (North's enemy is West and South) as well as his pretender to the throne (each king has an enemy within his own kingdom). Now let's first consider how to divide the kings. Clearly they can't go all in the same group. Also, if it is a 3-1 split, then two of the three may be happy because they hate the singleton, but the third of the three will hate the other two in the three, so a 3-1 split will not work. Now let's consider a 2-2 split, where the kingdoms pair off into two alliances. This may work for the kings, but we will need to make one observation: for either alliance, one of the king hates the other king (and possibly they both hate each other). For example, North is either paired with West or South, who North hates, or with East who hates North. Now lets consider the placement of everyone else. Everyone besides the kings (including the pretenders) hate the three other kings. So each citizen has to be in his own kings alliance (because there are two enemy kings in the other alliance). But now finally we get to a contradiction. In each alliance, there is a king who is allied with a king he hates. But then this king also hates the pretender in his own kingdom. Thus he has two people he hates. User cardboard\_box found a simplification. In addition to the other citizens besides the pretenders being unnecessary, it can actually be the case that all the pretenders are one and the same, and they don't need to hate anybody. But since he is taking the role of all the pretenders, all the kings hate him. But now which alliance can he go in? As before, both alliances have a king who hates the other king in the alliance, and all kings hate the pretender, so he cannot go in either alliance, a contradiction. Thus only five people are necessary to provide a counterexample.
2,062,522
The question that I saw is as follows: > > In the Parliament of Sikinia, each member has at most three enemies. Prove that the house can be separated into two houses, so that each member has at most one enemy in his own house. > > > I built a graph where each person corresponds to a vertex and there is an edge between them if the two are enemies. Then I tried to color the vertices of the graph using two colors and remove edges that were between vertices of different colors. The goal is to arrive at a graph with max degree 1. I tried a couple of examples. It seems to workout fine, but I don't know how to prove it.
2016/12/17
['https://math.stackexchange.com/questions/2062522', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/314798/']
I will give a counter-example for the case where the enemy relationship is not assumed to be symmetric (but is assumed to be irreflexive). Imagine four kingdoms called North, South, East, and West. Each kingdom has many citizens and a king and a pretender to the throne (actually, the pretender to the throne might be the only citizen, awkward). The enemies of each citizen are the three foreign kings. The enemies of each king are the two next counterclockwise kings (North's enemy is West and South) as well as his pretender to the throne (each king has an enemy within his own kingdom). Now let's first consider how to divide the kings. Clearly they can't go all in the same group. Also, if it is a 3-1 split, then two of the three may be happy because they hate the singleton, but the third of the three will hate the other two in the three, so a 3-1 split will not work. Now let's consider a 2-2 split, where the kingdoms pair off into two alliances. This may work for the kings, but we will need to make one observation: for either alliance, one of the king hates the other king (and possibly they both hate each other). For example, North is either paired with West or South, who North hates, or with East who hates North. Now lets consider the placement of everyone else. Everyone besides the kings (including the pretenders) hate the three other kings. So each citizen has to be in his own kings alliance (because there are two enemy kings in the other alliance). But now finally we get to a contradiction. In each alliance, there is a king who is allied with a king he hates. But then this king also hates the pretender in his own kingdom. Thus he has two people he hates. User cardboard\_box found a simplification. In addition to the other citizens besides the pretenders being unnecessary, it can actually be the case that all the pretenders are one and the same, and they don't need to hate anybody. But since he is taking the role of all the pretenders, all the kings hate him. But now which alliance can he go in? As before, both alliances have a king who hates the other king in the alliance, and all kings hate the pretender, so he cannot go in either alliance, a contradiction. Thus only five people are necessary to provide a counterexample.
Let's separate it into two houses, House A and House B. If person $1$ has two or more enemies in House A, then we put him or her in House B. Then we take care of person $2$, etc. After just finitely many house changes (because we don't have infinitely many people), we can get each member to have at most one enemy in his or her house.
2,062,522
The question that I saw is as follows: > > In the Parliament of Sikinia, each member has at most three enemies. Prove that the house can be separated into two houses, so that each member has at most one enemy in his own house. > > > I built a graph where each person corresponds to a vertex and there is an edge between them if the two are enemies. Then I tried to color the vertices of the graph using two colors and remove edges that were between vertices of different colors. The goal is to arrive at a graph with max degree 1. I tried a couple of examples. It seems to workout fine, but I don't know how to prove it.
2016/12/17
['https://math.stackexchange.com/questions/2062522', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/314798/']
The question is ambiguous in two ways: we are not told whether being an enemy is a symmetric or asymmetric relation, nor whether the parliament has a finite or infinite number of members. I will show that the assertion is false for asymmetric relations, even in the finite case; in fact, I give an (asymmetric) example of $15$ people, each having only $2$ enemies, who can't be divided into two groups in which each member has at most one enemy. On the other hand, if the relation is symmetric, the assertion is true even in the infinite case. **An asymmetric counterexample.** There are $15$ people, call them $x\_i,y\_i,y'\_i,z\_i,z'\_i\ (i=0,1,2).$ The enemies of $x\_i$ are $y\_i,y'\_i;$ the enemies of $y\_i,y'\_i$ are $z\_i,z'\_i;$ the enemies of $z\_i,z'\_i$ are $x\_i,x\_{i+1}$ (addition modulo $3$). Let each of the $15$ people be colored red or blue. Then at least two among $x\_0,x\_1,x\_2$ have the same color; without loss of generality, suppose that $x\_0,x\_1$ are red. If either $z\_0$ or $z'\_0$ is red, then we have a red person with two red enemies; so we may assume that $z\_0,z'\_0$ are blue. If either $y\_0$ or $y'\_0$ is blue, then we have a blue person with two blue enemies; so we may assume that $y\_0,y'\_0$ are red. But then $x\_0$ is a red person with two red enemies. **The finite symmetric case.** (Already proved in the [answer](https://math.stackexchange.com/questions/2062522/each-person-has-at-most-3-enemies-in-a-group-show-that-we-can-separate-them-int/2062534#2062534) by @cats, repeated here for convenience.) If $G=(V,E)$ is a finite *undirected* graph with maximum degree at most $3,$ then the vertex set $V$ can be partitioned into two sets $V\_1,V\_2$ so that, for $i=1,2,$ each vertex in $V\_i$ has at most one neighbor (i.e. "enemy") in $V\_i.$ This can be done by choosing a partition which maximizes the number of edges with one endpoint in $\_1$ and the other in $V\_2.$ (This argument does not work if $V$ is infinite.) **The infinite symmetric case.** If $G=(V,E)$ is any (not necessarily finite) undirected graph with maximum degree at most $3,$ then the vertex set $V$ can be partitioned into two sets $V\_1,V\_2$ so that, for $i=1,2,$ each vertex in $V\_i$ has at most one neighbor in $V\_i.$ This follows from the finite case by the usual sort of compactness argument, i.e., using the fact that the [Tychonoff product](https://en.wikipedia.org/wiki/Tychonoff%27s_theorem) of any family of finite spaces is compact. **More generally,** let $k$ be a positive integer and let $d\_1,\dots,d\_k$ be nonnegative integers. If $G=(V,E)$ is any (not necessarily finite) undirected graph with maximum degree at most $d\_1+\cdots+d\_k+k-1$, then the vertex set $V$ can be partitioned into $k$ sets $V\_1,\dots,V\_k$ so that, for each $i=1,\dots,k$, each vertex in $V\_i$ has at most $d\_i$ neighbors in $V\_i$. **Proof.** We may assume that $G$ is a finite graph and that $k=2$; the general case will then follow by induction on $k$ and a compactness argument. Let $d\_1,d\_2$ be nonnegative integers, and let $G=(V,E)$ be a finite graph with maximum degree at most $d\_1+d\_2+1$. Let $\{V\_1,V\_2\}$ be a partition of $V$ which minimizes the quantity $(d\_2+1)e\_1+(d\_1+1)e\_2$ where $e\_i$ is the number of edges joining two vertices in $V\_i$. Then each vertex in $V\_i$ has at most $d\_i$ neighbors in $V\_i$.
Let's separate it into two houses, House A and House B. If person $1$ has two or more enemies in House A, then we put him or her in House B. Then we take care of person $2$, etc. After just finitely many house changes (because we don't have infinitely many people), we can get each member to have at most one enemy in his or her house.
17,603,784
This question is a bit difficult to explain. I have a textfield on top (where the navigation bar is usually is) and when I start editing text, the keyboard shows and auto dims the background. I want to add another UIView below the textfield but have that visible and not dimmed out. Perfect image that describes what I want is this: <http://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/Art/keyboard_size.jpg> ![enter image description here](https://i.stack.imgur.com/0LAOK.jpg) I want to implement something similar like that google search bar underneath the search url bar. Notice how that is not dimmed out? How can I accomplish this? Thanks!
2013/07/11
['https://Stackoverflow.com/questions/17603784', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1212530/']
It is getting the characters from left to right (low to high, 0 to length) It is appending the characters from right to left. that reverses them. ``` 1 2 3 | | | \ | / X / | \ 3 2 1 ``` First time through the loop, it takes '1' and puts it in the string. Second time through the loop, it takes '2' and puts it in the string to the left of '1' Thirst time through the loop, it takes '3' and puts it to the left of '2' and '1'. When I say "it takes" I'm referring to the code: `input.charAt(i)` Note that the 'i' gets bigger each time through the loop because of the `i++`
It is actually a badly written program that constantly creates new (immutable) `String` objects while iterating over the characters of `input` from left to right, each time prepending the character to `result`. This is done by the code `input.charAt(i) + result` which puts the character in front of the previous result. A better implementation would use a `StringBuilder` (which is mutable) to avoid excessive `String` creation. Like this: ``` public static void main(String args[]) { String input = "***NGuyen**Van******A*******"; StringBuilder builder = new StringBuilder(); String result; for (int i = input.length() - 1; i >= 0; i--) { builder.append(input.charAt(i)); } result = builder.toString(); System.out.println(result); } ```
150,528
This is a code review for a set of loggers following [this](https://stackoverflow.com/questions/41175864/how-to-assure-contract-with-multiple-classes-that-are-similar-in-behavior-but-di/41230131?noredirect=1#comment69660624_41230131) question. The project is a universal windows application targeting Windows Phone. There are concerns over the tight coupling between the loggers and App. There is way too much code in the main program that is responsible for setting up the logger just right. There are also concerns on how to deal with the fact that a ReleaseLogger requires special behavior (establishing a session) that the DebugLogger class does not, and how to deal with this. App.xaml.cs ``` using Log.Common; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Foundation.Diagnostics; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Animation; using Windows.UI.Xaml.Navigation; // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227 namespace Log { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> public sealed partial class App : Application { #if WINDOWS_PHONE_APP private TransitionCollection transitions; #endif public const string TelemetryUrl = "http://try.count.ly"; public const string TelemetryAppKey = ""; private ILogger _logger; private ILogger Logger { get { if(null == _logger) { //#if PROD _logger = new ReleaseLogger(); //#else //_logger = new DebugLogger(); //#endif } return _logger; } } /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += this.OnSuspending; this.Resuming += this.OnResuming; this.UnhandledException += OnUnhandledException; } private async Task TryStartTelemetry() { var logger = Logger as ReleaseLogger; if (null != logger) { await logger.StartSessionAsync(this, TelemetryUrl, TelemetryAppKey); } } private async Task TryEndTelemetry() { var logger = Logger as ReleaseLogger; if (null != logger) { await logger.EndSessionAsync(); } } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override async void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); // TODO: change this value to a cache size that is appropriate for your application rootFrame.CacheSize = 1; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { #if WINDOWS_PHONE_APP // Removes the turnstile navigation for startup. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; #endif // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(MainPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } await TryStartTelemetry(); Logger.Log("Application Launched", LoggingLevel.Information, null); // Ensure the current window is active Window.Current.Activate(); } protected override async void OnActivated(IActivatedEventArgs args) { base.OnActivated(args); await TryStartTelemetry(); } #if WINDOWS_PHONE_APP /// <summary> /// Restores the content transitions after the app has launched. /// </summary> /// <param name="sender">The object where the handler is attached.</param> /// <param name="e">Details about the navigation event.</param> private void RootFrame_FirstNavigated(object sender, NavigationEventArgs e) { var rootFrame = sender as Frame; rootFrame.ContentTransitions = this.transitions ?? new TransitionCollection() { new NavigationThemeTransition() }; rootFrame.Navigated -= this.RootFrame_FirstNavigated; } #endif /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private async void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); // TODO: Save application state and stop any background activity await TryEndTelemetry(); deferral.Complete(); } private async void OnResuming(object sender, object e) { await TryStartTelemetry(); } private async void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) { await TryEndTelemetry(); } } } ``` ILogger.cs ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using Windows.Foundation.Diagnostics; namespace Log.Common { public interface ILogger { void LogException(Exception ex); void Log(string message, LoggingLevel loggingLevel, params object[] args); } } ``` DebugLogger.cs ``` using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Foundation.Diagnostics; namespace Log.Common { public class DebugLogger : ILogger { public void LogException(Exception ex) { if (ex == null) throw new ArgumentNullException("exception"); Debug.WriteLine("Exception: " + ex.Message); // Log to UI here. } public void Log(string message, LoggingLevel loggingLevel, params object[] args) { if (string.IsNullOrWhiteSpace(message)) throw new ArgumentException("message"); if (args != null && args.Length > 0) { message = string.Format(message, args); } //TODO: let's define when and where log switch (loggingLevel) { case LoggingLevel.Critical: Debug.WriteLine("Critical: " + message, args); // Log to UI here. break; case LoggingLevel.Error: Debug.WriteLine("Error: " + message, args); // Log to UI here. break; case LoggingLevel.Warning: Debug.WriteLine("Warning: " + message, args); // Log to UI here. break; case LoggingLevel.Information: Debug.WriteLine("Info: " + message, args); // Log to UI here. break; case LoggingLevel.Verbose: Debug.WriteLine("Verbose: " + message, args); break; default: throw new ArgumentOutOfRangeException(nameof(loggingLevel), loggingLevel, null); } } } } ``` ReleaseLogger.cs ``` using CountlySDK; using Log; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Foundation.Diagnostics; using Windows.UI.Xaml; namespace Log.Common { public class ReleaseLogger : ILogger { private bool _sessionStarted; // A Queue of exceptions to log. private Queue<Exception> _exceptionQueue; public ReleaseLogger() { _exceptionQueue = new Queue<Exception>(); _sessionStarted = false; Countly.IsLoggingEnabled = true; } public async Task StartSessionAsync(Application app, string telemetryUrl, string telemetryAppKey) { if (telemetryUrl == null) throw new ArgumentNullException("telemetryUrl"); if (telemetryAppKey == null) throw new ArgumentNullException("telemetryAppKey"); try { await Countly.StartSession(telemetryUrl, telemetryAppKey, app); while (_exceptionQueue.Count > 0) { await LogExceptionAsync(_exceptionQueue.Dequeue()); } _sessionStarted = true; } catch (Exception countlyEx) { // Log to UI here. } } public async Task EndSessionAsync() { try { await Countly.EndSession(); } catch (Exception countlyEx) { // Log to UI here. } finally { _sessionStarted = false; // Log to UI here. } } public async Task LogExceptionAsync(Exception ex) { if (ex == null) throw new ArgumentNullException("exception"); if (_sessionStarted) { try { await Countly.RecordException(ex.Message, ex.StackTrace); } catch (Exception countlyEx) { // Log to UI here. } } else { _exceptionQueue.Enqueue(ex); } } public void LogException(Exception ex) { var result = LogExceptionAsync(ex); } public async Task LogAsync(string message, LoggingLevel loggingLevel, params object[] args) { if (string.IsNullOrWhiteSpace(message)) throw new ArgumentException("message"); if (args != null && args.Length > 0) { message = string.Format(message, args); } switch (loggingLevel) { case LoggingLevel.Critical: case LoggingLevel.Error: // Log to UI here. await Countly.RecordException(message); break; case LoggingLevel.Warning: // Log to UI here. break; case LoggingLevel.Information: await Countly.RecordEvent(message); // Log to UI here. break; case LoggingLevel.Verbose: Debug.WriteLine(message, args); break; default: throw new ArgumentOutOfRangeException(nameof(loggingLevel), loggingLevel, null); } } public void Log(string message, LoggingLevel loggingLevel, params object[] args) { var result = LogAsync(message, loggingLevel, args); } } } ```
2016/12/21
['https://codereview.stackexchange.com/questions/150528', 'https://codereview.stackexchange.com', 'https://codereview.stackexchange.com/users/42250/']
Interesting question, * I noticed that 9-3\*3 does not return 0, but 27, you are not following PEMDAS * Personally, I would make sure that the input only contains numbers, dots, and math operators, and then use `eval`. `eval("9-3*3")` does return correctly 0. * 0.0022 \* 2 returns zero. * I would assign html elements like the one found from `document.getElementById(numberScreen)` to a higher scope variable for readability and performance * You do not check for existing periods in the current number, allowing for numbers like 12.24.2016 * Using a pure UI function (`innerHTML`) to drive the logic is wrong. It's okay for a beginner class, but anything more advanced should drive of (`id`). You dont want to replace 'x' with '\*' and also having to change the JS code * Your indentation is not perfect, use <http://jsbeautifier.org/> * You have zero warnings on jshint.com, which is amazing
To solve "There's no limit to amount of numbers in the display", If you change your javascript to: ``` if(content != "0"){ if (content.length < 16) content += btnNum; } else { content = btnNum; } ``` You'll be saying "only add more numbers if there is less than 16 numbers on my screen". (I put 16 because I tested your code and 16 is the max quantity until your div starts to expand) What do you mean with "Modulus is broken"?
150,528
This is a code review for a set of loggers following [this](https://stackoverflow.com/questions/41175864/how-to-assure-contract-with-multiple-classes-that-are-similar-in-behavior-but-di/41230131?noredirect=1#comment69660624_41230131) question. The project is a universal windows application targeting Windows Phone. There are concerns over the tight coupling between the loggers and App. There is way too much code in the main program that is responsible for setting up the logger just right. There are also concerns on how to deal with the fact that a ReleaseLogger requires special behavior (establishing a session) that the DebugLogger class does not, and how to deal with this. App.xaml.cs ``` using Log.Common; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Foundation.Diagnostics; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Animation; using Windows.UI.Xaml.Navigation; // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227 namespace Log { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> public sealed partial class App : Application { #if WINDOWS_PHONE_APP private TransitionCollection transitions; #endif public const string TelemetryUrl = "http://try.count.ly"; public const string TelemetryAppKey = ""; private ILogger _logger; private ILogger Logger { get { if(null == _logger) { //#if PROD _logger = new ReleaseLogger(); //#else //_logger = new DebugLogger(); //#endif } return _logger; } } /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += this.OnSuspending; this.Resuming += this.OnResuming; this.UnhandledException += OnUnhandledException; } private async Task TryStartTelemetry() { var logger = Logger as ReleaseLogger; if (null != logger) { await logger.StartSessionAsync(this, TelemetryUrl, TelemetryAppKey); } } private async Task TryEndTelemetry() { var logger = Logger as ReleaseLogger; if (null != logger) { await logger.EndSessionAsync(); } } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override async void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); // TODO: change this value to a cache size that is appropriate for your application rootFrame.CacheSize = 1; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { #if WINDOWS_PHONE_APP // Removes the turnstile navigation for startup. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; #endif // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(MainPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } await TryStartTelemetry(); Logger.Log("Application Launched", LoggingLevel.Information, null); // Ensure the current window is active Window.Current.Activate(); } protected override async void OnActivated(IActivatedEventArgs args) { base.OnActivated(args); await TryStartTelemetry(); } #if WINDOWS_PHONE_APP /// <summary> /// Restores the content transitions after the app has launched. /// </summary> /// <param name="sender">The object where the handler is attached.</param> /// <param name="e">Details about the navigation event.</param> private void RootFrame_FirstNavigated(object sender, NavigationEventArgs e) { var rootFrame = sender as Frame; rootFrame.ContentTransitions = this.transitions ?? new TransitionCollection() { new NavigationThemeTransition() }; rootFrame.Navigated -= this.RootFrame_FirstNavigated; } #endif /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private async void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); // TODO: Save application state and stop any background activity await TryEndTelemetry(); deferral.Complete(); } private async void OnResuming(object sender, object e) { await TryStartTelemetry(); } private async void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) { await TryEndTelemetry(); } } } ``` ILogger.cs ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using Windows.Foundation.Diagnostics; namespace Log.Common { public interface ILogger { void LogException(Exception ex); void Log(string message, LoggingLevel loggingLevel, params object[] args); } } ``` DebugLogger.cs ``` using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Foundation.Diagnostics; namespace Log.Common { public class DebugLogger : ILogger { public void LogException(Exception ex) { if (ex == null) throw new ArgumentNullException("exception"); Debug.WriteLine("Exception: " + ex.Message); // Log to UI here. } public void Log(string message, LoggingLevel loggingLevel, params object[] args) { if (string.IsNullOrWhiteSpace(message)) throw new ArgumentException("message"); if (args != null && args.Length > 0) { message = string.Format(message, args); } //TODO: let's define when and where log switch (loggingLevel) { case LoggingLevel.Critical: Debug.WriteLine("Critical: " + message, args); // Log to UI here. break; case LoggingLevel.Error: Debug.WriteLine("Error: " + message, args); // Log to UI here. break; case LoggingLevel.Warning: Debug.WriteLine("Warning: " + message, args); // Log to UI here. break; case LoggingLevel.Information: Debug.WriteLine("Info: " + message, args); // Log to UI here. break; case LoggingLevel.Verbose: Debug.WriteLine("Verbose: " + message, args); break; default: throw new ArgumentOutOfRangeException(nameof(loggingLevel), loggingLevel, null); } } } } ``` ReleaseLogger.cs ``` using CountlySDK; using Log; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Foundation.Diagnostics; using Windows.UI.Xaml; namespace Log.Common { public class ReleaseLogger : ILogger { private bool _sessionStarted; // A Queue of exceptions to log. private Queue<Exception> _exceptionQueue; public ReleaseLogger() { _exceptionQueue = new Queue<Exception>(); _sessionStarted = false; Countly.IsLoggingEnabled = true; } public async Task StartSessionAsync(Application app, string telemetryUrl, string telemetryAppKey) { if (telemetryUrl == null) throw new ArgumentNullException("telemetryUrl"); if (telemetryAppKey == null) throw new ArgumentNullException("telemetryAppKey"); try { await Countly.StartSession(telemetryUrl, telemetryAppKey, app); while (_exceptionQueue.Count > 0) { await LogExceptionAsync(_exceptionQueue.Dequeue()); } _sessionStarted = true; } catch (Exception countlyEx) { // Log to UI here. } } public async Task EndSessionAsync() { try { await Countly.EndSession(); } catch (Exception countlyEx) { // Log to UI here. } finally { _sessionStarted = false; // Log to UI here. } } public async Task LogExceptionAsync(Exception ex) { if (ex == null) throw new ArgumentNullException("exception"); if (_sessionStarted) { try { await Countly.RecordException(ex.Message, ex.StackTrace); } catch (Exception countlyEx) { // Log to UI here. } } else { _exceptionQueue.Enqueue(ex); } } public void LogException(Exception ex) { var result = LogExceptionAsync(ex); } public async Task LogAsync(string message, LoggingLevel loggingLevel, params object[] args) { if (string.IsNullOrWhiteSpace(message)) throw new ArgumentException("message"); if (args != null && args.Length > 0) { message = string.Format(message, args); } switch (loggingLevel) { case LoggingLevel.Critical: case LoggingLevel.Error: // Log to UI here. await Countly.RecordException(message); break; case LoggingLevel.Warning: // Log to UI here. break; case LoggingLevel.Information: await Countly.RecordEvent(message); // Log to UI here. break; case LoggingLevel.Verbose: Debug.WriteLine(message, args); break; default: throw new ArgumentOutOfRangeException(nameof(loggingLevel), loggingLevel, null); } } public void Log(string message, LoggingLevel loggingLevel, params object[] args) { var result = LogAsync(message, loggingLevel, args); } } } ```
2016/12/21
['https://codereview.stackexchange.com/questions/150528', 'https://codereview.stackexchange.com', 'https://codereview.stackexchange.com/users/42250/']
Interesting question, * I noticed that 9-3\*3 does not return 0, but 27, you are not following PEMDAS * Personally, I would make sure that the input only contains numbers, dots, and math operators, and then use `eval`. `eval("9-3*3")` does return correctly 0. * 0.0022 \* 2 returns zero. * I would assign html elements like the one found from `document.getElementById(numberScreen)` to a higher scope variable for readability and performance * You do not check for existing periods in the current number, allowing for numbers like 12.24.2016 * Using a pure UI function (`innerHTML`) to drive the logic is wrong. It's okay for a beginner class, but anything more advanced should drive of (`id`). You dont want to replace 'x' with '\*' and also having to change the JS code * Your indentation is not perfect, use <http://jsbeautifier.org/> * You have zero warnings on jshint.com, which is amazing
The code looks pretty good. Here are a few suggestions: You reference `document.getElementById(numberScreen)` quite a few times. Why not assign it a shorter variable name at the top of your JavaScript file, like you did with `numBtns` and `operators`? You could group your code into sections, to make it easier to find things. For example, have a variable-declaring section, then a functions section, then the code execution section. The sections can be differentiated with comment lines, like: `//--------- functions -------------------` That's just one way to group the code. Another way might work better for you. You could also group your functions with similar functions, to make them easier to find. As one example, `clearScreen()` and `resetOperating()` could be next to each other, and `evaluate()` could be toward the bottom. While grouping your functions, you can check to make sure no functions are called before they are declared -- it won't make the code run better, but it will increase readability.
150,528
This is a code review for a set of loggers following [this](https://stackoverflow.com/questions/41175864/how-to-assure-contract-with-multiple-classes-that-are-similar-in-behavior-but-di/41230131?noredirect=1#comment69660624_41230131) question. The project is a universal windows application targeting Windows Phone. There are concerns over the tight coupling between the loggers and App. There is way too much code in the main program that is responsible for setting up the logger just right. There are also concerns on how to deal with the fact that a ReleaseLogger requires special behavior (establishing a session) that the DebugLogger class does not, and how to deal with this. App.xaml.cs ``` using Log.Common; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Foundation.Diagnostics; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Animation; using Windows.UI.Xaml.Navigation; // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227 namespace Log { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> public sealed partial class App : Application { #if WINDOWS_PHONE_APP private TransitionCollection transitions; #endif public const string TelemetryUrl = "http://try.count.ly"; public const string TelemetryAppKey = ""; private ILogger _logger; private ILogger Logger { get { if(null == _logger) { //#if PROD _logger = new ReleaseLogger(); //#else //_logger = new DebugLogger(); //#endif } return _logger; } } /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += this.OnSuspending; this.Resuming += this.OnResuming; this.UnhandledException += OnUnhandledException; } private async Task TryStartTelemetry() { var logger = Logger as ReleaseLogger; if (null != logger) { await logger.StartSessionAsync(this, TelemetryUrl, TelemetryAppKey); } } private async Task TryEndTelemetry() { var logger = Logger as ReleaseLogger; if (null != logger) { await logger.EndSessionAsync(); } } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override async void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); // TODO: change this value to a cache size that is appropriate for your application rootFrame.CacheSize = 1; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { #if WINDOWS_PHONE_APP // Removes the turnstile navigation for startup. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; #endif // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(MainPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } await TryStartTelemetry(); Logger.Log("Application Launched", LoggingLevel.Information, null); // Ensure the current window is active Window.Current.Activate(); } protected override async void OnActivated(IActivatedEventArgs args) { base.OnActivated(args); await TryStartTelemetry(); } #if WINDOWS_PHONE_APP /// <summary> /// Restores the content transitions after the app has launched. /// </summary> /// <param name="sender">The object where the handler is attached.</param> /// <param name="e">Details about the navigation event.</param> private void RootFrame_FirstNavigated(object sender, NavigationEventArgs e) { var rootFrame = sender as Frame; rootFrame.ContentTransitions = this.transitions ?? new TransitionCollection() { new NavigationThemeTransition() }; rootFrame.Navigated -= this.RootFrame_FirstNavigated; } #endif /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private async void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); // TODO: Save application state and stop any background activity await TryEndTelemetry(); deferral.Complete(); } private async void OnResuming(object sender, object e) { await TryStartTelemetry(); } private async void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) { await TryEndTelemetry(); } } } ``` ILogger.cs ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using Windows.Foundation.Diagnostics; namespace Log.Common { public interface ILogger { void LogException(Exception ex); void Log(string message, LoggingLevel loggingLevel, params object[] args); } } ``` DebugLogger.cs ``` using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Foundation.Diagnostics; namespace Log.Common { public class DebugLogger : ILogger { public void LogException(Exception ex) { if (ex == null) throw new ArgumentNullException("exception"); Debug.WriteLine("Exception: " + ex.Message); // Log to UI here. } public void Log(string message, LoggingLevel loggingLevel, params object[] args) { if (string.IsNullOrWhiteSpace(message)) throw new ArgumentException("message"); if (args != null && args.Length > 0) { message = string.Format(message, args); } //TODO: let's define when and where log switch (loggingLevel) { case LoggingLevel.Critical: Debug.WriteLine("Critical: " + message, args); // Log to UI here. break; case LoggingLevel.Error: Debug.WriteLine("Error: " + message, args); // Log to UI here. break; case LoggingLevel.Warning: Debug.WriteLine("Warning: " + message, args); // Log to UI here. break; case LoggingLevel.Information: Debug.WriteLine("Info: " + message, args); // Log to UI here. break; case LoggingLevel.Verbose: Debug.WriteLine("Verbose: " + message, args); break; default: throw new ArgumentOutOfRangeException(nameof(loggingLevel), loggingLevel, null); } } } } ``` ReleaseLogger.cs ``` using CountlySDK; using Log; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Foundation.Diagnostics; using Windows.UI.Xaml; namespace Log.Common { public class ReleaseLogger : ILogger { private bool _sessionStarted; // A Queue of exceptions to log. private Queue<Exception> _exceptionQueue; public ReleaseLogger() { _exceptionQueue = new Queue<Exception>(); _sessionStarted = false; Countly.IsLoggingEnabled = true; } public async Task StartSessionAsync(Application app, string telemetryUrl, string telemetryAppKey) { if (telemetryUrl == null) throw new ArgumentNullException("telemetryUrl"); if (telemetryAppKey == null) throw new ArgumentNullException("telemetryAppKey"); try { await Countly.StartSession(telemetryUrl, telemetryAppKey, app); while (_exceptionQueue.Count > 0) { await LogExceptionAsync(_exceptionQueue.Dequeue()); } _sessionStarted = true; } catch (Exception countlyEx) { // Log to UI here. } } public async Task EndSessionAsync() { try { await Countly.EndSession(); } catch (Exception countlyEx) { // Log to UI here. } finally { _sessionStarted = false; // Log to UI here. } } public async Task LogExceptionAsync(Exception ex) { if (ex == null) throw new ArgumentNullException("exception"); if (_sessionStarted) { try { await Countly.RecordException(ex.Message, ex.StackTrace); } catch (Exception countlyEx) { // Log to UI here. } } else { _exceptionQueue.Enqueue(ex); } } public void LogException(Exception ex) { var result = LogExceptionAsync(ex); } public async Task LogAsync(string message, LoggingLevel loggingLevel, params object[] args) { if (string.IsNullOrWhiteSpace(message)) throw new ArgumentException("message"); if (args != null && args.Length > 0) { message = string.Format(message, args); } switch (loggingLevel) { case LoggingLevel.Critical: case LoggingLevel.Error: // Log to UI here. await Countly.RecordException(message); break; case LoggingLevel.Warning: // Log to UI here. break; case LoggingLevel.Information: await Countly.RecordEvent(message); // Log to UI here. break; case LoggingLevel.Verbose: Debug.WriteLine(message, args); break; default: throw new ArgumentOutOfRangeException(nameof(loggingLevel), loggingLevel, null); } } public void Log(string message, LoggingLevel loggingLevel, params object[] args) { var result = LogAsync(message, loggingLevel, args); } } } ```
2016/12/21
['https://codereview.stackexchange.com/questions/150528', 'https://codereview.stackexchange.com', 'https://codereview.stackexchange.com/users/42250/']
Interesting question, * I noticed that 9-3\*3 does not return 0, but 27, you are not following PEMDAS * Personally, I would make sure that the input only contains numbers, dots, and math operators, and then use `eval`. `eval("9-3*3")` does return correctly 0. * 0.0022 \* 2 returns zero. * I would assign html elements like the one found from `document.getElementById(numberScreen)` to a higher scope variable for readability and performance * You do not check for existing periods in the current number, allowing for numbers like 12.24.2016 * Using a pure UI function (`innerHTML`) to drive the logic is wrong. It's okay for a beginner class, but anything more advanced should drive of (`id`). You dont want to replace 'x' with '\*' and also having to change the JS code * Your indentation is not perfect, use <http://jsbeautifier.org/> * You have zero warnings on jshint.com, which is amazing
code layout =========== For code cleanliness, I recommend rearranging your code so that the function definitions are all together at the end, after the imperative commands. ``` // declare variables // set up event listeners // clear the screen // function definitions ``` avoiding global namespace pollution =================================== Since your logic (wisely) does not depend on global variable declarations, you can avoid polluting the global namespace by wrapping all your code in an immediately executing function expression (IEFE). ``` (function(){ // your code here })(); ``` Since JavaScript variables are function-scoped, this essentially creates a new scope in which your code and functions can refer to variables defined within. Code outside the scope (such as elsewhere on the page) can then use the same variable and function names without running into any collisions.
150,528
This is a code review for a set of loggers following [this](https://stackoverflow.com/questions/41175864/how-to-assure-contract-with-multiple-classes-that-are-similar-in-behavior-but-di/41230131?noredirect=1#comment69660624_41230131) question. The project is a universal windows application targeting Windows Phone. There are concerns over the tight coupling between the loggers and App. There is way too much code in the main program that is responsible for setting up the logger just right. There are also concerns on how to deal with the fact that a ReleaseLogger requires special behavior (establishing a session) that the DebugLogger class does not, and how to deal with this. App.xaml.cs ``` using Log.Common; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Foundation.Diagnostics; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Animation; using Windows.UI.Xaml.Navigation; // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227 namespace Log { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> public sealed partial class App : Application { #if WINDOWS_PHONE_APP private TransitionCollection transitions; #endif public const string TelemetryUrl = "http://try.count.ly"; public const string TelemetryAppKey = ""; private ILogger _logger; private ILogger Logger { get { if(null == _logger) { //#if PROD _logger = new ReleaseLogger(); //#else //_logger = new DebugLogger(); //#endif } return _logger; } } /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += this.OnSuspending; this.Resuming += this.OnResuming; this.UnhandledException += OnUnhandledException; } private async Task TryStartTelemetry() { var logger = Logger as ReleaseLogger; if (null != logger) { await logger.StartSessionAsync(this, TelemetryUrl, TelemetryAppKey); } } private async Task TryEndTelemetry() { var logger = Logger as ReleaseLogger; if (null != logger) { await logger.EndSessionAsync(); } } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override async void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); // TODO: change this value to a cache size that is appropriate for your application rootFrame.CacheSize = 1; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { #if WINDOWS_PHONE_APP // Removes the turnstile navigation for startup. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; #endif // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(MainPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } await TryStartTelemetry(); Logger.Log("Application Launched", LoggingLevel.Information, null); // Ensure the current window is active Window.Current.Activate(); } protected override async void OnActivated(IActivatedEventArgs args) { base.OnActivated(args); await TryStartTelemetry(); } #if WINDOWS_PHONE_APP /// <summary> /// Restores the content transitions after the app has launched. /// </summary> /// <param name="sender">The object where the handler is attached.</param> /// <param name="e">Details about the navigation event.</param> private void RootFrame_FirstNavigated(object sender, NavigationEventArgs e) { var rootFrame = sender as Frame; rootFrame.ContentTransitions = this.transitions ?? new TransitionCollection() { new NavigationThemeTransition() }; rootFrame.Navigated -= this.RootFrame_FirstNavigated; } #endif /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private async void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); // TODO: Save application state and stop any background activity await TryEndTelemetry(); deferral.Complete(); } private async void OnResuming(object sender, object e) { await TryStartTelemetry(); } private async void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) { await TryEndTelemetry(); } } } ``` ILogger.cs ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using Windows.Foundation.Diagnostics; namespace Log.Common { public interface ILogger { void LogException(Exception ex); void Log(string message, LoggingLevel loggingLevel, params object[] args); } } ``` DebugLogger.cs ``` using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Foundation.Diagnostics; namespace Log.Common { public class DebugLogger : ILogger { public void LogException(Exception ex) { if (ex == null) throw new ArgumentNullException("exception"); Debug.WriteLine("Exception: " + ex.Message); // Log to UI here. } public void Log(string message, LoggingLevel loggingLevel, params object[] args) { if (string.IsNullOrWhiteSpace(message)) throw new ArgumentException("message"); if (args != null && args.Length > 0) { message = string.Format(message, args); } //TODO: let's define when and where log switch (loggingLevel) { case LoggingLevel.Critical: Debug.WriteLine("Critical: " + message, args); // Log to UI here. break; case LoggingLevel.Error: Debug.WriteLine("Error: " + message, args); // Log to UI here. break; case LoggingLevel.Warning: Debug.WriteLine("Warning: " + message, args); // Log to UI here. break; case LoggingLevel.Information: Debug.WriteLine("Info: " + message, args); // Log to UI here. break; case LoggingLevel.Verbose: Debug.WriteLine("Verbose: " + message, args); break; default: throw new ArgumentOutOfRangeException(nameof(loggingLevel), loggingLevel, null); } } } } ``` ReleaseLogger.cs ``` using CountlySDK; using Log; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Foundation.Diagnostics; using Windows.UI.Xaml; namespace Log.Common { public class ReleaseLogger : ILogger { private bool _sessionStarted; // A Queue of exceptions to log. private Queue<Exception> _exceptionQueue; public ReleaseLogger() { _exceptionQueue = new Queue<Exception>(); _sessionStarted = false; Countly.IsLoggingEnabled = true; } public async Task StartSessionAsync(Application app, string telemetryUrl, string telemetryAppKey) { if (telemetryUrl == null) throw new ArgumentNullException("telemetryUrl"); if (telemetryAppKey == null) throw new ArgumentNullException("telemetryAppKey"); try { await Countly.StartSession(telemetryUrl, telemetryAppKey, app); while (_exceptionQueue.Count > 0) { await LogExceptionAsync(_exceptionQueue.Dequeue()); } _sessionStarted = true; } catch (Exception countlyEx) { // Log to UI here. } } public async Task EndSessionAsync() { try { await Countly.EndSession(); } catch (Exception countlyEx) { // Log to UI here. } finally { _sessionStarted = false; // Log to UI here. } } public async Task LogExceptionAsync(Exception ex) { if (ex == null) throw new ArgumentNullException("exception"); if (_sessionStarted) { try { await Countly.RecordException(ex.Message, ex.StackTrace); } catch (Exception countlyEx) { // Log to UI here. } } else { _exceptionQueue.Enqueue(ex); } } public void LogException(Exception ex) { var result = LogExceptionAsync(ex); } public async Task LogAsync(string message, LoggingLevel loggingLevel, params object[] args) { if (string.IsNullOrWhiteSpace(message)) throw new ArgumentException("message"); if (args != null && args.Length > 0) { message = string.Format(message, args); } switch (loggingLevel) { case LoggingLevel.Critical: case LoggingLevel.Error: // Log to UI here. await Countly.RecordException(message); break; case LoggingLevel.Warning: // Log to UI here. break; case LoggingLevel.Information: await Countly.RecordEvent(message); // Log to UI here. break; case LoggingLevel.Verbose: Debug.WriteLine(message, args); break; default: throw new ArgumentOutOfRangeException(nameof(loggingLevel), loggingLevel, null); } } public void Log(string message, LoggingLevel loggingLevel, params object[] args) { var result = LogAsync(message, loggingLevel, args); } } } ```
2016/12/21
['https://codereview.stackexchange.com/questions/150528', 'https://codereview.stackexchange.com', 'https://codereview.stackexchange.com/users/42250/']
Interesting question, * I noticed that 9-3\*3 does not return 0, but 27, you are not following PEMDAS * Personally, I would make sure that the input only contains numbers, dots, and math operators, and then use `eval`. `eval("9-3*3")` does return correctly 0. * 0.0022 \* 2 returns zero. * I would assign html elements like the one found from `document.getElementById(numberScreen)` to a higher scope variable for readability and performance * You do not check for existing periods in the current number, allowing for numbers like 12.24.2016 * Using a pure UI function (`innerHTML`) to drive the logic is wrong. It's okay for a beginner class, but anything more advanced should drive of (`id`). You dont want to replace 'x' with '\*' and also having to change the JS code * Your indentation is not perfect, use <http://jsbeautifier.org/> * You have zero warnings on jshint.com, which is amazing
Fundamentally, your problems lie in the way you are evaluating your input string. ### Problem 1: You only recognize one operator in the string to be evaluated, the last one that was typed. (i.e the contents of `operand`). We need something more sophisticated than `contents.split(operand)` here. The solution here is to use a *lexer*. This breaks up the contents string into *tokens*, much like `contents.split` except that it will split on more all the different operators, and can also tag each token to say whether it's an operator or a number. A simple way to do this might be to call `contents.split` once for each of possible operator, merging the sublists generated each time. In pseudocode: ``` tokens = contents.split(' ') for operator in operators { tokens = tokens.map(x => x.split(operator)) tokens = tokens.reduce((a, b) => a + b) } ``` The problem with this is that it doesn't give any information on what sort of thing each token is and it isn't very easily extensible. A better way would be in a state machine: ``` function lexer(contents) { tokens = [] while contents is not empty { char = contents[0] contents = contents.slice(1) if char is an operator { tokens.append({ type: 'operator', value: char }) } number = "" while char is a number { number += char char = contents[0] contents = contents.slice(1) } if number != "" { tokens.append({ type: 'number', value: parseInt(number, 10) }) } } } ``` This has the advantage of giving information about each token, parsing the numbers at this point rather than later and having far better complexity - \$O(n)\$ instead of \$O(nk)\$ where \$k\$ is the number of operators, and \$n\$ is the length of the string. ### Problem 2: You only use the first two numbers of this in your calculation - `firstNumber` and `secondNumber`, and you don't follow the usual orders of operation (PEMDAS - or BIDMAS in the UK) The solution to this is to *parse* the tokens we generated in the last step into something which we can evaluate with the right order of operations. The easiest way to do this is to go through each operator, starting with the highest precedence so that the correct order of operations is maintained: ``` function parser(tokens) { ast = tokens for currentOperator in operators, ordered by precedence { tokens = ast ast = [] while tokens is not empty { token = tokens[0] tokens = tokens.slice(1) if token is a number { ast.append(token) } else if token is an operator { if token is currentOperator { lhs = ast[ast.length - 1] rhs = tokens[0] ast[ast.length - 1] = { operator: token, lhs: lhs, rhs: rhs } tokens = tokens.slice(1) } else { ast.append(token) } } } } } ``` A more sophisticated (and efficient) way to do this would be to use something like [Dikjstra's shunting yard algorithm](https://www.wikiwand.com/en/Shunting-yard_algorithm). This yields what is called an *abstract syntax tree* (the `ast` variable from the last example). This is now in a form we can easily evaluate. There should only be one element in `ast` if the expression was well formed. This object has three fields: `lhs`, `rhs` and `operator`, which correspond to the left hand side, right hand side and the operator of the operation we should perform. The left and right hand sides are themselves expressions to evaluate, which we should do before performing the operation. This is expressed in pseudocode like so: ``` function evaluate(ast) { lhs = evaluate(ast.lhs) rhs = evaluate(ast.rhs) switch ast.operator { case '+': return lhs + rhs case '-': return lhs - rhs case '*': return lhs * rhs case '/': return lhs / rhs } } ``` Putting this all together, our new final solution, that handles multiple operations and evaluates in the correct order, is: ``` answer = evaluate(parser(lexer(contents)) ``` This pattern of lexing to tokens, parsing tokens to an abstract syntax tree and evaluating or transforming this tree is prevalent in computer science.
150,528
This is a code review for a set of loggers following [this](https://stackoverflow.com/questions/41175864/how-to-assure-contract-with-multiple-classes-that-are-similar-in-behavior-but-di/41230131?noredirect=1#comment69660624_41230131) question. The project is a universal windows application targeting Windows Phone. There are concerns over the tight coupling between the loggers and App. There is way too much code in the main program that is responsible for setting up the logger just right. There are also concerns on how to deal with the fact that a ReleaseLogger requires special behavior (establishing a session) that the DebugLogger class does not, and how to deal with this. App.xaml.cs ``` using Log.Common; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Foundation.Diagnostics; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Animation; using Windows.UI.Xaml.Navigation; // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227 namespace Log { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> public sealed partial class App : Application { #if WINDOWS_PHONE_APP private TransitionCollection transitions; #endif public const string TelemetryUrl = "http://try.count.ly"; public const string TelemetryAppKey = ""; private ILogger _logger; private ILogger Logger { get { if(null == _logger) { //#if PROD _logger = new ReleaseLogger(); //#else //_logger = new DebugLogger(); //#endif } return _logger; } } /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += this.OnSuspending; this.Resuming += this.OnResuming; this.UnhandledException += OnUnhandledException; } private async Task TryStartTelemetry() { var logger = Logger as ReleaseLogger; if (null != logger) { await logger.StartSessionAsync(this, TelemetryUrl, TelemetryAppKey); } } private async Task TryEndTelemetry() { var logger = Logger as ReleaseLogger; if (null != logger) { await logger.EndSessionAsync(); } } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override async void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); // TODO: change this value to a cache size that is appropriate for your application rootFrame.CacheSize = 1; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { #if WINDOWS_PHONE_APP // Removes the turnstile navigation for startup. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; #endif // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(MainPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } await TryStartTelemetry(); Logger.Log("Application Launched", LoggingLevel.Information, null); // Ensure the current window is active Window.Current.Activate(); } protected override async void OnActivated(IActivatedEventArgs args) { base.OnActivated(args); await TryStartTelemetry(); } #if WINDOWS_PHONE_APP /// <summary> /// Restores the content transitions after the app has launched. /// </summary> /// <param name="sender">The object where the handler is attached.</param> /// <param name="e">Details about the navigation event.</param> private void RootFrame_FirstNavigated(object sender, NavigationEventArgs e) { var rootFrame = sender as Frame; rootFrame.ContentTransitions = this.transitions ?? new TransitionCollection() { new NavigationThemeTransition() }; rootFrame.Navigated -= this.RootFrame_FirstNavigated; } #endif /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private async void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); // TODO: Save application state and stop any background activity await TryEndTelemetry(); deferral.Complete(); } private async void OnResuming(object sender, object e) { await TryStartTelemetry(); } private async void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) { await TryEndTelemetry(); } } } ``` ILogger.cs ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using Windows.Foundation.Diagnostics; namespace Log.Common { public interface ILogger { void LogException(Exception ex); void Log(string message, LoggingLevel loggingLevel, params object[] args); } } ``` DebugLogger.cs ``` using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Foundation.Diagnostics; namespace Log.Common { public class DebugLogger : ILogger { public void LogException(Exception ex) { if (ex == null) throw new ArgumentNullException("exception"); Debug.WriteLine("Exception: " + ex.Message); // Log to UI here. } public void Log(string message, LoggingLevel loggingLevel, params object[] args) { if (string.IsNullOrWhiteSpace(message)) throw new ArgumentException("message"); if (args != null && args.Length > 0) { message = string.Format(message, args); } //TODO: let's define when and where log switch (loggingLevel) { case LoggingLevel.Critical: Debug.WriteLine("Critical: " + message, args); // Log to UI here. break; case LoggingLevel.Error: Debug.WriteLine("Error: " + message, args); // Log to UI here. break; case LoggingLevel.Warning: Debug.WriteLine("Warning: " + message, args); // Log to UI here. break; case LoggingLevel.Information: Debug.WriteLine("Info: " + message, args); // Log to UI here. break; case LoggingLevel.Verbose: Debug.WriteLine("Verbose: " + message, args); break; default: throw new ArgumentOutOfRangeException(nameof(loggingLevel), loggingLevel, null); } } } } ``` ReleaseLogger.cs ``` using CountlySDK; using Log; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Foundation.Diagnostics; using Windows.UI.Xaml; namespace Log.Common { public class ReleaseLogger : ILogger { private bool _sessionStarted; // A Queue of exceptions to log. private Queue<Exception> _exceptionQueue; public ReleaseLogger() { _exceptionQueue = new Queue<Exception>(); _sessionStarted = false; Countly.IsLoggingEnabled = true; } public async Task StartSessionAsync(Application app, string telemetryUrl, string telemetryAppKey) { if (telemetryUrl == null) throw new ArgumentNullException("telemetryUrl"); if (telemetryAppKey == null) throw new ArgumentNullException("telemetryAppKey"); try { await Countly.StartSession(telemetryUrl, telemetryAppKey, app); while (_exceptionQueue.Count > 0) { await LogExceptionAsync(_exceptionQueue.Dequeue()); } _sessionStarted = true; } catch (Exception countlyEx) { // Log to UI here. } } public async Task EndSessionAsync() { try { await Countly.EndSession(); } catch (Exception countlyEx) { // Log to UI here. } finally { _sessionStarted = false; // Log to UI here. } } public async Task LogExceptionAsync(Exception ex) { if (ex == null) throw new ArgumentNullException("exception"); if (_sessionStarted) { try { await Countly.RecordException(ex.Message, ex.StackTrace); } catch (Exception countlyEx) { // Log to UI here. } } else { _exceptionQueue.Enqueue(ex); } } public void LogException(Exception ex) { var result = LogExceptionAsync(ex); } public async Task LogAsync(string message, LoggingLevel loggingLevel, params object[] args) { if (string.IsNullOrWhiteSpace(message)) throw new ArgumentException("message"); if (args != null && args.Length > 0) { message = string.Format(message, args); } switch (loggingLevel) { case LoggingLevel.Critical: case LoggingLevel.Error: // Log to UI here. await Countly.RecordException(message); break; case LoggingLevel.Warning: // Log to UI here. break; case LoggingLevel.Information: await Countly.RecordEvent(message); // Log to UI here. break; case LoggingLevel.Verbose: Debug.WriteLine(message, args); break; default: throw new ArgumentOutOfRangeException(nameof(loggingLevel), loggingLevel, null); } } public void Log(string message, LoggingLevel loggingLevel, params object[] args) { var result = LogAsync(message, loggingLevel, args); } } } ```
2016/12/21
['https://codereview.stackexchange.com/questions/150528', 'https://codereview.stackexchange.com', 'https://codereview.stackexchange.com/users/42250/']
Interesting question, * I noticed that 9-3\*3 does not return 0, but 27, you are not following PEMDAS * Personally, I would make sure that the input only contains numbers, dots, and math operators, and then use `eval`. `eval("9-3*3")` does return correctly 0. * 0.0022 \* 2 returns zero. * I would assign html elements like the one found from `document.getElementById(numberScreen)` to a higher scope variable for readability and performance * You do not check for existing periods in the current number, allowing for numbers like 12.24.2016 * Using a pure UI function (`innerHTML`) to drive the logic is wrong. It's okay for a beginner class, but anything more advanced should drive of (`id`). You dont want to replace 'x' with '\*' and also having to change the JS code * Your indentation is not perfect, use <http://jsbeautifier.org/> * You have zero warnings on jshint.com, which is amazing
Just a few side notes: To ordinary people, `%` means *percent*. Only programmers think of `%` being the modulus (or remainder, depending on the language) operator. Since your calculator is intended for ordinary people, the `%` means exactly what it should. You should add a function to display a result: ``` function display(result) { document.getElementById(numberScreen).innerHTML = result; } ``` With this function you don't need to mention `numberScreen` anywhere else in the code, which is good since the calculator code should talk about numbers and operators, not about manipulating HTML.
58,593,349
This comes from an exercise in book *Haskell from First Principles*. The exercise is to implement `Applicative` for `ZipList'`, which is analogous to the Prelude's `ZipList`. The book has this hint > > Check Prelude > for functions that can give you what you need. One starts > with the letter `z`, the other with the letter `r`. You’re looking > for inspiration from these functions, not to be able to directly > reuse them as you’re using a custom `List` type, not the > `Prelude` provided list type. > > > I guessed the function that starts with `z` is `zipWith`, but I do not know about a function that starts with `r`. ``` data List a = Nil | Cons a (List a) deriving (Eq, Show) zipWith' :: (a -> b -> c) -> List a -> List b -> List c zipWith' _ Nil _ = Nil zipWith' _ _ Nil = Nil zipWith' f (Cons x xs) (Cons y ys) = Cons (f x y) (zipWith' f xs ys) newtype ZipList' a = ZipList' (List a) deriving (Eq, Show) instance Functor ZipList' where fmap f (ZipList' xs) = ZipList' $ fmap f xs instance Applicative ZipList' where pure x = ZipList' $ Cons x Nil (ZipList' fs) <*> (ZipList' xs) = ZipList' $ zipWith' ($) fs xs ``` This passes a test case in the book, but I am wondering if there's a better way to implement it since I did not use a function that starts with `r`. I have a feeling this was supposed to be `repeat` because it's also supposed to work over infinite lists.
2019/10/28
['https://Stackoverflow.com/questions/58593349', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4281998/']
Using a combination of `ADDRESS` and `MATCH` should help: ``` =ADDRESS(MATCH(YEAR(L12),Table!$A$1:$A$26,0),MATCH(MONTH(L12),Table!$A$1:$M$1,0)) ``` [![enter image description here](https://i.stack.imgur.com/9i3DR.png)](https://i.stack.imgur.com/9i3DR.png) Table: [![enter image description here](https://i.stack.imgur.com/mK5Lr.png)](https://i.stack.imgur.com/mK5Lr.png)
I always suggest using `INDEX`/`MATCH` instead of `VLOOKUP`. `INDEX`/`MATCH` can do everything `VLOOKUP` (and `HLOOKUP`) can do but it is: * faster (important when used in many cells); * more versatile (the value you are looking up does not need to be in a column to the right); * more robust (inserting columns does not break it); * easier to use (no column counting required); If you used an `INDEX`/`MATCH` formula, such as this: ``` =INDEX(Table!$B$4:$M$65,MATCH(YEAR(L12),Table!$A$4:$A$65,0),MATCH(MONTH(L12),Table!$B$3:$M$3,0)) ``` You could put it straight into a `CELL` function to return the full address: ``` =CELL( "address", INDEX(Table!$B$4:$M$65,MATCH(YEAR(L12),Table!$A$4:$A$65,0),MATCH(MONTH(L12),Table!$B$3:$M$3,0)) ) ``` Example Table: [![enter image description here](https://i.stack.imgur.com/cJPDf.png)](https://i.stack.imgur.com/cJPDf.png) Example Result: [![enter image description here](https://i.stack.imgur.com/LFpGU.png)](https://i.stack.imgur.com/LFpGU.png) **AUTOMATICALLY COLOUR THE VALUE IN THE TABLE** You do not need the address to highlight the value in the table. Just create a conditional formatting rule for `$B$4:$M$65`: ``` =AND(MONTH(Sheet2!$L$12)=B$3,YEAR(Sheet2!$L$12)=$A4) ``` [![enter image description here](https://i.stack.imgur.com/TIpZ1.png)](https://i.stack.imgur.com/TIpZ1.png)
1,262,376
I am using jquery, JSON, and AJAX for a comment system. I am curious, is there a size limit on what you can send through/store with JSON? Like if a user types a large amount and I send it through JSON is there some sort of maximum limit? Also can any kind of text be sent through JSON. for example sometime I allow users to use html, will this be ok?
2009/08/11
['https://Stackoverflow.com/questions/1262376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/143030/']
JSON is similar to other data formats like XML - if you need to transmit more data, you just send more data. There's no inherent size limitation to the JSON request. Any limitation would be set by the server parsing the request. (For instance, ASP.NET has the "MaxJsonLength" property of the serializer.)
Implementations are free to set limits on JSON documents, including the size, so choose your parser wisely. See [RFC 7159](https://www.rfc-editor.org/rfc/rfc7159), Section 9. Parsers: "An implementation may set limits on the size of texts that it accepts. An implementation may set limits on the maximum depth of nesting. An implementation may set limits on the range and precision of numbers. An implementation may set limits on the length and character contents of strings."
1,262,376
I am using jquery, JSON, and AJAX for a comment system. I am curious, is there a size limit on what you can send through/store with JSON? Like if a user types a large amount and I send it through JSON is there some sort of maximum limit? Also can any kind of text be sent through JSON. for example sometime I allow users to use html, will this be ok?
2009/08/11
['https://Stackoverflow.com/questions/1262376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/143030/']
It depends on the implementation of your JSON writer/parser. Microsoft's DataContractJsonSerializer seems to have a hard limit around 8kb (8192 I think), and it will error out for larger strings. Edit: We were able to resolve the 8K limit for JSON strings by setting the MaxJsonLength property in the web config as described in this answer: <https://stackoverflow.com/a/1151993/61569>
What is the requirement? Are you trying to send a large SQL Table as JSON object? I think **it is not practical**. You will consume a **large chunk of server resource** if you push thru with this. You will also not be able to measure the progress with a progress bar because your App will just wait for the server to reply back which would take ages. What I recommend to do is to chop the request into batches say first 1000 then request again the next 1000 till you get what you need. This way you could also put a nice progress bar to know the progress as extracting that amount of data could really take too long.
1,262,376
I am using jquery, JSON, and AJAX for a comment system. I am curious, is there a size limit on what you can send through/store with JSON? Like if a user types a large amount and I send it through JSON is there some sort of maximum limit? Also can any kind of text be sent through JSON. for example sometime I allow users to use html, will this be ok?
2009/08/11
['https://Stackoverflow.com/questions/1262376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/143030/']
There is no fixed limit on how large a JSON data block is or any of the fields. There are limits to how much JSON the JavaScript implementation of various browsers can handle (e.g. around 40MB in my experience). See [this question for example](https://stackoverflow.com/questions/4833480/have-i-reached-the-limits-of-the-size-of-objects-javascript-in-my-browser-can-ha).
Surely everyone's missed a trick here. The current file size limit of a json file is 18,446,744,073,709,551,616 characters or if you prefer bytes, or even 2^64 bytes if you're looking at 64 bit infrastructures at least. For all intents, and purposes we can assume it's unlimited as you'll probably have a hard time hitting this issue...
1,262,376
I am using jquery, JSON, and AJAX for a comment system. I am curious, is there a size limit on what you can send through/store with JSON? Like if a user types a large amount and I send it through JSON is there some sort of maximum limit? Also can any kind of text be sent through JSON. for example sometime I allow users to use html, will this be ok?
2009/08/11
['https://Stackoverflow.com/questions/1262376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/143030/']
JSON is similar to other data formats like XML - if you need to transmit more data, you just send more data. There's no inherent size limitation to the JSON request. Any limitation would be set by the server parsing the request. (For instance, ASP.NET has the "MaxJsonLength" property of the serializer.)
It depends on the implementation of your JSON writer/parser. Microsoft's DataContractJsonSerializer seems to have a hard limit around 8kb (8192 I think), and it will error out for larger strings. Edit: We were able to resolve the 8K limit for JSON strings by setting the MaxJsonLength property in the web config as described in this answer: <https://stackoverflow.com/a/1151993/61569>
1,262,376
I am using jquery, JSON, and AJAX for a comment system. I am curious, is there a size limit on what you can send through/store with JSON? Like if a user types a large amount and I send it through JSON is there some sort of maximum limit? Also can any kind of text be sent through JSON. for example sometime I allow users to use html, will this be ok?
2009/08/11
['https://Stackoverflow.com/questions/1262376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/143030/']
There is no fixed limit on how large a JSON data block is or any of the fields. There are limits to how much JSON the JavaScript implementation of various browsers can handle (e.g. around 40MB in my experience). See [this question for example](https://stackoverflow.com/questions/4833480/have-i-reached-the-limits-of-the-size-of-objects-javascript-in-my-browser-can-ha).
What is the requirement? Are you trying to send a large SQL Table as JSON object? I think **it is not practical**. You will consume a **large chunk of server resource** if you push thru with this. You will also not be able to measure the progress with a progress bar because your App will just wait for the server to reply back which would take ages. What I recommend to do is to chop the request into batches say first 1000 then request again the next 1000 till you get what you need. This way you could also put a nice progress bar to know the progress as extracting that amount of data could really take too long.
1,262,376
I am using jquery, JSON, and AJAX for a comment system. I am curious, is there a size limit on what you can send through/store with JSON? Like if a user types a large amount and I send it through JSON is there some sort of maximum limit? Also can any kind of text be sent through JSON. for example sometime I allow users to use html, will this be ok?
2009/08/11
['https://Stackoverflow.com/questions/1262376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/143030/']
Surely everyone's missed a trick here. The current file size limit of a json file is 18,446,744,073,709,551,616 characters or if you prefer bytes, or even 2^64 bytes if you're looking at 64 bit infrastructures at least. For all intents, and purposes we can assume it's unlimited as you'll probably have a hard time hitting this issue...
What is the requirement? Are you trying to send a large SQL Table as JSON object? I think **it is not practical**. You will consume a **large chunk of server resource** if you push thru with this. You will also not be able to measure the progress with a progress bar because your App will just wait for the server to reply back which would take ages. What I recommend to do is to chop the request into batches say first 1000 then request again the next 1000 till you get what you need. This way you could also put a nice progress bar to know the progress as extracting that amount of data could really take too long.
1,262,376
I am using jquery, JSON, and AJAX for a comment system. I am curious, is there a size limit on what you can send through/store with JSON? Like if a user types a large amount and I send it through JSON is there some sort of maximum limit? Also can any kind of text be sent through JSON. for example sometime I allow users to use html, will this be ok?
2009/08/11
['https://Stackoverflow.com/questions/1262376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/143030/']
There is really no limit on the size of JSON data to be send or receive. We can send Json data in file too. According to the capabilities of browser that you are working with, Json data can be handled.
The maximum length of JSON strings. The default is 2097152 characters, which is equivalent to 4 MB of Unicode string data. Refer below URL <https://learn.microsoft.com/en-us/dotnet/api/system.web.script.serialization.javascriptserializer.maxjsonlength?view=netframework-4.7.2>
1,262,376
I am using jquery, JSON, and AJAX for a comment system. I am curious, is there a size limit on what you can send through/store with JSON? Like if a user types a large amount and I send it through JSON is there some sort of maximum limit? Also can any kind of text be sent through JSON. for example sometime I allow users to use html, will this be ok?
2009/08/11
['https://Stackoverflow.com/questions/1262376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/143030/']
Implementations are free to set limits on JSON documents, including the size, so choose your parser wisely. See [RFC 7159](https://www.rfc-editor.org/rfc/rfc7159), Section 9. Parsers: "An implementation may set limits on the size of texts that it accepts. An implementation may set limits on the maximum depth of nesting. An implementation may set limits on the range and precision of numbers. An implementation may set limits on the length and character contents of strings."
The maximum length of JSON strings. The default is 2097152 characters, which is equivalent to 4 MB of Unicode string data. Refer below URL <https://learn.microsoft.com/en-us/dotnet/api/system.web.script.serialization.javascriptserializer.maxjsonlength?view=netframework-4.7.2>
1,262,376
I am using jquery, JSON, and AJAX for a comment system. I am curious, is there a size limit on what you can send through/store with JSON? Like if a user types a large amount and I send it through JSON is there some sort of maximum limit? Also can any kind of text be sent through JSON. for example sometime I allow users to use html, will this be ok?
2009/08/11
['https://Stackoverflow.com/questions/1262376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/143030/']
It depends on the implementation of your JSON writer/parser. Microsoft's DataContractJsonSerializer seems to have a hard limit around 8kb (8192 I think), and it will error out for larger strings. Edit: We were able to resolve the 8K limit for JSON strings by setting the MaxJsonLength property in the web config as described in this answer: <https://stackoverflow.com/a/1151993/61569>
The maximum length of JSON strings. The default is 2097152 characters, which is equivalent to 4 MB of Unicode string data. Refer below URL <https://learn.microsoft.com/en-us/dotnet/api/system.web.script.serialization.javascriptserializer.maxjsonlength?view=netframework-4.7.2>
1,262,376
I am using jquery, JSON, and AJAX for a comment system. I am curious, is there a size limit on what you can send through/store with JSON? Like if a user types a large amount and I send it through JSON is there some sort of maximum limit? Also can any kind of text be sent through JSON. for example sometime I allow users to use html, will this be ok?
2009/08/11
['https://Stackoverflow.com/questions/1262376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/143030/']
JSON is similar to other data formats like XML - if you need to transmit more data, you just send more data. There's no inherent size limitation to the JSON request. Any limitation would be set by the server parsing the request. (For instance, ASP.NET has the "MaxJsonLength" property of the serializer.)
Surely everyone's missed a trick here. The current file size limit of a json file is 18,446,744,073,709,551,616 characters or if you prefer bytes, or even 2^64 bytes if you're looking at 64 bit infrastructures at least. For all intents, and purposes we can assume it's unlimited as you'll probably have a hard time hitting this issue...
40,901,121
I'm using AsyncTask to request json data through php which is uploaded in AWS cloud. Below is my code: `@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { new JsonTask().execute("http://XXX.qiykuanrge.us-west-2.elasticbeanstalk.com/index.php/?key=leg"); return leg_state_view; }` ``` public class JsonTask extends AsyncTask<String, String, List<CongressModel>> { @Override protected List<CongressModel> doInBackground(String... params) { HttpURLConnection connection = null; BufferedReader reader = null; try { URL url = new URL(params[0]); connection = (HttpURLConnection) url.openConnection(); connection.connect(); ``` ... I got this error: java.net.UnknownHostException: Unable to resolve host "csci571.qiykuanrge.us-west-2.elasticbeanstalk.com": No address associated with hostname my php looks like this: ```js <?php date_default_timezone_set('UTC'); header('Access-Control-Allow-Origin: *'); if (isset($_GET["key"])) { if ($_GET["key"] == "leg") { $url = "http://104.198.0.197:8080/legislators?order=state__asc,last_name__asc&per_page=all&apikey="; $content = file_get_contents($url); echo $content; } ``` Does someone know what is going on?
2016/12/01
['https://Stackoverflow.com/questions/40901121', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5538299/']
There is no need to use jquery. Just use **ng-class** and add a condition to show or hide that class to your post. Se snipped how content is shown or hidden with the hidden class according to property `post.readMore` in the controller ```js angular.module('myapp', []) .controller('foo', function($scope) { $scope.post = { readMore: true, fields: { title: 'The post title', date: new Date() } } $scope.showReadMore = function(post) { post.readMore = true; } $scope.hideReadmore = function(post) { post.readMore = false; } }); ``` ```html <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <style type="text/css"> .hidden { display: none; } </style> </head> <body ng-app="myapp"> <div ng-controller="foo"> <div ng-if="!post.firstFeatured" class="col-sm-10 blog-content blogPreview" style="max-width: 400px"> <a ng-click="goToPostDetail(post, $index)"> <img class="img-responsive img-blog" ng-src="{{ post.fields.image.fields.file.url }}" width="100%" alt="" /> <div class="blogOverlay" ng-class="{'hidden' : !post.readMore}" ng-mouseover="showReadMore(post)" ng-mouseleave="hideReadmore(post)"> <h2>{{ post.fields.title }}</h2> </div> <div class="newOverlay" ng-class="{'hidden' : post.readMore}" ng-mouseleave="showReadMore(post)" ng-mouseover="hideReadmore(post)"> <h2>{{ post.fields.title }}</h2> <h3>{{post.fields.date}}</h3> <a class="btn btn-primary readmore" ng-click="goToPostDetail(post, $index)">Read More</a> </div> </a> </div> </div> </body> </html> ```
give class name something like `class="blogOverlay_{{$index}}"` and then pass `$index` to JavaScript like `showReadMore($index)` This way Your class names are unique and they will change for only `index` you want to change
40,901,121
I'm using AsyncTask to request json data through php which is uploaded in AWS cloud. Below is my code: `@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { new JsonTask().execute("http://XXX.qiykuanrge.us-west-2.elasticbeanstalk.com/index.php/?key=leg"); return leg_state_view; }` ``` public class JsonTask extends AsyncTask<String, String, List<CongressModel>> { @Override protected List<CongressModel> doInBackground(String... params) { HttpURLConnection connection = null; BufferedReader reader = null; try { URL url = new URL(params[0]); connection = (HttpURLConnection) url.openConnection(); connection.connect(); ``` ... I got this error: java.net.UnknownHostException: Unable to resolve host "csci571.qiykuanrge.us-west-2.elasticbeanstalk.com": No address associated with hostname my php looks like this: ```js <?php date_default_timezone_set('UTC'); header('Access-Control-Allow-Origin: *'); if (isset($_GET["key"])) { if ($_GET["key"] == "leg") { $url = "http://104.198.0.197:8080/legislators?order=state__asc,last_name__asc&per_page=all&apikey="; $content = file_get_contents($url); echo $content; } ``` Does someone know what is going on?
2016/12/01
['https://Stackoverflow.com/questions/40901121', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5538299/']
There is no need to use jquery. Just use **ng-class** and add a condition to show or hide that class to your post. Se snipped how content is shown or hidden with the hidden class according to property `post.readMore` in the controller ```js angular.module('myapp', []) .controller('foo', function($scope) { $scope.post = { readMore: true, fields: { title: 'The post title', date: new Date() } } $scope.showReadMore = function(post) { post.readMore = true; } $scope.hideReadmore = function(post) { post.readMore = false; } }); ``` ```html <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <style type="text/css"> .hidden { display: none; } </style> </head> <body ng-app="myapp"> <div ng-controller="foo"> <div ng-if="!post.firstFeatured" class="col-sm-10 blog-content blogPreview" style="max-width: 400px"> <a ng-click="goToPostDetail(post, $index)"> <img class="img-responsive img-blog" ng-src="{{ post.fields.image.fields.file.url }}" width="100%" alt="" /> <div class="blogOverlay" ng-class="{'hidden' : !post.readMore}" ng-mouseover="showReadMore(post)" ng-mouseleave="hideReadmore(post)"> <h2>{{ post.fields.title }}</h2> </div> <div class="newOverlay" ng-class="{'hidden' : post.readMore}" ng-mouseleave="showReadMore(post)" ng-mouseover="hideReadmore(post)"> <h2>{{ post.fields.title }}</h2> <h3>{{post.fields.date}}</h3> <a class="btn btn-primary readmore" ng-click="goToPostDetail(post, $index)">Read More</a> </div> </a> </div> </div> </body> </html> ```
You need not complicate much Check out the below css and live plunker ``` .blue{ background-color:blue; } .red{ background-color:red; } .blue:hover { background-color:yellow; visibility:hidden } ``` [PLUNKER DEMO](https://plnkr.co/edit/7RRlxmvTnggyw2LnOzPq?p=preview) Update 1 : Hides and shows
14,297,940
I need help with making a certain MFC program. I need to make a program that will draw a line in the following way: the user chooses the starting point by left clicking, and the final point by left clicking the second time, after which the points are connected and the line is drawn. I've managed to get the coordinates of the first one with this: ``` void CsemView::OnLButtonDown(UINT nFlags, CPoint point) { CsemDoc* pDoc= GetDocument(); // TODO: Add your message handler code here and/or call default pDoc->a_pos=point; Invalidate(); CView::OnLButtonDown(nFlags, point); } ``` The problem is, i don't know how to get the coordinates of the second one with the second left click. I've managed to do it by using the on double left click function( and putting pDoc->b\_pos=point; in it), but that's not really what I was supposed to do. (I was putting in the coordinates of the first one into MoveTo and the second one into LineTo). I would appreciate if someone could help me (I'm suspecting there's perhaps a different, simpler way of doing this). Thanks in advance.
2013/01/12
['https://Stackoverflow.com/questions/14297940', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1973086/']
If you want to get two results from a same event, you have to keep a state variable to track wht click is it. On other words, your `CsemDoc` should have an `a_pos` and `b_pos` members, and `CsemView` a `bool is_b`, initialized as false. The `OnLButtonDow` method should: be something like ``` if(!is_b) { set the a_pos; is_b = true; } else { set the b_pos; is_b = false; invalidate the draw; } ```
You can push the mouse co-ordinates on each LButtonDown to a vector and draw the lines between P[i] and P[i+1] and upon a RButtonDown you can stop recording of the points after that and no more extra lines will be drawn. Have a separate button like any drawing toolbox to start the line drawing so that any LButtonDown events after that will be pushed to the vector. Hope this helps!
18,226,698
I have 2 pages when button in page1 is clicked it will linked to the page 2, then the page2 will load with transition. The page loads with fade in and doesnt work with slidedown. ``` $(document).ready(function() { $("body").css("display", "none"); $("body").fadeIn(2000); }); ``` The code above works well,but the below doesnt work: ``` $(document).ready(function() { $("body").css("display", "none"); $("body").slideDown(2000); }); ``` My full code ``` <meta http-equiv="Page-Enter" content="blendTrans(Duration=1.0)"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>About</title> <script type="text/javascript" src="C:/Users/jovine/Desktop/Anything/BAS/jquery.min.js"></script> <script type="text/javascript" src="C:/Users/jovine/Desktop/Anything/BAS/jquery.fullbg.min.js"></script> <link type="text/css" rel="stylesheet" href="basabout.css" media="all" /> <script type="text/javascript"> $(window).load(function(){ $("body").slideUp(1).delay(2000).slideDown('slow'); }); </script> </head> <body> <img class="fullbg" src="background2.png" id="background" style="z-index:-9999; " /> <script type="text/javascript"> $(window).load(function() { $("#background").fullBg(); }); </script> <div id="header" class="header"> <img class="title" src="aboutus.png"> <br> <img class="triangle" src="triangle.png"> </div> <div id="content" class="content"> <img class="subtitle" src="about.png"> <br /> <p class="subtitle_content">We are the voice of the Beauty industry in Singapore. <hr class="divider"> <div class="logo"> <img src="peoples.png" style="margin-left:70px;"> <img src="roll.png" style="margin-left:340px;"> <img src="mic.png" style="margin-left:440px;"> </div> <div class="logo_title"> <img src="whoarewe.png" style="margin-left:40px;"> <img src="whatwedo.png" style="margin-left:320px;"> <img src="whatscomingup.png" style="margin-left:420px;"> </div> <div id="logo_content" class="logo_content"> <p class="content1">BAS stand for Beauty Association of<br>Singapore. BAS was built to contribute<br>to the development, advancement and<br>prestige of the Beauty industry in<br>Singapore.</p> <p class="content2">We are inspired by purpose, and we<br>strive to be the voice of the burgeoning<br>Beauty industry in Singapore.</p> <p class="content3">STAY TUNED!</p> </div> </div> </body> </html> ```
2013/08/14
['https://Stackoverflow.com/questions/18226698', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2681621/']
Have you tried using shutil? ``` import shutil shutil.copy(src, dst) ```
There may be a problem with the way Python is passing the arguments to the shell command. Try using [subprocess.call](http://docs.python.org/2/library/subprocess.html#using-the-subprocess-module). This method takes arguments as an array and passes them that way to the command: ``` import subprocess subprocess.call(["copy", "/b", '"imgFile.jpg" + "zipFile.zip"', "newImage.jpg"]) ```
57,350,378
I'd like to see if it would be possible to convert a `BubbleSort` function, such as: ``` def BubbleSort(l): for i in range(len(l)-1): for j in range(len(l)-1-i): if (l[j]>l[j+1]): l[j],l[j+1]=l[j+1],l[j] return l ``` to a one-liner list comprehension, maybe similar to: ``` def BubbleSort(l): return [something_goes_here for i in range(len(l)-1) for j in range(len(l)-1-i) if (l[j]>l[j+1])] ``` ### Sample Input: ``` print(BubbleSort([1,5,-5,0,10,100])) ``` ### Sample Output ``` [-5, 0, 1, 5, 10, 100] ```
2019/08/04
['https://Stackoverflow.com/questions/57350378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6553328/']
A solution based on side-effects looks like this: ``` def bubblesort(l): [l.append(l.pop(0) if i == len(l) - 1 or l[0] < l[1] else l.pop(1)) for j in range(0, len(l)) for i in range(0, len(l))] return l ``` This will sort the list `l` in-place. The basic idea is to treat `l` as both the input and output-list. Swaps can then be emulated by either moving the first or the second element of `l` to the end. The last element must be moved to the end without any comparison to get a new list list. A visual example of one iteration (`[l.append(l.pop(0) if i == len(l) - 1 or l[0] < l[1] else l.pop(1)) for i in range(0, len(l))]`): ``` 1 3 2 6 5 4 | 3 2 6 5 4 | 1 3 6 5 4 | 1 2 6 5 4 | 1 2 3 6 4 | 1 2 3 5 6 | 1 2 3 5 4 | 1 2 3 5 4 6 ``` In this example `|` denotes the separator between the last element of the original list and the first element that was already appended. Repeating this process `len(l)` times guarantees that the entire list is sorted. Note that while this example does perform a bubblesort, it's runtime is `O(n^3)`, since we need to remove the first or second element from the list in each step, which runs in `O(n)`. EDIT: It becomes more easy to see that this is actually bubblesort from the above algorithm, if we rewrite the sample-iteration as such: ``` | 1 3 2 6 5 4 1 | 3 2 6 5 4 1 2 | 3 6 5 4 1 2 3 | 6 5 4 1 2 3 5 | 6 4 1 2 3 5 4 | 6 1 2 3 5 4 6 | ``` Here the separator denotes the end of the list and a circular view of the list is used. EDIT 2: Found a more efficient way to solve this that uses slice-assignment: ``` def bubblesort(l): [l.__setitem__(slice(i, i + 2), (l[i:i + 2] if l[i] < l[i + 1] else l[i + 1:i - 1:-1])) for j in range(0, len(l)) for i in range(0, len(l) - 1)] return l ```
Using a list comprehension to hide a for loop is kind of cheating given that the result produced by the comprehension is not the sorted list. But if you're going to do that, you might want to avoid building a list of None elements by performing the swaps in the condition rather than as the output value. For example: ``` a = [1, 3, 2, 6, 5, 4] [_ for n in range(len(a),1,-1) for i in range(n-1) if a[i]>a[i+1] and a.__setitem__(slice(i,i+2),a[i:i+2][::-1])] ``` Isolating the element swapping part, this would give: ``` swap = lambda(a,i):a.__setitem__(slice(i,i+2),a[i:i+2][::-1]) [_ for n in range(len(a),1,-1) for i in range(n-1) if a[i]>a[i+1] and swap(a,i)] ``` Which is no different from: ``` for n in range(len(a),1,-1): for i in range(n-1): if a[i]>a[i+1]: swap(a,i) # same as a[i],a[i+1] = a[i+1],a[i] ``` The list comprehension is merely a different way to write the for loop and is not actually returning the sorted result. What would be more in the spirit of a list comprehension is to actually return the sorted result without affecting the original list. You can do this using a temporary list within the comprehension to perform the element swapping and progressively return the position that is guaranteed to be at the right sorted index: ``` a = [1, 3, 2, 6, 5, 4] s = [ b.pop(-1) for b in [list(a)] for n in range(len(a),0,-1) if not [_ for i in range(n-1) if b[i]<b[i+1] and b.__setitem__(slice(i,i+2),b[i:i+2][::-1])] ] print(s) # [1, 2, 3, 4, 5, 6] ``` The approach is the same as before except that `b` is used internally to manage swapping and return the sorted values. Because the guaranteed sorted position is always the last one in `b`, the swapping condition was reversed so that internally `b` is sorted in descending order which produces the output in ascending order when taking the last item at each iteration. Note that all these solutions fail to implement the early exit condition that allows bubble sort to be very efficient on already sorted lists and lists where elements are near their sorted position (i.e. stop when no swaps in a pass). The number of iterations will always be N\*(N+1)/2 no matter the original order of elements giving a time complexity of O(N^2) all the time instead of worst case.
57,350,378
I'd like to see if it would be possible to convert a `BubbleSort` function, such as: ``` def BubbleSort(l): for i in range(len(l)-1): for j in range(len(l)-1-i): if (l[j]>l[j+1]): l[j],l[j+1]=l[j+1],l[j] return l ``` to a one-liner list comprehension, maybe similar to: ``` def BubbleSort(l): return [something_goes_here for i in range(len(l)-1) for j in range(len(l)-1-i) if (l[j]>l[j+1])] ``` ### Sample Input: ``` print(BubbleSort([1,5,-5,0,10,100])) ``` ### Sample Output ``` [-5, 0, 1, 5, 10, 100] ```
2019/08/04
['https://Stackoverflow.com/questions/57350378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6553328/']
A solution based on side-effects looks like this: ``` def bubblesort(l): [l.append(l.pop(0) if i == len(l) - 1 or l[0] < l[1] else l.pop(1)) for j in range(0, len(l)) for i in range(0, len(l))] return l ``` This will sort the list `l` in-place. The basic idea is to treat `l` as both the input and output-list. Swaps can then be emulated by either moving the first or the second element of `l` to the end. The last element must be moved to the end without any comparison to get a new list list. A visual example of one iteration (`[l.append(l.pop(0) if i == len(l) - 1 or l[0] < l[1] else l.pop(1)) for i in range(0, len(l))]`): ``` 1 3 2 6 5 4 | 3 2 6 5 4 | 1 3 6 5 4 | 1 2 6 5 4 | 1 2 3 6 4 | 1 2 3 5 6 | 1 2 3 5 4 | 1 2 3 5 4 6 ``` In this example `|` denotes the separator between the last element of the original list and the first element that was already appended. Repeating this process `len(l)` times guarantees that the entire list is sorted. Note that while this example does perform a bubblesort, it's runtime is `O(n^3)`, since we need to remove the first or second element from the list in each step, which runs in `O(n)`. EDIT: It becomes more easy to see that this is actually bubblesort from the above algorithm, if we rewrite the sample-iteration as such: ``` | 1 3 2 6 5 4 1 | 3 2 6 5 4 1 2 | 3 6 5 4 1 2 3 | 6 5 4 1 2 3 5 | 6 4 1 2 3 5 4 | 6 1 2 3 5 4 6 | ``` Here the separator denotes the end of the list and a circular view of the list is used. EDIT 2: Found a more efficient way to solve this that uses slice-assignment: ``` def bubblesort(l): [l.__setitem__(slice(i, i + 2), (l[i:i + 2] if l[i] < l[i + 1] else l[i + 1:i - 1:-1])) for j in range(0, len(l)) for i in range(0, len(l) - 1)] return l ```
``` def bubblesort(l): [[l.insert(j+1, l.pop(j)) for j in range(i) if l[j] > l[j+1]] for i in range(len(l)-1,0,-1)] return l ``` I use the `l.insert(j+1, l.pop(j))` to swap the elements in the list. The rest are just the nested loops.
57,350,378
I'd like to see if it would be possible to convert a `BubbleSort` function, such as: ``` def BubbleSort(l): for i in range(len(l)-1): for j in range(len(l)-1-i): if (l[j]>l[j+1]): l[j],l[j+1]=l[j+1],l[j] return l ``` to a one-liner list comprehension, maybe similar to: ``` def BubbleSort(l): return [something_goes_here for i in range(len(l)-1) for j in range(len(l)-1-i) if (l[j]>l[j+1])] ``` ### Sample Input: ``` print(BubbleSort([1,5,-5,0,10,100])) ``` ### Sample Output ``` [-5, 0, 1, 5, 10, 100] ```
2019/08/04
['https://Stackoverflow.com/questions/57350378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6553328/']
Using a list comprehension to hide a for loop is kind of cheating given that the result produced by the comprehension is not the sorted list. But if you're going to do that, you might want to avoid building a list of None elements by performing the swaps in the condition rather than as the output value. For example: ``` a = [1, 3, 2, 6, 5, 4] [_ for n in range(len(a),1,-1) for i in range(n-1) if a[i]>a[i+1] and a.__setitem__(slice(i,i+2),a[i:i+2][::-1])] ``` Isolating the element swapping part, this would give: ``` swap = lambda(a,i):a.__setitem__(slice(i,i+2),a[i:i+2][::-1]) [_ for n in range(len(a),1,-1) for i in range(n-1) if a[i]>a[i+1] and swap(a,i)] ``` Which is no different from: ``` for n in range(len(a),1,-1): for i in range(n-1): if a[i]>a[i+1]: swap(a,i) # same as a[i],a[i+1] = a[i+1],a[i] ``` The list comprehension is merely a different way to write the for loop and is not actually returning the sorted result. What would be more in the spirit of a list comprehension is to actually return the sorted result without affecting the original list. You can do this using a temporary list within the comprehension to perform the element swapping and progressively return the position that is guaranteed to be at the right sorted index: ``` a = [1, 3, 2, 6, 5, 4] s = [ b.pop(-1) for b in [list(a)] for n in range(len(a),0,-1) if not [_ for i in range(n-1) if b[i]<b[i+1] and b.__setitem__(slice(i,i+2),b[i:i+2][::-1])] ] print(s) # [1, 2, 3, 4, 5, 6] ``` The approach is the same as before except that `b` is used internally to manage swapping and return the sorted values. Because the guaranteed sorted position is always the last one in `b`, the swapping condition was reversed so that internally `b` is sorted in descending order which produces the output in ascending order when taking the last item at each iteration. Note that all these solutions fail to implement the early exit condition that allows bubble sort to be very efficient on already sorted lists and lists where elements are near their sorted position (i.e. stop when no swaps in a pass). The number of iterations will always be N\*(N+1)/2 no matter the original order of elements giving a time complexity of O(N^2) all the time instead of worst case.
``` def bubblesort(l): [[l.insert(j+1, l.pop(j)) for j in range(i) if l[j] > l[j+1]] for i in range(len(l)-1,0,-1)] return l ``` I use the `l.insert(j+1, l.pop(j))` to swap the elements in the list. The rest are just the nested loops.
29,813,126
So far i have a list view with a custom adapter, and each item in list has a button. Im really confused; Im trying to do the following: When user clicks on button(a delete button) in item in the list, i want to know in which item button was clicked so i can know which item to delete-how do i implement this? Ive seen something about setting tags, but Im still very lost. I have also tried to reach the button from the list layout from my main activity, and cannot reference it. please can you give me a detailed description on how to do what i want to do thanks. **ADDED adapter code:** ``` public class LocationAdapter extends BaseAdapter{ String [] n; Context context; String[] a; private static LayoutInflater inflater=null; public LocationAdapter(MainActivity mainActivity, String[] names, String[] addresses) { // TODO Auto-generated constructor stub n=names; context=mainActivity; a=addresses; inflater = ( LayoutInflater )context. getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { // TODO Auto-generated method stub return n.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } public class Holder { TextView name; TextView address; ImageButton ib; } @Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub Holder holder=new Holder(); View rowView; rowView = inflater.inflate(R.layout.rowlayout2, null); holder.name =(TextView) rowView.findViewById(R.id.EditTextName); holder.address =(TextView) rowView.findViewById(R.id.EditTextAddress); holder.ib = (ImageButton) rowView.findViewById(R.id.Delete); holder.name.setText(n[position]); holder.address.setText(a[position]); holder.ib.setTag(convertView); rowView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(context, "You Clicked "+n[position], Toast.LENGTH_LONG).show(); } }); return rowView; } ``` }
2015/04/23
['https://Stackoverflow.com/questions/29813126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4725548/']
Use this inside your getView() method of adapter. ``` yourButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { System.out.println("button : "+position+ " clicked"); // Do you code here. } }); ```
You need to add the `onClick` in the `getView`. Example : <http://jmsliu.com/2444/click-button-in-listview-and-get-item-position.html> Theres a lot of tutorials for this out there.
29,813,126
So far i have a list view with a custom adapter, and each item in list has a button. Im really confused; Im trying to do the following: When user clicks on button(a delete button) in item in the list, i want to know in which item button was clicked so i can know which item to delete-how do i implement this? Ive seen something about setting tags, but Im still very lost. I have also tried to reach the button from the list layout from my main activity, and cannot reference it. please can you give me a detailed description on how to do what i want to do thanks. **ADDED adapter code:** ``` public class LocationAdapter extends BaseAdapter{ String [] n; Context context; String[] a; private static LayoutInflater inflater=null; public LocationAdapter(MainActivity mainActivity, String[] names, String[] addresses) { // TODO Auto-generated constructor stub n=names; context=mainActivity; a=addresses; inflater = ( LayoutInflater )context. getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { // TODO Auto-generated method stub return n.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } public class Holder { TextView name; TextView address; ImageButton ib; } @Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub Holder holder=new Holder(); View rowView; rowView = inflater.inflate(R.layout.rowlayout2, null); holder.name =(TextView) rowView.findViewById(R.id.EditTextName); holder.address =(TextView) rowView.findViewById(R.id.EditTextAddress); holder.ib = (ImageButton) rowView.findViewById(R.id.Delete); holder.name.setText(n[position]); holder.address.setText(a[position]); holder.ib.setTag(convertView); rowView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(context, "You Clicked "+n[position], Toast.LENGTH_LONG).show(); } }); return rowView; } ``` }
2015/04/23
['https://Stackoverflow.com/questions/29813126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4725548/']
Use this inside your getView() method of adapter. ``` yourButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { System.out.println("button : "+position+ " clicked"); // Do you code here. } }); ```
``` public class SeekBarAdapter {private SeekBarListener mListener; private ClickListener mListenerClick; public interface SeekBarListener { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser, int positionInList); public void onStartTrackingTouch(SeekBar seekBar, int positionInList); public void onStopTrackingTouch(SeekBar seekBar, int positionInList); } public interface ClickListener { public void onClick(View v, int positionInList); } public listAdapter getAdapter(Context context, ItemPhotoEffect itemPhotoEff) { return new listAdapter(context, itemPhotoEff); } public void setSeekBarListener(SeekBarListener listener) { mListener = listener; } public void setClickListener(ClickListener listener) { mListenerClick = listener; } public class listAdapter extends BaseAdapter { private LayoutInflater mInflater; private onSeekbarChange mSeekListener; private onClickChange mImgClickListener; private ArrayList<Bitmap> itemsList; private Bitmap imgIcon; private ArrayList<Integer> positionProgress; private ArrayList<ColorEffectItem> colorItem; public listAdapter(Context context, ItemPhotoEffect itemPhotoEff) { mInflater = LayoutInflater.from(context); if (mSeekListener == null) { mSeekListener = new onSeekbarChange(); } if (mImgClickListener == null) { mImgClickListener = new onClickChange(); } this.itemsList = itemPhotoEff.getSeekBarItem().getIconSeekBar(); this.positionProgress = itemPhotoEff.getSeekBarItem() .getPositionProgress(); // if (itemPhotoEff.getSeekBarItem().getColorItem() != null) { this.colorItem = itemPhotoEff.getSeekBarItem().getColorItem(); // } } @Override public int getCount() { if (itemsList != null) { return itemsList.size(); } else { return 0; } } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { final ViewHolder holder; // if (convertView == null) { holder = new ViewHolder(); convertView = mInflater.inflate(R.layout.seekbar_adapter_layout, null); holder.img = (ImageView) convertView.findViewById(R.id.imageView1); holder.seekbar = (SeekBar) convertView.findViewById(R.id.seekBar1); holder.colorbutton = (ImageView) convertView .findViewById(R.id.colorImage); holder.ln_img = (LinearLayout) convertView .findViewById(R.id.ln_colorimg); convertView.setTag(holder); // } else { // holder = (ViewHolder) convertView.getTag(); // } holder.img.setImageBitmap(itemsList.get(position)); if (positionProgress.get(position) != null) { holder.seekbar.setVisibility(View.VISIBLE); holder.ln_img.setVisibility(View.GONE); holder.seekbar.setProgress(positionProgress.get(position)); } else { holder.ln_img.setVisibility(View.VISIBLE); holder.seekbar.setVisibility(View.GONE); holder.colorbutton.setBackgroundColor(Color.rgb(this.colorItem .get(position).getRcolor(), this.colorItem .get(position).getGcolor(), this.colorItem .get(position).getBcolor())); } holder.seekbar.setOnSeekBarChangeListener(mSeekListener); holder.ln_img.setOnClickListener(mImgClickListener); holder.seekbar.setTag(position); holder.ln_img.setTag(position); return convertView; } } static class ViewHolder { ImageView img; SeekBar seekbar; ImageView colorbutton; LinearLayout ln_img; }// This is class you need to know which button has been click public class onClickChange implements OnClickListener { @Override public void onClick(View v) { // TODO Auto-generated method stub int position = (Integer) v.getTag(); if (mListenerClick != null) { mListenerClick.onClick(v, position); } } } public class onSeekbarChange implements OnSeekBarChangeListener { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int position = (Integer) seekBar.getTag(); if (mListener != null) { mListener.onProgressChanged(seekBar, progress, fromUser, position); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { int position = (Integer) seekBar.getTag(); if (mListener != null) { mListener.onStartTrackingTouch(seekBar, position); } } @Override public void onStopTrackingTouch(SeekBar seekBar) { int position = (Integer) seekBar.getTag(); if (mListener != null) { mListener.onStopTrackingTouch(seekBar, position); } } }} ``` You can use mycode. Implements interface OnclickListener in your adapter. And then implement in activity: + PositionInList use if you have than 1 button in row. ``` adapter.setClickListener(new ClickListener() { @Override public void onClick(View v, int positionInList) { // TODO Auto-generated method stub Log.i("", "Click on position in list" + positionInList); } }); ```
29,813,126
So far i have a list view with a custom adapter, and each item in list has a button. Im really confused; Im trying to do the following: When user clicks on button(a delete button) in item in the list, i want to know in which item button was clicked so i can know which item to delete-how do i implement this? Ive seen something about setting tags, but Im still very lost. I have also tried to reach the button from the list layout from my main activity, and cannot reference it. please can you give me a detailed description on how to do what i want to do thanks. **ADDED adapter code:** ``` public class LocationAdapter extends BaseAdapter{ String [] n; Context context; String[] a; private static LayoutInflater inflater=null; public LocationAdapter(MainActivity mainActivity, String[] names, String[] addresses) { // TODO Auto-generated constructor stub n=names; context=mainActivity; a=addresses; inflater = ( LayoutInflater )context. getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { // TODO Auto-generated method stub return n.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } public class Holder { TextView name; TextView address; ImageButton ib; } @Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub Holder holder=new Holder(); View rowView; rowView = inflater.inflate(R.layout.rowlayout2, null); holder.name =(TextView) rowView.findViewById(R.id.EditTextName); holder.address =(TextView) rowView.findViewById(R.id.EditTextAddress); holder.ib = (ImageButton) rowView.findViewById(R.id.Delete); holder.name.setText(n[position]); holder.address.setText(a[position]); holder.ib.setTag(convertView); rowView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(context, "You Clicked "+n[position], Toast.LENGTH_LONG).show(); } }); return rowView; } ``` }
2015/04/23
['https://Stackoverflow.com/questions/29813126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4725548/']
Implement an `OnClickListener` for your `delete` button. When the `delete` button is clicked, remove the row in the data source at `position`, and then call `notifyDataSetChanged()` ``` @Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub Holder holder=new Holder(); View rowView; rowView = inflater.inflate(R.layout.rowlayout2, null); holder.name =(TextView) rowView.findViewById(R.id.EditTextName); holder.address =(TextView) rowView.findViewById(R.id.EditTextAddress); holder.ib = (ImageButton) rowView.findViewById(R.id.Delete); holder.name.setText(n[position]); holder.address.setText(a[position]); holder.ib.setTag(convertView); //Add this for on-click of delete button holder.ib.setOnClickListener(new OnClickListener(){ //Delete the row in your data source specified at position }); rowView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(context, "You Clicked "+n[position], Toast.LENGTH_LONG).show(); } }); return rowView; } ```
Use this inside your getView() method of adapter. ``` yourButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { System.out.println("button : "+position+ " clicked"); // Do you code here. } }); ```
29,813,126
So far i have a list view with a custom adapter, and each item in list has a button. Im really confused; Im trying to do the following: When user clicks on button(a delete button) in item in the list, i want to know in which item button was clicked so i can know which item to delete-how do i implement this? Ive seen something about setting tags, but Im still very lost. I have also tried to reach the button from the list layout from my main activity, and cannot reference it. please can you give me a detailed description on how to do what i want to do thanks. **ADDED adapter code:** ``` public class LocationAdapter extends BaseAdapter{ String [] n; Context context; String[] a; private static LayoutInflater inflater=null; public LocationAdapter(MainActivity mainActivity, String[] names, String[] addresses) { // TODO Auto-generated constructor stub n=names; context=mainActivity; a=addresses; inflater = ( LayoutInflater )context. getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { // TODO Auto-generated method stub return n.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } public class Holder { TextView name; TextView address; ImageButton ib; } @Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub Holder holder=new Holder(); View rowView; rowView = inflater.inflate(R.layout.rowlayout2, null); holder.name =(TextView) rowView.findViewById(R.id.EditTextName); holder.address =(TextView) rowView.findViewById(R.id.EditTextAddress); holder.ib = (ImageButton) rowView.findViewById(R.id.Delete); holder.name.setText(n[position]); holder.address.setText(a[position]); holder.ib.setTag(convertView); rowView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(context, "You Clicked "+n[position], Toast.LENGTH_LONG).show(); } }); return rowView; } ``` }
2015/04/23
['https://Stackoverflow.com/questions/29813126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4725548/']
Use this inside your getView() method of adapter. ``` yourButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { System.out.println("button : "+position+ " clicked"); // Do you code here. } }); ```
You should not use Array. Array has fixed length so you cannot exactly remove its element. You need to use ArrayList in place of Array and implement ViewHolder pattern correctly: ``` ArrayList<Item> items = new ArrayList<>(); //merge both the content of a and n into one object "Item" //and use ArrayList @Override public View getView(final int position, View convertView, ViewGroup parent) { Holder holder; if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.rowlayout2, parent, false); holder = new Holder(convertView); convertView.setTag(holder); } else { holder = (Holder) convertView.getTag(); } holder.name.setText(getItem(position).name); ... holder.root.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { items.remove(position); notifyDataSetChanged(); } }); return convertView; } ``` If you want to set clickable on the whole row with then you need to put the root element inside the ViewHolder. ``` class Holder{ TextView name, address, ...; LinearLayout root; // or any Layout which is the root container of your row } ```
29,813,126
So far i have a list view with a custom adapter, and each item in list has a button. Im really confused; Im trying to do the following: When user clicks on button(a delete button) in item in the list, i want to know in which item button was clicked so i can know which item to delete-how do i implement this? Ive seen something about setting tags, but Im still very lost. I have also tried to reach the button from the list layout from my main activity, and cannot reference it. please can you give me a detailed description on how to do what i want to do thanks. **ADDED adapter code:** ``` public class LocationAdapter extends BaseAdapter{ String [] n; Context context; String[] a; private static LayoutInflater inflater=null; public LocationAdapter(MainActivity mainActivity, String[] names, String[] addresses) { // TODO Auto-generated constructor stub n=names; context=mainActivity; a=addresses; inflater = ( LayoutInflater )context. getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { // TODO Auto-generated method stub return n.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } public class Holder { TextView name; TextView address; ImageButton ib; } @Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub Holder holder=new Holder(); View rowView; rowView = inflater.inflate(R.layout.rowlayout2, null); holder.name =(TextView) rowView.findViewById(R.id.EditTextName); holder.address =(TextView) rowView.findViewById(R.id.EditTextAddress); holder.ib = (ImageButton) rowView.findViewById(R.id.Delete); holder.name.setText(n[position]); holder.address.setText(a[position]); holder.ib.setTag(convertView); rowView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(context, "You Clicked "+n[position], Toast.LENGTH_LONG).show(); } }); return rowView; } ``` }
2015/04/23
['https://Stackoverflow.com/questions/29813126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4725548/']
Implement an `OnClickListener` for your `delete` button. When the `delete` button is clicked, remove the row in the data source at `position`, and then call `notifyDataSetChanged()` ``` @Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub Holder holder=new Holder(); View rowView; rowView = inflater.inflate(R.layout.rowlayout2, null); holder.name =(TextView) rowView.findViewById(R.id.EditTextName); holder.address =(TextView) rowView.findViewById(R.id.EditTextAddress); holder.ib = (ImageButton) rowView.findViewById(R.id.Delete); holder.name.setText(n[position]); holder.address.setText(a[position]); holder.ib.setTag(convertView); //Add this for on-click of delete button holder.ib.setOnClickListener(new OnClickListener(){ //Delete the row in your data source specified at position }); rowView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(context, "You Clicked "+n[position], Toast.LENGTH_LONG).show(); } }); return rowView; } ```
You need to add the `onClick` in the `getView`. Example : <http://jmsliu.com/2444/click-button-in-listview-and-get-item-position.html> Theres a lot of tutorials for this out there.
29,813,126
So far i have a list view with a custom adapter, and each item in list has a button. Im really confused; Im trying to do the following: When user clicks on button(a delete button) in item in the list, i want to know in which item button was clicked so i can know which item to delete-how do i implement this? Ive seen something about setting tags, but Im still very lost. I have also tried to reach the button from the list layout from my main activity, and cannot reference it. please can you give me a detailed description on how to do what i want to do thanks. **ADDED adapter code:** ``` public class LocationAdapter extends BaseAdapter{ String [] n; Context context; String[] a; private static LayoutInflater inflater=null; public LocationAdapter(MainActivity mainActivity, String[] names, String[] addresses) { // TODO Auto-generated constructor stub n=names; context=mainActivity; a=addresses; inflater = ( LayoutInflater )context. getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { // TODO Auto-generated method stub return n.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } public class Holder { TextView name; TextView address; ImageButton ib; } @Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub Holder holder=new Holder(); View rowView; rowView = inflater.inflate(R.layout.rowlayout2, null); holder.name =(TextView) rowView.findViewById(R.id.EditTextName); holder.address =(TextView) rowView.findViewById(R.id.EditTextAddress); holder.ib = (ImageButton) rowView.findViewById(R.id.Delete); holder.name.setText(n[position]); holder.address.setText(a[position]); holder.ib.setTag(convertView); rowView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(context, "You Clicked "+n[position], Toast.LENGTH_LONG).show(); } }); return rowView; } ``` }
2015/04/23
['https://Stackoverflow.com/questions/29813126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4725548/']
Implement an `OnClickListener` for your `delete` button. When the `delete` button is clicked, remove the row in the data source at `position`, and then call `notifyDataSetChanged()` ``` @Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub Holder holder=new Holder(); View rowView; rowView = inflater.inflate(R.layout.rowlayout2, null); holder.name =(TextView) rowView.findViewById(R.id.EditTextName); holder.address =(TextView) rowView.findViewById(R.id.EditTextAddress); holder.ib = (ImageButton) rowView.findViewById(R.id.Delete); holder.name.setText(n[position]); holder.address.setText(a[position]); holder.ib.setTag(convertView); //Add this for on-click of delete button holder.ib.setOnClickListener(new OnClickListener(){ //Delete the row in your data source specified at position }); rowView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(context, "You Clicked "+n[position], Toast.LENGTH_LONG).show(); } }); return rowView; } ```
``` public class SeekBarAdapter {private SeekBarListener mListener; private ClickListener mListenerClick; public interface SeekBarListener { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser, int positionInList); public void onStartTrackingTouch(SeekBar seekBar, int positionInList); public void onStopTrackingTouch(SeekBar seekBar, int positionInList); } public interface ClickListener { public void onClick(View v, int positionInList); } public listAdapter getAdapter(Context context, ItemPhotoEffect itemPhotoEff) { return new listAdapter(context, itemPhotoEff); } public void setSeekBarListener(SeekBarListener listener) { mListener = listener; } public void setClickListener(ClickListener listener) { mListenerClick = listener; } public class listAdapter extends BaseAdapter { private LayoutInflater mInflater; private onSeekbarChange mSeekListener; private onClickChange mImgClickListener; private ArrayList<Bitmap> itemsList; private Bitmap imgIcon; private ArrayList<Integer> positionProgress; private ArrayList<ColorEffectItem> colorItem; public listAdapter(Context context, ItemPhotoEffect itemPhotoEff) { mInflater = LayoutInflater.from(context); if (mSeekListener == null) { mSeekListener = new onSeekbarChange(); } if (mImgClickListener == null) { mImgClickListener = new onClickChange(); } this.itemsList = itemPhotoEff.getSeekBarItem().getIconSeekBar(); this.positionProgress = itemPhotoEff.getSeekBarItem() .getPositionProgress(); // if (itemPhotoEff.getSeekBarItem().getColorItem() != null) { this.colorItem = itemPhotoEff.getSeekBarItem().getColorItem(); // } } @Override public int getCount() { if (itemsList != null) { return itemsList.size(); } else { return 0; } } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { final ViewHolder holder; // if (convertView == null) { holder = new ViewHolder(); convertView = mInflater.inflate(R.layout.seekbar_adapter_layout, null); holder.img = (ImageView) convertView.findViewById(R.id.imageView1); holder.seekbar = (SeekBar) convertView.findViewById(R.id.seekBar1); holder.colorbutton = (ImageView) convertView .findViewById(R.id.colorImage); holder.ln_img = (LinearLayout) convertView .findViewById(R.id.ln_colorimg); convertView.setTag(holder); // } else { // holder = (ViewHolder) convertView.getTag(); // } holder.img.setImageBitmap(itemsList.get(position)); if (positionProgress.get(position) != null) { holder.seekbar.setVisibility(View.VISIBLE); holder.ln_img.setVisibility(View.GONE); holder.seekbar.setProgress(positionProgress.get(position)); } else { holder.ln_img.setVisibility(View.VISIBLE); holder.seekbar.setVisibility(View.GONE); holder.colorbutton.setBackgroundColor(Color.rgb(this.colorItem .get(position).getRcolor(), this.colorItem .get(position).getGcolor(), this.colorItem .get(position).getBcolor())); } holder.seekbar.setOnSeekBarChangeListener(mSeekListener); holder.ln_img.setOnClickListener(mImgClickListener); holder.seekbar.setTag(position); holder.ln_img.setTag(position); return convertView; } } static class ViewHolder { ImageView img; SeekBar seekbar; ImageView colorbutton; LinearLayout ln_img; }// This is class you need to know which button has been click public class onClickChange implements OnClickListener { @Override public void onClick(View v) { // TODO Auto-generated method stub int position = (Integer) v.getTag(); if (mListenerClick != null) { mListenerClick.onClick(v, position); } } } public class onSeekbarChange implements OnSeekBarChangeListener { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int position = (Integer) seekBar.getTag(); if (mListener != null) { mListener.onProgressChanged(seekBar, progress, fromUser, position); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { int position = (Integer) seekBar.getTag(); if (mListener != null) { mListener.onStartTrackingTouch(seekBar, position); } } @Override public void onStopTrackingTouch(SeekBar seekBar) { int position = (Integer) seekBar.getTag(); if (mListener != null) { mListener.onStopTrackingTouch(seekBar, position); } } }} ``` You can use mycode. Implements interface OnclickListener in your adapter. And then implement in activity: + PositionInList use if you have than 1 button in row. ``` adapter.setClickListener(new ClickListener() { @Override public void onClick(View v, int positionInList) { // TODO Auto-generated method stub Log.i("", "Click on position in list" + positionInList); } }); ```
29,813,126
So far i have a list view with a custom adapter, and each item in list has a button. Im really confused; Im trying to do the following: When user clicks on button(a delete button) in item in the list, i want to know in which item button was clicked so i can know which item to delete-how do i implement this? Ive seen something about setting tags, but Im still very lost. I have also tried to reach the button from the list layout from my main activity, and cannot reference it. please can you give me a detailed description on how to do what i want to do thanks. **ADDED adapter code:** ``` public class LocationAdapter extends BaseAdapter{ String [] n; Context context; String[] a; private static LayoutInflater inflater=null; public LocationAdapter(MainActivity mainActivity, String[] names, String[] addresses) { // TODO Auto-generated constructor stub n=names; context=mainActivity; a=addresses; inflater = ( LayoutInflater )context. getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { // TODO Auto-generated method stub return n.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } public class Holder { TextView name; TextView address; ImageButton ib; } @Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub Holder holder=new Holder(); View rowView; rowView = inflater.inflate(R.layout.rowlayout2, null); holder.name =(TextView) rowView.findViewById(R.id.EditTextName); holder.address =(TextView) rowView.findViewById(R.id.EditTextAddress); holder.ib = (ImageButton) rowView.findViewById(R.id.Delete); holder.name.setText(n[position]); holder.address.setText(a[position]); holder.ib.setTag(convertView); rowView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(context, "You Clicked "+n[position], Toast.LENGTH_LONG).show(); } }); return rowView; } ``` }
2015/04/23
['https://Stackoverflow.com/questions/29813126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4725548/']
Implement an `OnClickListener` for your `delete` button. When the `delete` button is clicked, remove the row in the data source at `position`, and then call `notifyDataSetChanged()` ``` @Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub Holder holder=new Holder(); View rowView; rowView = inflater.inflate(R.layout.rowlayout2, null); holder.name =(TextView) rowView.findViewById(R.id.EditTextName); holder.address =(TextView) rowView.findViewById(R.id.EditTextAddress); holder.ib = (ImageButton) rowView.findViewById(R.id.Delete); holder.name.setText(n[position]); holder.address.setText(a[position]); holder.ib.setTag(convertView); //Add this for on-click of delete button holder.ib.setOnClickListener(new OnClickListener(){ //Delete the row in your data source specified at position }); rowView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(context, "You Clicked "+n[position], Toast.LENGTH_LONG).show(); } }); return rowView; } ```
You should not use Array. Array has fixed length so you cannot exactly remove its element. You need to use ArrayList in place of Array and implement ViewHolder pattern correctly: ``` ArrayList<Item> items = new ArrayList<>(); //merge both the content of a and n into one object "Item" //and use ArrayList @Override public View getView(final int position, View convertView, ViewGroup parent) { Holder holder; if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.rowlayout2, parent, false); holder = new Holder(convertView); convertView.setTag(holder); } else { holder = (Holder) convertView.getTag(); } holder.name.setText(getItem(position).name); ... holder.root.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { items.remove(position); notifyDataSetChanged(); } }); return convertView; } ``` If you want to set clickable on the whole row with then you need to put the root element inside the ViewHolder. ``` class Holder{ TextView name, address, ...; LinearLayout root; // or any Layout which is the root container of your row } ```
446,589
Given a continuous function $f\colon \mathbb R \to \mathbb R$ and the fact that $ \lim\_{x\rightarrow \infty} f(x)$ and $ \lim\_{x\rightarrow -\infty}f(x)$ exist (finite), prove that $f$ is bounded. I understand why it's true, but I have no idea how to formally prove this. I'd appreciate the help.
2013/07/18
['https://math.stackexchange.com/questions/446589', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/84007/']
There exists $x\_1$ with $|f(x)-\lim\_{y\to\infty}f(y)|<1$ for all $x>x\_1$. There exists $x\_2$ with $|f(x)-\lim\_{y\to-\infty}f(y)|<1$ for all $x<x\_2$. And $f$ is bounded on the compact interval $[x\_2,x\_1]$.
Clearly, it is sufficient to prove that $f$ is bounded on $\mathbb{R}\_+$, the problem being symmetric. Let $\ell\stackrel{\mathrm{def}}{=} \lim\_{+\infty} f$; wlog, $\ell=0$ (just by "considering" $g\stackrel{\mathrm{def}}{=}f-\ell$ instead). * By definition [1], there exists $A\geq 0$ such that $\forall x \geq A$ $|f(x)|\leq 1$. * Moreover, $f$ being continuous on $[0,A]$, it is also bounded there: let $M=\max\_{x\in[0,A]} |f(x)|$. Setting $$M^\prime\stackrel{\mathrm{def}}{=}\max(M,1)$$ we thus have that for all $x \geq 0$, $|f(x)| \leq M^\prime$; that is, $f$ is bounded on $\mathbb{R}\_+$. [1] definition of the limit, taking $\varepsilon=1$.
67,646,455
```js for (var i = 1; i <= 4; i++) { var str = ""; for (var j = 1; j <= i; j++) { str = str + i; } console.log(str); } ``` This is the code I Perform But its Wrong ``` 1 23 456 78910 ``` anybody please help?
2021/05/22
['https://Stackoverflow.com/questions/67646455', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15997945/']
```js var current_value = 1; for (var i = 1; i <= 4; i++) { var str = ""; for (var j = 1; j <= i; j++) { str = str + current_value++; } console.log(str); } ```
This is how I would solve your problem. You can use [`Array.prototype.map()`](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/map) in order to create loops easily. If we now create an empty array with 5 indexes we can use the [`Array.prototype.keys()`](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/keys) to get an array of values from 0 to 4. Besides that my code follows the same concept with using an empty string (`res`) and adding values to it. Also we mustn't forget to check if `res` is still empty. ```js let v = 1; [...Array(5).keys()].map((i) => { let res = ""; [...Array(i)].map(() => (res = res + v++)); res && console.log(res); }); ``` **Edit:** I just realized the `.keys()` is not even needed because simply using the index has the same effect: ```js let v = 1; [...Array(5)].map((_, i) => { let res = ""; [...Array(i)].map(() => (res = res + v++)); res && console.log(res); }); ```
55,663,305
I'am a begginer in Dart and i dont know how to acces to the values of the next Set ``` Set mySet = Set.from(['Please', 'Help', 'Me']); ```
2019/04/13
['https://Stackoverflow.com/questions/55663305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11240739/']
*I didn't get the clarity of what you mean by accessing next set but, you can access your current set data in following ways.* ``` Set mySet = Set.from(['Please', 'Help', 'Me']); // declaration. ``` Accessing through index ``` print('mySet.elementAt(0): ${mySet.elementAt(0)}'); print('mySet.elementAt(1): ${mySet.elementAt(1)}'); print('mySet.elementAt(2): ${mySet.elementAt(2)}'); ``` Iterating over set. ``` mySet.forEach((value) => {print(value)}); ``` Logging to see data stored in current set. ``` print('mySet: ${mySet.toString()}'); ```
From Wikipedia: > > > > > > Unlike most other collection types, rather than retrieving a specific element from a set, one typically tests a value for membership in a set. > > > > > > > > > That is, if this is not possible (to acces to the values) then this does not mean that this data structure does not fulfill its purpose. Maybe you should choose a different, and at the same time, more suitable, for your purposes, data structure?
65,708,307
I am uploading a static site using the `databricks` platform specifically using the below command for pushing `html` content to a location. ``` dbutils.fs.put("/mnt/$web/index.html", html, overwrite=True) ``` This is working but the HTML file is downloading instead of displaying. This is because the content type is wrong: Content-Type: `application/octet-stream`. Is there any way to set this using `databricks` ?
2021/01/13
['https://Stackoverflow.com/questions/65708307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3331783/']
Finally, this code worked for me. First, I am getting connection string from databricks scope as ``` dbutils.secrets.get(scope = "generic-scope", key = "website-key") ``` If you don't have it then look for it inside Storage Account's Container Access Key [![access location in azure storage account](https://i.stack.imgur.com/nycYw.png)](https://i.stack.imgur.com/nycYw.png) ``` from azure.storage.blob import BlobServiceClient, ContentSettings connect_str="connectionString" blob_service_client = BlobServiceClient.from_connection_string(connect_str) # Instantiate a ContainerClient container_client = blob_service_client.get_container_client("$web") # List files in blob folder blobs_list = container_client.list_blobs() for blob in blobs_list: print(blob.content_settings.content_type) # application/octet-stream blob.set_http_headers( content_settings=ContentSettings( content_type="text/html; charset=utf-8" ) ) ```
`dbutils.fs.put` works with files on DBFS and doesn't "know" about underlying implementation details, because you can mount different things - S3, ADLSv1/v2, etc. Changing of the content-type is specific to the blob storage API, so you will need to implement the code in Python (for [example](https://stackoverflow.com/questions/59752380/set-content-type-when-uploading-to-azure-blob-storage)) or Scala that will use that API to set content-type for uploaded files, or upload files & set content-type via API, without `dbutils.fs.put`.
15,376,970
I have 2 files: main\_activity.xml and home.xml. I made a button in main\_activity.xml Here is the code snippet: ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:background="@drawable/splash_background" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/Home" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="43dp" android:onClick="home" android:text="Home" /> </RelativeLayout> ``` And then, I have my home.xml. I want the button to open up home.xml. How can i do this? I don't know any java and I am new to android development. Here is my home.xml below: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:background="@drawable/app_bg" android:layout_height="match_parent" android:orientation="vertical" > </LinearLayout> ``` And below is my AndroidManifest.xml: ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.idozer" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="false" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.idozer.SplashActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.idozer.MainActivity" android:label="@string/app_name" > </activity> </application> </manifest> ``` And that's all I have. Please, if you reply, tell me where to add the code such as the directory or between code snippets.
2013/03/13
['https://Stackoverflow.com/questions/15376970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1978141/']
> > You can use this code. > > > Android: OnClickListener > ------------------------ > > > **In our activity class we add the onclick method.** > > In our activity class we add the onclick method. > > > ``` //On click event for button1 public void button1OnClick(View v) { //Inform the user the button has been clicked Toast.makeText(this, "Button1 clicked.", Toast.LENGTH_SHORT).show(); } ``` > > In the layout file we add a reference to the onclick handler in the > activity. The app will automatically bind the onclick method to the > view (in this case button1) > > > ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button1" android:onClick="button1OnClick"/> </LinearLayout> ```
``` Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show(); } }); ```
15,376,970
I have 2 files: main\_activity.xml and home.xml. I made a button in main\_activity.xml Here is the code snippet: ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:background="@drawable/splash_background" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/Home" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="43dp" android:onClick="home" android:text="Home" /> </RelativeLayout> ``` And then, I have my home.xml. I want the button to open up home.xml. How can i do this? I don't know any java and I am new to android development. Here is my home.xml below: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:background="@drawable/app_bg" android:layout_height="match_parent" android:orientation="vertical" > </LinearLayout> ``` And below is my AndroidManifest.xml: ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.idozer" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="false" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.idozer.SplashActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.idozer.MainActivity" android:label="@string/app_name" > </activity> </application> </manifest> ``` And that's all I have. Please, if you reply, tell me where to add the code such as the directory or between code snippets.
2013/03/13
['https://Stackoverflow.com/questions/15376970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1978141/']
For managing click activity in android ,you can do as below 1. Implement `OnClickListener` on **YourActivity.java** class like `public class MainActivity extends Activity implements OnClickListener` 2. Then, declare your button in .java class like `Button btn = (Button) findViewById(R.id.btnPlay);` 3. Then use button `btn` variable as below ``` btn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { myClick(v); /* my method to call new intent or activity */ } }); ``` 4. Handle the click event: ``` public void myClick(View v) { Intent intent = new Intent(**this, Swipe.class**); startActivity(intent);// for calling the activity } ``` you also need to register your activity(.java) in `android manifest` as below ``` <activity android:name=".Swipe" android:screenOrientation="landscape" > </activity> ```
I will give you just a little bit to get you started as this answer may help others that are having trouble with using `onClick()` this way but you really need to learn Java and go through the **[Android Docs](http://developer.android.com/index.html)** so you can ask better questions You need to read [Here](http://developer.android.com/reference/android/app/Activity.html) about `Actviities` and how to create them. Then in your code you will have a function ``` public void home(View v) //the name of this function comes from where you declared in your manifest `android:onClick="home" { Intent intent (MainActivity.this, HomeActivity.class); //MainActivity is the name of current activity and HomeActivity is the name of the activity you want to start can add intent extras/flags/categories here startActivity(intent); } ``` You also need to add the `HomeActivity` in your `manifest` as you have for the other `Activities`. But you really need to go through the docs and do some tutorials to get an idea of how the Android framework operates and you need to learn Java to make your life a whole lot easier. Besides the previous two links I have given, also see [this post](https://stackoverflow.com/questions/15059351/using-nested-interfaces-for-communication-between-two-classes-in-java-android/15059793#15059793) about click events as there are different ways to use `onClick()` I hope this is enough to get you started and I really hope you go through the docs to get a better understanding of what you are doing. Good luck to you! Another important link to get started [Intents](http://developer.android.com/reference/android/content/Intent.html)
15,376,970
I have 2 files: main\_activity.xml and home.xml. I made a button in main\_activity.xml Here is the code snippet: ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:background="@drawable/splash_background" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/Home" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="43dp" android:onClick="home" android:text="Home" /> </RelativeLayout> ``` And then, I have my home.xml. I want the button to open up home.xml. How can i do this? I don't know any java and I am new to android development. Here is my home.xml below: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:background="@drawable/app_bg" android:layout_height="match_parent" android:orientation="vertical" > </LinearLayout> ``` And below is my AndroidManifest.xml: ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.idozer" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="false" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.idozer.SplashActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.idozer.MainActivity" android:label="@string/app_name" > </activity> </application> </manifest> ``` And that's all I have. Please, if you reply, tell me where to add the code such as the directory or between code snippets.
2013/03/13
['https://Stackoverflow.com/questions/15376970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1978141/']
create another class goto your project right click and click class and create Home. In that Home class file extends activity and add code like this ``` public class Home extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.home); } } ``` in **splash activity class** add this line ``` Intent intent = new Intent(SplashActivity.this,Home.class); startActivity(intent); ``` add Home activity class in your android manifest file ``` <activity android:name="com.example.idozer.Home" android:label="@string/app_name" > </activity> ```
``` Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show(); } }); ```
15,376,970
I have 2 files: main\_activity.xml and home.xml. I made a button in main\_activity.xml Here is the code snippet: ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:background="@drawable/splash_background" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/Home" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="43dp" android:onClick="home" android:text="Home" /> </RelativeLayout> ``` And then, I have my home.xml. I want the button to open up home.xml. How can i do this? I don't know any java and I am new to android development. Here is my home.xml below: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:background="@drawable/app_bg" android:layout_height="match_parent" android:orientation="vertical" > </LinearLayout> ``` And below is my AndroidManifest.xml: ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.idozer" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="false" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.idozer.SplashActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.idozer.MainActivity" android:label="@string/app_name" > </activity> </application> </manifest> ``` And that's all I have. Please, if you reply, tell me where to add the code such as the directory or between code snippets.
2013/03/13
['https://Stackoverflow.com/questions/15376970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1978141/']
For managing click activity in android ,you can do as below 1. Implement `OnClickListener` on **YourActivity.java** class like `public class MainActivity extends Activity implements OnClickListener` 2. Then, declare your button in .java class like `Button btn = (Button) findViewById(R.id.btnPlay);` 3. Then use button `btn` variable as below ``` btn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { myClick(v); /* my method to call new intent or activity */ } }); ``` 4. Handle the click event: ``` public void myClick(View v) { Intent intent = new Intent(**this, Swipe.class**); startActivity(intent);// for calling the activity } ``` you also need to register your activity(.java) in `android manifest` as below ``` <activity android:name=".Swipe" android:screenOrientation="landscape" > </activity> ```
``` Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show(); } }); ```
15,376,970
I have 2 files: main\_activity.xml and home.xml. I made a button in main\_activity.xml Here is the code snippet: ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:background="@drawable/splash_background" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/Home" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="43dp" android:onClick="home" android:text="Home" /> </RelativeLayout> ``` And then, I have my home.xml. I want the button to open up home.xml. How can i do this? I don't know any java and I am new to android development. Here is my home.xml below: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:background="@drawable/app_bg" android:layout_height="match_parent" android:orientation="vertical" > </LinearLayout> ``` And below is my AndroidManifest.xml: ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.idozer" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="false" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.idozer.SplashActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.idozer.MainActivity" android:label="@string/app_name" > </activity> </application> </manifest> ``` And that's all I have. Please, if you reply, tell me where to add the code such as the directory or between code snippets.
2013/03/13
['https://Stackoverflow.com/questions/15376970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1978141/']
create another class goto your project right click and click class and create Home. In that Home class file extends activity and add code like this ``` public class Home extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.home); } } ``` in **splash activity class** add this line ``` Intent intent = new Intent(SplashActivity.this,Home.class); startActivity(intent); ``` add Home activity class in your android manifest file ``` <activity android:name="com.example.idozer.Home" android:label="@string/app_name" > </activity> ```
I will give you just a little bit to get you started as this answer may help others that are having trouble with using `onClick()` this way but you really need to learn Java and go through the **[Android Docs](http://developer.android.com/index.html)** so you can ask better questions You need to read [Here](http://developer.android.com/reference/android/app/Activity.html) about `Actviities` and how to create them. Then in your code you will have a function ``` public void home(View v) //the name of this function comes from where you declared in your manifest `android:onClick="home" { Intent intent (MainActivity.this, HomeActivity.class); //MainActivity is the name of current activity and HomeActivity is the name of the activity you want to start can add intent extras/flags/categories here startActivity(intent); } ``` You also need to add the `HomeActivity` in your `manifest` as you have for the other `Activities`. But you really need to go through the docs and do some tutorials to get an idea of how the Android framework operates and you need to learn Java to make your life a whole lot easier. Besides the previous two links I have given, also see [this post](https://stackoverflow.com/questions/15059351/using-nested-interfaces-for-communication-between-two-classes-in-java-android/15059793#15059793) about click events as there are different ways to use `onClick()` I hope this is enough to get you started and I really hope you go through the docs to get a better understanding of what you are doing. Good luck to you! Another important link to get started [Intents](http://developer.android.com/reference/android/content/Intent.html)
15,376,970
I have 2 files: main\_activity.xml and home.xml. I made a button in main\_activity.xml Here is the code snippet: ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:background="@drawable/splash_background" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/Home" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="43dp" android:onClick="home" android:text="Home" /> </RelativeLayout> ``` And then, I have my home.xml. I want the button to open up home.xml. How can i do this? I don't know any java and I am new to android development. Here is my home.xml below: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:background="@drawable/app_bg" android:layout_height="match_parent" android:orientation="vertical" > </LinearLayout> ``` And below is my AndroidManifest.xml: ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.idozer" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="false" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.idozer.SplashActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.idozer.MainActivity" android:label="@string/app_name" > </activity> </application> </manifest> ``` And that's all I have. Please, if you reply, tell me where to add the code such as the directory or between code snippets.
2013/03/13
['https://Stackoverflow.com/questions/15376970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1978141/']
> > You can use this code. > > > Android: OnClickListener > ------------------------ > > > **In our activity class we add the onclick method.** > > In our activity class we add the onclick method. > > > ``` //On click event for button1 public void button1OnClick(View v) { //Inform the user the button has been clicked Toast.makeText(this, "Button1 clicked.", Toast.LENGTH_SHORT).show(); } ``` > > In the layout file we add a reference to the onclick handler in the > activity. The app will automatically bind the onclick method to the > view (in this case button1) > > > ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button1" android:onClick="button1OnClick"/> </LinearLayout> ```
I will give you just a little bit to get you started as this answer may help others that are having trouble with using `onClick()` this way but you really need to learn Java and go through the **[Android Docs](http://developer.android.com/index.html)** so you can ask better questions You need to read [Here](http://developer.android.com/reference/android/app/Activity.html) about `Actviities` and how to create them. Then in your code you will have a function ``` public void home(View v) //the name of this function comes from where you declared in your manifest `android:onClick="home" { Intent intent (MainActivity.this, HomeActivity.class); //MainActivity is the name of current activity and HomeActivity is the name of the activity you want to start can add intent extras/flags/categories here startActivity(intent); } ``` You also need to add the `HomeActivity` in your `manifest` as you have for the other `Activities`. But you really need to go through the docs and do some tutorials to get an idea of how the Android framework operates and you need to learn Java to make your life a whole lot easier. Besides the previous two links I have given, also see [this post](https://stackoverflow.com/questions/15059351/using-nested-interfaces-for-communication-between-two-classes-in-java-android/15059793#15059793) about click events as there are different ways to use `onClick()` I hope this is enough to get you started and I really hope you go through the docs to get a better understanding of what you are doing. Good luck to you! Another important link to get started [Intents](http://developer.android.com/reference/android/content/Intent.html)
15,376,970
I have 2 files: main\_activity.xml and home.xml. I made a button in main\_activity.xml Here is the code snippet: ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:background="@drawable/splash_background" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/Home" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="43dp" android:onClick="home" android:text="Home" /> </RelativeLayout> ``` And then, I have my home.xml. I want the button to open up home.xml. How can i do this? I don't know any java and I am new to android development. Here is my home.xml below: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:background="@drawable/app_bg" android:layout_height="match_parent" android:orientation="vertical" > </LinearLayout> ``` And below is my AndroidManifest.xml: ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.idozer" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="false" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.idozer.SplashActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.idozer.MainActivity" android:label="@string/app_name" > </activity> </application> </manifest> ``` And that's all I have. Please, if you reply, tell me where to add the code such as the directory or between code snippets.
2013/03/13
['https://Stackoverflow.com/questions/15376970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1978141/']
> > You can use this code. > > > Android: OnClickListener > ------------------------ > > > **In our activity class we add the onclick method.** > > In our activity class we add the onclick method. > > > ``` //On click event for button1 public void button1OnClick(View v) { //Inform the user the button has been clicked Toast.makeText(this, "Button1 clicked.", Toast.LENGTH_SHORT).show(); } ``` > > In the layout file we add a reference to the onclick handler in the > activity. The app will automatically bind the onclick method to the > view (in this case button1) > > > ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button1" android:onClick="button1OnClick"/> </LinearLayout> ```
create another class goto your project right click and click class and create Home. In that Home class file extends activity and add code like this ``` public class Home extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.home); } } ``` in **splash activity class** add this line ``` Intent intent = new Intent(SplashActivity.this,Home.class); startActivity(intent); ``` add Home activity class in your android manifest file ``` <activity android:name="com.example.idozer.Home" android:label="@string/app_name" > </activity> ```
15,376,970
I have 2 files: main\_activity.xml and home.xml. I made a button in main\_activity.xml Here is the code snippet: ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:background="@drawable/splash_background" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/Home" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="43dp" android:onClick="home" android:text="Home" /> </RelativeLayout> ``` And then, I have my home.xml. I want the button to open up home.xml. How can i do this? I don't know any java and I am new to android development. Here is my home.xml below: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:background="@drawable/app_bg" android:layout_height="match_parent" android:orientation="vertical" > </LinearLayout> ``` And below is my AndroidManifest.xml: ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.idozer" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="false" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.idozer.SplashActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.idozer.MainActivity" android:label="@string/app_name" > </activity> </application> </manifest> ``` And that's all I have. Please, if you reply, tell me where to add the code such as the directory or between code snippets.
2013/03/13
['https://Stackoverflow.com/questions/15376970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1978141/']
> > You can use this code. > > > Android: OnClickListener > ------------------------ > > > **In our activity class we add the onclick method.** > > In our activity class we add the onclick method. > > > ``` //On click event for button1 public void button1OnClick(View v) { //Inform the user the button has been clicked Toast.makeText(this, "Button1 clicked.", Toast.LENGTH_SHORT).show(); } ``` > > In the layout file we add a reference to the onclick handler in the > activity. The app will automatically bind the onclick method to the > view (in this case button1) > > > ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button1" android:onClick="button1OnClick"/> </LinearLayout> ```
`android:onClick` was added in API level 4 to make it easier, more Javascript-web-like, and drive everything from the XML. What it does internally is add an `OnClickListener` on the `Button`, which calls your home method. ``` <Button android:id="@+id/Home" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="43dp" android:onClick="home" android:text="Home" /> ``` . ``` public void home(View view){ Intent intent=new Intent (view.getContext(),Luton.class); this.startActivity(intent); } ``` In your activity class Using java code you can do button click by getting the id of the button from xml. ``` <Button android:id="@+id/myHomeButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="43dp" android:text="Home" /> ``` . ``` Button button= (Button) findViewById(R.id.myHomeButton); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //do whatever you want on button click } }); ``` Both are exactly the same
15,376,970
I have 2 files: main\_activity.xml and home.xml. I made a button in main\_activity.xml Here is the code snippet: ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:background="@drawable/splash_background" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/Home" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="43dp" android:onClick="home" android:text="Home" /> </RelativeLayout> ``` And then, I have my home.xml. I want the button to open up home.xml. How can i do this? I don't know any java and I am new to android development. Here is my home.xml below: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:background="@drawable/app_bg" android:layout_height="match_parent" android:orientation="vertical" > </LinearLayout> ``` And below is my AndroidManifest.xml: ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.idozer" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="false" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.idozer.SplashActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.idozer.MainActivity" android:label="@string/app_name" > </activity> </application> </manifest> ``` And that's all I have. Please, if you reply, tell me where to add the code such as the directory or between code snippets.
2013/03/13
['https://Stackoverflow.com/questions/15376970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1978141/']
For managing click activity in android ,you can do as below 1. Implement `OnClickListener` on **YourActivity.java** class like `public class MainActivity extends Activity implements OnClickListener` 2. Then, declare your button in .java class like `Button btn = (Button) findViewById(R.id.btnPlay);` 3. Then use button `btn` variable as below ``` btn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { myClick(v); /* my method to call new intent or activity */ } }); ``` 4. Handle the click event: ``` public void myClick(View v) { Intent intent = new Intent(**this, Swipe.class**); startActivity(intent);// for calling the activity } ``` you also need to register your activity(.java) in `android manifest` as below ``` <activity android:name=".Swipe" android:screenOrientation="landscape" > </activity> ```
> > You can use this code. > > > Android: OnClickListener > ------------------------ > > > **In our activity class we add the onclick method.** > > In our activity class we add the onclick method. > > > ``` //On click event for button1 public void button1OnClick(View v) { //Inform the user the button has been clicked Toast.makeText(this, "Button1 clicked.", Toast.LENGTH_SHORT).show(); } ``` > > In the layout file we add a reference to the onclick handler in the > activity. The app will automatically bind the onclick method to the > view (in this case button1) > > > ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button1" android:onClick="button1OnClick"/> </LinearLayout> ```
15,376,970
I have 2 files: main\_activity.xml and home.xml. I made a button in main\_activity.xml Here is the code snippet: ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:background="@drawable/splash_background" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/Home" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="43dp" android:onClick="home" android:text="Home" /> </RelativeLayout> ``` And then, I have my home.xml. I want the button to open up home.xml. How can i do this? I don't know any java and I am new to android development. Here is my home.xml below: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:background="@drawable/app_bg" android:layout_height="match_parent" android:orientation="vertical" > </LinearLayout> ``` And below is my AndroidManifest.xml: ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.idozer" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="false" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.idozer.SplashActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.idozer.MainActivity" android:label="@string/app_name" > </activity> </application> </manifest> ``` And that's all I have. Please, if you reply, tell me where to add the code such as the directory or between code snippets.
2013/03/13
['https://Stackoverflow.com/questions/15376970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1978141/']
create another class goto your project right click and click class and create Home. In that Home class file extends activity and add code like this ``` public class Home extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.home); } } ``` in **splash activity class** add this line ``` Intent intent = new Intent(SplashActivity.this,Home.class); startActivity(intent); ``` add Home activity class in your android manifest file ``` <activity android:name="com.example.idozer.Home" android:label="@string/app_name" > </activity> ```
`android:onClick` was added in API level 4 to make it easier, more Javascript-web-like, and drive everything from the XML. What it does internally is add an `OnClickListener` on the `Button`, which calls your home method. ``` <Button android:id="@+id/Home" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="43dp" android:onClick="home" android:text="Home" /> ``` . ``` public void home(View view){ Intent intent=new Intent (view.getContext(),Luton.class); this.startActivity(intent); } ``` In your activity class Using java code you can do button click by getting the id of the button from xml. ``` <Button android:id="@+id/myHomeButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="43dp" android:text="Home" /> ``` . ``` Button button= (Button) findViewById(R.id.myHomeButton); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //do whatever you want on button click } }); ``` Both are exactly the same
15,482,231
I'm starting out learning Clojure, and was trying to implement some basic numerical derivative functions for practice. I'm trying to create a `gradient` function that accepts an n-variable function and the points at which to evaluate it. To do this in a "functional" style, I want to implement the gradient as a `map` of a 1-variable derivatives. The 1-variable derivative function is simple: ``` (defn derivative "Numerical derivative of a univariate function." [f x] (let [eps 10e-6] ; Fix epsilon, just for starters. ; Centered derivative is [f(x+e) - f(x-e)] / (2e) (/ (- (f (+ x eps)) (f (- x eps))) (* 2 eps)))) ``` I'd like to design the gradient along these lines: ``` (defn gradient "Numerical gradient of a multivariate function." [f & x] (let [varity-index (range (count x)) univariate-in-i (fn [i] (_?_))] ; Creates a univariate fn ; of x_i (other x's fixed) ;; For each i = 0, ... n-1: ;; (1) Get univariate function of x_i ;; (2) Take derivative of that function ;; Gradient is sequence of those univariate derivatives. (map derivative (map univariate-in-i varity-index) x))) ``` So, `gradient` has variable arity (can accept any # of x's), and the order of the x's counts. The function `univariate-in-i` takes an index `i = 0, 1, ... n-1` and returns a 1-variable function by partial-ing out all the variables except `x_i`. E.g., you'd get: ``` #(f x_0 x_1 ... x_i-1 % x_i+1 ... x_n) ^ (x_i still variable) ``` `map`-ping this function over `varity-index` gets you a sequence of 1-variable functions in each `x_i`, and then `map`-ping `derivative` over these gets you a sequence of derivatives in each `x_i` which is the gradient we want. My questions is: I'm not sure what a good way to implement `univariate-in-i` is. I essentially need to fill in values for x's in `f` except at some particular spot (i.e., place the `%` above), but programmatically. I'm more interested in technique than solution (i.e., I know how to compute gradients, I'm trying to learn functional programming and idiomatic Clojure). Therefore, I'd like to stay true to the strategy of treating the gradient as a map of 1-d derivatives over partialed-out functions. But if there's a better "functional" approach to this, please let me know. I'd rather not resort to macros if possible. Thanks in advance! **Update:** Using Ankur's answer below, the gradient function I get is: ``` (defn gradient "Numerical gradient of a multivariate function." [f & x] (let [varity-index (range (count x)) x-vec (vec x) univariate-in-i (fn [i] #(->> (assoc x-vec i %) (apply f)))] (map derivative (map univariate-in-i varity-index) x))) ``` which does exactly what I'd hoped, and seems very concise and functional.
2013/03/18
['https://Stackoverflow.com/questions/15482231', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2136974/']
You can define `univariate-in-i` as shown below. (Assuming that all the other position values are defined in some var default which is a vector) ``` (fn [i] #(->> (assoc default i %) (apply f))) ```
if you find this abit difficult to comprehend (in the context of how to implement gradient), another variant of multivariable gradient implementation using clojure: [![enter image description here](https://i.stack.imgur.com/frt1S.png)](https://i.stack.imgur.com/frt1S.png) then, given `f and vector v of a1,....,aN`, will differentiate while all the variables except xi are fixed: ``` (defn partial-diff [f v i] (let [h 10e-6 w (update v i + h)] (/ (- (apply f w) (apply f v)) h))) (defn gradient [f v] (map #(partial-diff f v %) (range (count v)))) ``` => ``` (gradient (fn [x y] (+ (* x x) (* x y y))) [3 3]) => (15.000009999965867 18.000030000564493) ```
63,071,294
I have a list view with item template formed of several elements, one of them is a frame with `TapGestureRecognizer` added to it as the following example: ```xml <ListView.ItemTemplate> <DataTemplate> <ViewCell> <Grid Margin="10,5" HorizontalOptions="FillAndExpand" RowSpacing="0"> <Grid.ColumnDefinitions> <ColumnDefinition Width="100"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <!-- Other Element --> <Frame x:Name="SampleFrame" Grid.Column="1"/> </Grid> </ViewCell> </DataTemplate> </ListView.ItemTemplate> ``` ```cs public TVEntryItem() { InitializeComponent(); var TapGesture = new TapGestureRecognizer(); TapGesture.Tapped += TapGesture_Tapped; SampleFrame.GestureRecognizers.Add(TapGesture); } private void TapGesture_Tapped(object sender, EventArgs e) { Navigation.PushModalAsync(new DetailedView()); } ``` Now when I tap on the frame the event is called indeed and a new instance of `DetailedView` is created -Verified by break point in the `DetailedView` constructor function-, but the page itself is never displayed, and the break point inside the `DetailedView` `OnAppearing` is never hit. What am I missing here ?! Any suggestions ?! Thanks in advance ^^.
2020/07/24
['https://Stackoverflow.com/questions/63071294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9277972/']
In your case , the Frame is in a ViewCell , so it will never if you handle it in **ContentPage** directly . Firstly , make sure that the **MainPage** of the App is a **NavigationPage** ### in App.xaml.cs ``` public App() { InitializeComponent(); MainPage = new NavigationPage(new xxxPage()); } ``` If you want to add a TapGesture on the frame , you could check the following code . ### in Xaml ``` <?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:d="http://xamarin.com/schemas/2014/forms/design" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Name="Page" // set the name of contentpage here x:Class="xxx.xxxPage"> ``` ``` <Frame Grid.Column="1" BackgroundColor="Red"> <Frame.GestureRecognizers> <TapGestureRecognizer Command="{Binding Source={x:Reference Page}, Path=BindingContext.TapCommand}" /> </Frame.GestureRecognizers> </Frame> ``` ### in ContentPage ``` public xxxPage() { InitializeComponent(); BindingContext = new xxxViewModel(this.Navigation); } ``` ### in ViewModel public class xxxViewModel { ``` public ICommand TapCommand { get; private set; } INavigation Navigation; public MyViewModel(INavigation navigation) { this.Navigation = navigation; TapCommand = new Command(()=> { Navigation.PushModalAsync(new Page1()); }); // other code ,like setting itemsource of listview } } ``` [![enter image description here](https://i.stack.imgur.com/WkIoB.gif)](https://i.stack.imgur.com/WkIoB.gif)
Try this one ``` Navigation.PushModalAsync(new NavigationPage(new DetailedView())); ```
63,071,294
I have a list view with item template formed of several elements, one of them is a frame with `TapGestureRecognizer` added to it as the following example: ```xml <ListView.ItemTemplate> <DataTemplate> <ViewCell> <Grid Margin="10,5" HorizontalOptions="FillAndExpand" RowSpacing="0"> <Grid.ColumnDefinitions> <ColumnDefinition Width="100"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <!-- Other Element --> <Frame x:Name="SampleFrame" Grid.Column="1"/> </Grid> </ViewCell> </DataTemplate> </ListView.ItemTemplate> ``` ```cs public TVEntryItem() { InitializeComponent(); var TapGesture = new TapGestureRecognizer(); TapGesture.Tapped += TapGesture_Tapped; SampleFrame.GestureRecognizers.Add(TapGesture); } private void TapGesture_Tapped(object sender, EventArgs e) { Navigation.PushModalAsync(new DetailedView()); } ``` Now when I tap on the frame the event is called indeed and a new instance of `DetailedView` is created -Verified by break point in the `DetailedView` constructor function-, but the page itself is never displayed, and the break point inside the `DetailedView` `OnAppearing` is never hit. What am I missing here ?! Any suggestions ?! Thanks in advance ^^.
2020/07/24
['https://Stackoverflow.com/questions/63071294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9277972/']
Thanks to [Lucas Zhang - MSFT](https://stackoverflow.com/users/10216982/lucas-zhang-msft)'s answer, I could come up with a solution. As he described, I cannot call navigation service inside a `ViewCell`, so, simply, I called the navigation service from the main page instead. ```cs private void TapGesture_Tapped(object sender, EventArgs e) { App.Current.MainPage.Navigation.PushModalAsync(new DetailedView()); } ```
Try this one ``` Navigation.PushModalAsync(new NavigationPage(new DetailedView())); ```
3,569,553
To give more context, we have $X\_i = 1$ if true, $0$ otherwise. The probability that the outcome will be true is 0.6. The sample is independent. This is my work so far, but I feel like it's wrong.$\DeclareMathOperator{\Var}{Var}$ $\Var(\frac{1}{n}Y) = E[(\frac{1}{n}\sum\_{i = 1}^nX\_i)^2] - E[\frac{1}{n}\sum\_{i = 1}^nX\_i]^2$ $ = E[\frac{1}{n}\sum\_{i = 1}^nX\_i\cdot\frac{1}{n}\sum\_{i = 1}^nX\_i] - (E[X])^2 = E[X^2] - E[X]^2 = \Var(X).$ Where am I going wrong? Thanks. EDIT: To get these equivilances, I'm using the linearity of the expected value and the fact that $E[AB] = E[A]E[B]$.
2020/03/04
['https://math.stackexchange.com/questions/3569553', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/494405/']
$E[(\frac{1}{n}\sum\limits\_{i = 1}^nX\_i)^2] - E[\frac{1}{n}\sum\limits\_{i = 1}^nX\_i]^2$ Up to here it is OK. Then you cannot say that $E[(\frac{1}{n}\sum\_{i = 1}^nX\_i)^2]=E[\frac{1}{n}\sum\limits\_{i = 1}^nX\_i]E\cdot[\frac{1}{n}\sum\limits\_{i = 1}^nX\_i]$. It is just $\frac1{n^2} E(\sum\limits\_{i = 1}^nX\_i)^2)$. And $E[\frac{1}{n}\sum\limits\_{i = 1}^nX\_i]^2=\frac1{n^2}\cdot E[\sum\limits\_{i = 1}^nX\_i]^2$. So in total we have $\frac1{n^2}\cdot Var(Y)$. We know that $Var(\frac1n\cdot Y)=Var(\overline X)=\frac{Var(X\_i)}{n}$ if $X\_i$ are identical and independent distributed. Thus $\frac1{n^2}\cdot Var(Y)=\frac{Var(X\_i)}{n}=p\cdot (1-p)=0.6\cdot 0.4=0.24$
For independent RV's one has $$ Var(\sum\_1^n X\_i) = \sum\_1^n Var(X\_i)$$ hence $$ Var(\frac1n Y) =\frac1{n^2} n Var(X\_1)=\frac1n Var(X\_1) $$ since $X\_i$'s are identically distributed.
73,681,765
I am trying to remove text before specific brackets using REGEX in comma separated column using Pandas From this - ``` colA My Company Ltd [CS], address, nbc [LV], state [NP], pc [SS], country Business Plc [CS], address, abc [LV], state [NP], code [SS], country Work Harder Inc [CS], address, xyz[CS], state [NP], code [SS], country Company Business People [CS], address, typode [SS], country, nlp [CS] ``` **Text before [CS] and [LV] and within brackets has to be removed** Expected result - ``` colA address, state [NP], pc [SS], country address, state [NP], code [SS], country address, state [NP], code [SS], country address, typode [SS], country ```
2022/09/11
['https://Stackoverflow.com/questions/73681765', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12989327/']
You can´t instantiate the `UIApplicationDelegateAdaptor` yourself. The system will do that for you. But there is a workaround. [From Documentation](https://developer.apple.com/documentation/swiftui/uiapplicationdelegateadaptor) > > If your app delegate conforms to the ObservableObject protocol, as in the example above, then SwiftUI puts the delegate it creates into the Environment. You can access the delegate from any scene or view in your app using the EnvironmentObject property wrapper: > > > This means get rid of your `CameraManager`, move the functions into `AppDelegate` and conform it to `ObservableObject` then you can access it in every subview from the Environment as `AppDelegate`.
I'm just posting what I did in case anyone is curious. Instead of trying to use bindings, I just used notification center to post notifications from the app delegate and respond to them from the appropriate views with .onReceive
6,783,556
i want get all values in "Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU" and put it in listbox via c# .
2011/07/21
['https://Stackoverflow.com/questions/6783556', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/856482/']
**EDIT AGAIN FOR Windows Form** Here's a complete listing, assuming you have a ListBox with an id of "lbKeys": ``` using Microsoft.Win32; using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.UI; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1() { RegistryKey myKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU"); // Check to see if there were any subkeys if (myKey.SubKeyCount > 0) { foreach (string subKey in myKey.GetSubKeyNames()) { lbKeys.Items.Add(subKey); } } } } ``` There may not have been any subkeys for the key you were looking at - under the previous code I gave you, the foreach loop wouldn't do anything because there was nothing to loop through.
Use OpenSubKey to open up Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU, and then call GetSubKeyNames to get the names of the subkeys. [Here](http://msdn.microsoft.com/en-us/library/microsoft.win32.registrykey%28VS.80%29.aspx) is a good example for you. I think putting them in a ListBox is fairly easy task. ``` RegistryKey keys Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU"); foreach (string subKeyName in keys.GetSubKeyNames()) { using(RegistryKey tempKey = keys.OpenSubKey(subKeyName)) { Console.WriteLine("\nThere are {0} values for {1}.", tempKey.ValueCount.ToString(), tempKey.Name); foreach(string valueName in tempKey.GetValueNames()) { Console.WriteLine("{0,-8}: {1}", valueName, tempKey.GetValue(valueName).ToString()); } } } ```
472,805
Since moving a laptop when it's powered on can harm the HDD, so I choose to suspend it to memory before moving, so would this still harm the computer ?
2012/09/11
['https://superuser.com/questions/472805', 'https://superuser.com', 'https://superuser.com/users/73361/']
The problem is not that the hardware is not optimized for running Linux; rather, it is that Linux device drivers are not optimized for taking advantage of all the power management features of the hardware. Generally, you will see the most power management problems on Linux with graphics cards. Things like the motherboard, CPU, RAM, case fans, and hard drives are handled very well, and due to efficiencies they may even run cooler than they do on Windows. Graphics drivers on Linux come in two general varieties: proprietary (closed source), and open source. Open source **graphics** drivers, in general, have poor power management (not to be confused with open source drivers for the CPU and other hardware, which have quite good power management). This situation is slowly improving because the graphics drivers are always being worked on and improved. However, **right now**, if you need the absolute best power management for your graphics card, it is better to go with a proprietary driver if available. Here is a breakdown of the availability by vendor: * ATI/AMD: Both proprietary and open source available. Open source drivers are usually used by default and proprietary driver has to be enabled by the user. * Nvidia: Both proprietary and open source available. Open source drivers are used by default on some distributions; other distributions use the proprietary drivers by default. * Intel: Only open source driver available. This open source driver is generally considered to be the most optimized (best performance, power management) compared to the open source drivers for ATI/AMD and Nvidia. Although no high-performance, power-efficient proprietary driver is available for Intel hardware, the power management is already pretty good for the open source driver, so it is safe to use it and should not cause noticeable additional wear and tear.
Generally speaking hardware wear and tear come from fatigue due to heating up and cooling down rapidly over and over again. this causes the materials to develop microscopic cracks that can cause it to fail. I have never heard of one OS causing more or less fatigue than another unless fans and cooling are not configured properly.