Insert or update based on row data

Question: First off, I know about REPLACE INTO and INSERT INTO ... ON KEY DUPLICATE UPDATE but this is not what I'm looking for -or- I don't know how to use them to achieve what I want.
This is my simple table structure:
+-----------+---------+----------+----------+
| player_id | item_id | quantity | location |
+-----------+---------+----------+----------+

My INSERT query looks like this:
INSERT INTO items VALUES (2, 10, 40, 1);

Now, if there is a row where all fields match, except for quantity (doesn't matter if it matches or not, but the point is that the other 3 match). So, if there's a row where player_id is 2, item_id is 10 and location is 1 (quantity value doesn't matter - it can be 40, but also doesn't have to), then I want to update it, rather than insert a new one.
Obviously, I'm looking for a way that is different than SELECT + UPDATE, if there is any...
Comment: so you want to insert new rows on every insert EXCEPT where you got 2,10,x,1, in that case you only want to do an update, right?
Answer: If there are no other constraints to be considered, couldn't you just add a combined unique key over (player_id, item_id and location), and then go for INSERT INTO ... ON DUPLICATE KEY UPDATE?
Edit: Trying to clarify. I suppose you have something like the following table creation statement:
CREATE TABLE items (
    player_id INT NOT NULL,
    item_id INT NOT NULL,
    quantity INT NOT NULL,
    location INT NOT NULL
) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_unicode_ci;

You add a combined unique index for three columns:
ALTER TABLE items ADD UNIQUE player_item_location (player_id, item_id, location);

So you can INSERT this row:
INSERT INTO items (player_id, item_id, quantity, location) VALUES (2, 10, 40, 1);

And if you try to execute the same INSERT again, you end up with the message:
#1062 - Duplicate entry '2-10-1' for key 'player_item_location'

But if you add the ON DUPLICATE KEY UPDATE like this:
INSERT INTO items (player_id, item_id, quantity, location) VALUES (2, 10, 30, 1) ON DUPLICATE KEY UPDATE quantity = 30;

You will end up in not adding another row, but updating the existing one (player 2, item 10, location 1) and changing its quantity from 40 to 30.
And, if you want to add another row, say for player 3, item 10, location 1, this will work, too:
INSERT INTO items (player_id, item_id, quantity, location) VALUES (3, 10, 40, 1);

So after the three INSERTs, you should end up in having the following rows in your table:
mysql> SELECT * FROM items;
+-----------+---------+----------+----------+
| player_id | item_id | quantity | location |
+-----------+---------+----------+----------+
|         2 |      10 |       30 |        1 |
|         3 |      10 |       40 |        1 |
+-----------+---------+----------+----------+
2 rows in set (0.00 sec)

Based on your question, I thought that this is the behaviour you wanted to have. If not, please let us know what exactly doesn't work or where I didn't understand you correctly.
Comment: It won't let me have multiple rows with same player_id, item_id or location. A player can have items on multiple places which are defined by their IDs.
Comment: Tried to clarify my answer by editing it... Hope this makes sense now and works as you expected?
Comment: Thanks, it works perfectly!
Btw, how efficient is this compared with SELECT + UPDATE/INSERT? I'm not able to test with big amount of rows right now, but I'm asking for an approximate evaluation.
Comment: Glad to help! I have no numbers for efficiency, but I suppose since RDBMS are generally really fast when they can use indexes you shouldn't experience performance issues.
Moreover, the `INSERT INTO ... ON DUPLICATE KEY` is executed atomically, which means you don't have to worry about transaction handling - which you would have to if you first `SELECT` and then `UPDATE`, because you cannot be sure that the database content hasn't changed between these two statements.
Answer: Well, you can use BEFORE INSERT triggers, which will be executed before every insert and make the required changes according to the values.
Read more here: http://dev.mysql.com/doc/refman/5.0/en///create-trigger.html

Insert or update based on row data


Harmonizing the bebop major (diminished sixth) scale - Barry Harris

Question: @JohnBelzaguy shared this link with me https://cochranemusic.com/barry-harris-6th-dim-scale-diminished.
It's about Barry Harris and the "diminished sixth" - Bebop major - scale.
But I'm having trouble understanding the basic harmonization Harris is teaching in the video, because the students are having trouble playing it.
This YouTube video is linked right at the time of the scale harmonization:

Are my two harmonizations below right? Harris starts with a Cmaj7 and then seems to just go up the scale in parallel movement...

I'm wondering if a few of my chord symbols are correct? dimΔ7, mΔ7, Δ7♭5 some of those are on multiple roots.
Comment: There are a few better videos of this on YouTube, here's one: https://youtu.be/_n0vuuKdUyM This and a few others have the benefit of Barry not trying to correct people that are scuffling to play it for the first time, phew!
Comment: In the minor version, the fourth chord you call "F dim maj7" ... but it has an Eb? That's not a chord symbol I've ever used, but if it should follow the same logic as your other "dim maj7" chords, then it should have an E natural, right? So that symbol is probably wrong. To me it's more like a rootless G7#5b9
Comment: @piiperiReinstateMonica you're right, it should just be a Fm7b5. It''s the only chord on beats 2 or 4 that's different from major to minor btw. Actually the reason I'm commenting is more to say that almost all the chords on beats 2 and 4 sound like rootless dominants to me, the G7#5b9 could also be a rootless Db9. Also the G#dimΔ7 sounds like an E7#9 or a Bb13 b9. Several of the chords on beats 2 and 4 sound like rootless dominants to my ear since I'm used to playing them in general.
Comment: @piiperiReinstateMonica, I correct the chart for the Fm7b5, thanks for spotting that.
Comment: I see the point about Fm7♭5 and G♯dimΔ7 as dominants or their tritone substitutions, that makes sense as they would resolve to the tonic and it's relative minor. I suppose what I labelled AdimΔ7 and E♭Δ7♭5? would be dominants to Bb moving out of key or tritone subs. to E minor. Does that make sense? My initial question wasn't about _application_ of these odd chords - I just wanted to know if I understood the video lesson - but understanding their use if of course the ultimate goal.
Comment: If I understand the application of these chord correctly, it seems those on basses C, D, G, B have their typical roles of tonic, subdominant, dominant, and the other chords on basses E, F, A can be viewed as various rootless dominants to the tonic, submediant, or mediant, except Em7sus4 and AmΔ7 being mediant and submediant. Is this the basic jist?
Comment: What chord is "Cmaj7" in the sixth diminished scale really? If the basic idea is that in this 8-note scale, building "stacks of thirds" produces only two different chords or functions, tonic and dominant ... then in that sense, a C - E - G - B chord is not a stack of thirds in the scale, because the last interval G - B is actually a _fourth_. So if we use C - E - G - B that's called "Cmaj7", and move that along the scale, do we now have more than two functions?
Answer: The basic concept
Speaking broadly, the point of the bebop scale approach to block-chord harmony is that you don't have to think of a different chord for each melody note. For a major chord, if the melody note is the 1, 3, 5, or 6, you play a major 6 shape (C6), and if the melody is the 2, 4, ♭6, or 7, you play a diminished 7 shape (Bdim7).
The result looks like this. I have put the voicings in close position, assuming you know how to drop the second voice to make it match yours:

Note that in Barry Harris's conception a "major" chord is a major 6, and the 7th scale degree or leading tone is a non–chord tone. If your example had a prominent B on a downbeat, then I would harmonize using a Cmaj7 shape or something similar. But this would be somewhat beside the point, because the context for this discussion is, how do we harmonize a melody built from the bebop scale? The principle of bebop scales is that only chord tones appear on downbeats, so if a melody is written purely using the C major bebop scale, you will never have B (or D, F, or A♭) on a downbeat.
That is to say that the chord voicings Harris is teaching in this video aren't meant to be a comprehensive formula for harmonizing any melody. Any real melody will have some parts that can be interpreted as coming from the bebop scale and others that can't; these voicings apply only to the former.
Also note that for other qualities of chord, there are other bebop scales. The dominant bebop scale is the most important one after the major bebop scale here. These scales also yield two-chord alternating harmonic patterns that can be used to harmonize melodies that use the scale.
I've discussed these considerations on this site before here, but let me excerpt a relevant part:

A different set of voicings, derived from the appropriate bebop scale, is used for each chord. Over the I chord, the voicings come from the major bebop scale and alternate between the major I6 and vii°7 chords. This is because the stable scale degrees (1, 3, 5, and 6) tend to sit on the downbeats, so we'll hear the sound of the I chord on the downbeats and a passing chord, vii°7, on the upbeats. This principle of alternating between the main chord and passing chords is central to Barry Harris's harmonic concept, and also used widely in big band arranging.
Over ii and V, we generally use the mixolydian bebop scale. In C, that's G A B C D E F F#, adding a major 7. The two chord shapes outlined are G7 and  F♯ø7, and a well-constructed melody usually again has G, B, D, and F on downbeats, so the F♯ø7 acts as a passing chord. (Occasionally, one note can be swapped around in order to create smooth voice leading; changing the E here to a E♭ to form F♯°7 is a natural choice.)

There is also a "melodic minor" bebop scale; here I have written out the voicings for a Cm6 to parallel your second line. It's nearly the same, just changing E to E♭:

As for practicing these voicings, I would recommend doing as you have done, writing out the voicings in both close and drop-2 (and maybe drop-2-4 as well) forms, and practicing walking up and down the major scale in various keys. The goal is to get to a point where just looking at the keyboard, you can "see" which notes belong to the "chord tones"/major 6 subset of the bebop scale and which ones belong to the "non–chord tones"/diminished 7 subset. Then the rest of the notes in the voicing just fall in place below the melody.
What's happening in the video
At the point in the video you have linked to, Harris is introducing a more advanced application of the bebop scales that disregards the "alternating chords" principles outlined above. Your transcription is correct, but you should note that that set of voicings is just one of an arbitrary number that you could generate by picking any shape from within the bebop scale and moving each voice up and down in diatonic parallel. Rather than getting hung up on playing that exact line, developing the mental dexterity to walk through the bebop scale using any shape would be a better practice goal.
The editing of the video makes it easy to think that this follows directly from the "basic" bebop scale harmonic conception, when in fact there are multiple things going on: Harris is treating the bebop scale as a mode, and applying another harmonization technique, namely, the technique of moving a shape diatonically through a scale or mode, to it.
So (and this is just my opinion), I wouldn't ascribe special significance to the chord voicings you have transcribed. Rather, we have one concept (bebop scales) and another concept (parallel diatonic harmonization) and they are being used simultaneously.
When someone says "bebop scale harmonization," they are usually referring to the more narrow process outline above.
Comment: In the video they are starting from Cmaj7, aren't they?
Comment: I'm not sure what you mean re. repeating the B. If you check OP's transcription it's clearly what Harris is expecting – e.g. he says "fourths. fourths!" when they get to the Em11 (or Em7sus4 as OP has it) on the way back down. I haven't been able to grab the audio to really convince myself the transcription's accurate but the circumstantial evidence is good --eta: I'm starting the video at 6.29 per the OP's link
Comment: As far as I could tell OP was asking about what happens in that bit of the video ;)
Comment: This is a long answer to a question I didn't ask. I already know about the block chord method. The video presents something different.
Comment: See my last four paragraphs.
Comment: How does that answer whether my notation is what Harris wants the students to play in the part of the video I linked? The problem is the students keep making mistakes. I _think_ I know what Harris wants played, but I'm looking for confirmation of only that.
Comment: "Your transcription is correct."
Comment: This was really helpful! I couldn't figure out what to do on the 7th chord in lieu of the 7 being included in the maj6 inverions, but the fact that he treats it like a passing chord (and therefore a diminished chord being appropriate) unlocked the concept. Thanks!
Answer: People who are into the "Barry Harris" approach seem to be characteristically bad at explaining the point, the purpose, the context, or the intended use of the concept, or maybe perhaps people trying to 'get to grips' with it are expecting a much more holistic and enlightening result than it is reasonable to expect. The point as far as I see it is that when you harmonise, say, the C major scale the traditional way (that is, taking Cmaj7 and repeatedly moving every voice up to the next tone in the C major scale), you get chords with strong harmonic pulls away from C major. Whereas if you add in your favourite extra note, all the chords in the resulting harmonised scale generally feel more or less as if they belong in, or over, C major. You have the details exactly right, but it's really not significant what the chord names of the voicings generated are; the idea is "this is all C major stuff"
Comment: What you call taking Cmaj7 is usually called stacks of thirds, meaning to take every 2nd note of the scale. It extends to Cmaj9, and in theory to Cmaj11, Cmaj13. That's how chords and harmony are built in traditional Western music. If you use other scales, you get different phenomena when taking every other note.
Comment: I meant to say that your answer seems to assume that everyone knows what "the traditional way" is without explaining, or that a maj7 chord is a traditional stereotypical harmonization. In what genres and traditions is this? IMO the answer would benefit from explaining these a little bit.
Comment: Ah, I think I see your point. Especially if the parallel motion is quick you don't hear bona fide chords, it's like passing motion. I did compare this scale harmonization with the block chord (C6 positions with dim7 passing) and after alternating both several times, at a fairly quick pace, it starts to sound the same. At a lower tempo, if wanting to treat these odd voicings like dimΔ7 as bona fide chords, resolving them as some kind of rootless dominant seems to work nicely.
Comment: I think you should explain "the traditional way". Meaning, stacks of thirds, i.e. every second note? All chords that are possible with the major scale are possible with the sixth diminished scale as well, so the point must be what happens when you take every Nth note of the scale.
Comment: Yes, as in applying the same principal but only using the notes we have at our disposal in the C major scale
Comment: Ok I think I see the point you're getting at; I'd say this is focussing more on the meaning of "harmonise the C major scale the traditional way" than I really intended – I just meant "do the thing that's being done here, with the C major scale".
Comment: (not least as trying to view Barry Harris stuff in terms of universal harmonic organisational principles is exactly what I think goes wrong with attempts to understand/apply it! It's "here's a way to generate some cool stuff that sounds good" rather than "this unlocks a new theoretical realm of jazz harmony")
Comment: My concern was only whether my notation was what Harris presented in the video. I only added chord symbols treating the basses and roots. But I think I understand from the other comments many of these chords should be considered rootless voicings of various dominant and tritone substitutes.
Comment: @MichaelCurtis Yes, but (also seeing your subsequent comments) I thought I should warn against – or, to put it a little milder, point away from – over-interpretation of the resulting voicings. For my money, even to say they should be considered this, or considered that, is overegging it – they're voicings you can move up and down through over C major and be reasonably confident it will sound "fine", or "hip". It's just like if you're on C major, and you go Dm7-Ebm7-Em7 – it sounds like you're comping C major. But you don't need to think about the harmonic possibilities of those chords –
Comment: you just run a m7 up from the ii to the iii and you know pretty well in advance what it'll sound like
Comment: @JudyN. Do you mean to say that this Barry Harris scale is sort of like just a way to generate chords that create a sense of motion without actually moving anywhere? Meaning that you layer this "system" over, say, C major,  you kind of stay at C major whatever you do ... but if the "real" chord degree changes to, say, F major, then you should layer a slightly different sixth diminished scale on top of that F major? Can you give an example of what should be played if the "real" chord is F?
Comment: @piiperiReinstateMonica Well... I can only say how I see it, and, like I say, there's a lot of BH 'discussion' that remains totally opaque to me so maybe others have something else going on. But yes, that gets close to how I see it – however I would say, the way you've phrased it puts me in mind of "what scale should I play over this chord" kind of questions. Just as picking a set of notes to play over, say, Am, depends on *personal taste and *where you are in the tune, and just as you might play A dorian, A aeolian, harmonic minor, melodic, bop minor, whole tone, depending on what the tune's
Comment: doing and what side of bed you got out of in the morning, the idea of these scales of chords is to give you ammunition in your arsenal that you have at your disposal, and can call upon at will, as something to play.


RE: Project Euler 1:Find the sum of all the multiples of 3 or 5 below 1000 comments

Question: I see a lot of people saying that the sum of all the multiples of 3 and 5 up to 1000 being one sum and others saying another. Some include the multiples of 15, some don't. So, What is it in reality?
(1..1000).to_a.each do |i|
  num = []
  if i % 3 == 0
    num << i
    p num
  elsif i % 5 == 0
    num << i
    p num
  end
end

I know there is a better way to code this but when i run this code I don't get repeats. meaning no two 15s
So why would we have to subtract it?
just wondering.
Comment: Subtract what? State your question clearly.
Comment: @sawa if you re-read the the question you'll notice i had mentioned only one example to which this post is about. repeating the multiples of 15s to which the multiples of 3 and 5 eventually overlap. so would you agree that you misread it perhaps?
Comment: No I won't. Why should I?
Answer: Building upon the original problem statement from project euler which is less ambiguous:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

This means "multiples of either 3 or 5", which naturally includes multiples of 15 one or the other way around. However, your code will not work, because

the num variable is reset to an empty array on every iteration. You should instead initialize the variable outside of the loop
No need to store the numbers in an array, we can directly compute the sum.
1..1000 will iterate up to the number 1000 whereas the problem clearly wants us to find "all the multiples of 3 or 5 below 1000". You can achieve that with an exclusive range 1...1000 (three dots) or by writing 1..999. This should be the primary reason why you get the wrong result.
to_a is not necessary.
you can combine the conditionals with ||, so you dont have to write the identical inner code twice.

All of this leads to
sum = 0
(1...1000).each do |i|
  if i % 3 == 0 || i % 5 == 0
    sum += i
  end
end

For a more functional-ish approach you could rewrite this as follows:
(1...1000).select {|x| x % 3 == 0 || x % 5 == 0 }.inject(:+)

Comment: thanks for the answer. and Yes the like i said the original code could have done better and proved it right. In sum to all, we do have to include 15s 30s and so forth, where the 3s and 5s overlap.


Partial Möbius convolutions

Question: I am well aware of the Möbius inversion formula, which states
$$\sum_{d \mid q} \mu(q/d) = \mathbf{1}_{q=1}$$
Do we know how to give a closed formula for the "partial" such convolution
$$\sum_{a \mid d \mid q} \mu(q/d) = \sum_{d \mid q/a} \mu(q/d) = ?$$
Comment: Note that the last sum in this post is precisely an instance of the first sum, with $q$ replaced by $q/a$.
Answer: Write $d=at$, so we have
$$
S=\sum_{\substack{t\in\mathbb Z\\at|q}}\mu\left(q\over at\right)=\sum_{t|(q/a)}\mu\left(q/a\over t\right)=\mathbf{1}_{q=a}.
$$

Partial Möbius convolutions


Add border depending on last elements

Question: I have a parent div#main that contains unknown number of divs in rows. Every row has 3 divs that are display: inline-block. Now, because of that, the last row can contain 1, 2 or 3 divs, depending on their number.
If the last row has only 1 div, then I want do add border-left and border-right to it.
If the last row has 2 divs, then I want do add border-right to the first div in that row, or border-left to the second div.
And if the last row has 3 divs, then I want to add border-left and border-right to to the second div (the middle one).
(You'll get the full picture when you look at the snipper, or the fiddle)
I managed to solve this issue by using JS, but I'm looking for a pure CSS solution, if there is one.

$('.main').each(function(){

 var div_length = $(this).find('div').length;

 if((div_length % 3) === 0){
  div_last_items = div_length;
 }

 else if((div_length % 3) === 1){
  div_last_items = div_length - 1;
  $(this).find('div:nth-last-child(1)').addClass('active-borders');
 }

 else if((div_length % 3) === 2){
  div_last_items = div_length - 2;
  $(this).find('div:nth-last-child(2)').addClass('active-border');
 }

 $(this).find('div:lt('+div_last_items+')').each(function(i){
  i=i+2;
  if(i % 3 === 0){
   $(this).addClass('active-borders')
  }
 });
});
.main {
    width: 360px;
    text-align: center;
}
.main>div {
    display:inline-block;
    vertical-align:top;
    width: 100px;
    height: 100px;
    background:red;
    margin-top: 10px;
    margin-bottom: 10px;
}
.main>div:nth-child(3n+2) {
    margin-left: 20px;
    margin-right: 20px;
}

.active-borders{
    border-left: 5px solid black;
    border-right: 5px solid black;
}

.active-border{
    border-right: 5px solid black;
}

JSFiddle
Comment: Hmm ok. Even with pre-processors (SASS, Less etc) I don't think it would be straight-forward because the preprocessors would not know how many elements are present in your markup (unless you compile them on client side in which case you would need JS anyway).
Comment: Possible duplicate: http://stackoverflow.com/questions/8720931/can-css-detect-the-number-of-children-an-element-has or http://stackoverflow.com/questions/26188427/css-trick-nth-of-type
Comment: Just out of curiosity, any reason for wanting a pure CSS solution? I think it is going to be pretty complex (if at all possible).
Comment: @Harry I'm just looking if there is one so I can tell my client that JS is necessary here. However, I don't know if it can maybe done with SASS somehow?
Comment: @Harry yes, that's true. I thought maybe with some combination of `:nth-last-child` and SASS can be possible. Thanks for the effort :)
Answer: I never thought this would be possible with pure CSS but it is. All credits would go to this answer for showing an idea on how this could be achieved. This answer is based on that but I am drafting a separate answer because the selectors are a bit different here and I wanted to explain them.
Selector Additions:
div > div:nth-child(3n) + div:nth-last-child(1) {
  border-left: 5px solid black;
  border-right: 5px solid black;
}
div > div:nth-child(3n+1) + div:nth-last-child(1) {
  border-left: 5px solid black;
}
div > div:nth-child(3n+1) + div:nth-last-child(2) {
  border-left: 5px solid black;
  border-right: 5px solid black;
}

Explanation:
div > div:nth-child(3n) + div:nth-last-child(1)

Select the last child of the parent div when it immediately follows the 3nth child. If the last child immediately follows the 3nth child then it would obviously be the only item in the last row.

div > div:nth-child(3n+1) + div:nth-last-child(1)

Select the last child of the parent div when it immediately follows the 3n+1th child. If the last child immediately follows the 3n+1th child then it means that the last row has 2 items.

div > div:nth-child(3n+1) + div:nth-last-child(2)

Select the second last child of the parent div when it immediately follows the 3n+1th child. If the second last child immediately follows the 3n+1th child then it means that the last row has 3 items.

We cannot use the selector div > div:nth-child(3n+2) + div:nth-last-child(1) for the case where the last row has 3 items because we need the middle element to be styled and not the last,

.main {
  width: 360px;
  text-align: center;
}
.main>div {
  display: inline-block;
  vertical-align: top;
  width: 100px;
  height: 100px;
  background: red;
  margin-top: 10px;
  margin-bottom: 10px;
}
.main>div:nth-child(3n+2) {
  margin-left: 20px;
  margin-right: 20px;
}
div > div:nth-child(3n) + div:nth-last-child(1) {
  border-left: 5px solid black;
  border-right: 5px solid black;
}
div > div:nth-child(3n+1) + div:nth-last-child(1) {
  border-left: 5px solid black;
}
div > div:nth-child(3n+1) + div:nth-last-child(2) {
  border-left: 5px solid black;
  border-right: 5px solid black;
}

The selectors in the above snippet adds a border-left to the second div in the last row if it has only 2 items. If you need to apply border-right to the first div in the last row when it has only 2 items, you can make use of the below selector:
div > div:nth-child(3n+1):nth-last-child(2)

This means, select the second last child of the parent div when it also happens to be the 3n+1th div. If this selector is matched, it implies that the last row has two items.

.main {
  width: 360px;
  text-align: center;
}
.main>div {
  display: inline-block;
  vertical-align: top;
  width: 100px;
  height: 100px;
  background: red;
  margin-top: 10px;
  margin-bottom: 10px;
}
.main>div:nth-child(3n+2) {
  margin-left: 20px;
  margin-right: 20px;
}
div > div:nth-child(3n) + div:nth-last-child(1) {
  border-left: 5px solid black;
  border-right: 5px solid black;
}
/*div > div:nth-child(3n+1) + div:nth-last-child(1) {
  border-left: 5px solid black;
}*/
div > div:nth-child(3n+1):nth-last-child(2){
  border-right: 5px solid black;
}
div > div:nth-child(3n+1) + div:nth-last-child(2) {
  border-left: 5px solid black;
  border-right: 5px solid black;
}

Comment: There's a typo in the second selector in the explanation... `3n` should be `3n+1`
Comment: Here's [a post](http://stackoverflow.com/questions/8720931/can-css-detect-the-number-of-children-an-element-has) from 3 years ago which is also relevant... nice work though +1
Comment: Thanks for both the comment and the link @Danield
Comment: I also didin't thought that it can be done with pure CSS, so I'm really stuned now! Now I have to explain my client that I was wrong :P Thanks a million @Harry.
Answer: In general adding border changes border-box dimension of the element. That change of geometry by itself may move element to the next row. Chicken-egg problem.
Thus you cannot do that by CSS means. And even with JS you should be careful - you may get not you want in some circumstances.

Add border depending on last elements


Qual a maneira correta de realizar testes de desempenho em Python?

Question: Ao responder essa pergunta A sintaxe do Python tanto aceita "+" quanto "," no comando "print()"? :

Apresentei a seguinte resposta:
Caso sua intenção seja imprimir apenas uma linha, ambos os métodos não possuem diferença.

Porém se estiver fazendo print em massa dentro de laço,
por exemplo ao imprimir um relatório, imprimindo uma tabela
ou imprimindo um planilha. E desempenho é o que importa,
a maneira como você faz a concatenação dos dados pode ser
a diferença entre imprimir os dados no intervalo do cafezinho
ou deixar seus dados sendo impressos durante o almoço.

Fiz o teste de desempenho com alguns tipos de concatenação
para saber qual é mais rápido:

import time

#Concatenar usando o operador +
def função1():
  nome = "Júlia"
  print("Olá " + nome)

#Concatenar usando o próprio print()
def função2():
  nome = "Júlia"
  print("Olá ",nome)

#Concatenar usando formatação de string
def função3():
  nome = "Júlia"
  print("Olá %s" % nome)

#Concatenar usando o método join()
def função4():
  nome = "Júlia"
  print("Olá %s".join([nome]))

#Aguarda 5s para estabilização dos processos de inicialização
time.sleep(5)

#Mede o desempenho da função1()
inicio = time.time()
função1()
print("Concatenado com + levou    %s segundos." % (time.time() - inicio))

#Mede o desempenho da função2()
start_time = time.time()
função2()
print("Concatenado com , levou    %s segundos." % (time.time() - inicio))

#Mede o desempenho da função3()
start_time = time.time()
função3()
print("Concatenado com %% levou    %s segundos." % (time.time() - inicio))

#Mede o desempenho da função3()
start_time = time.time()
função4()
print("Concatenado com join levou %s segundos." % (time.time() - inicio))

Os resultados foram esses:

Olá Júlia
Concatenado com + levou    0.00017952919006347656 segundos.
Olá  Júlia
Concatenado com , levou    0.0002543926239013672 segundos.
Olá Júlia
Concatenado com % levou    0.0002880096435546875 segundos.
Olá Júlia
Concatenado com join levou 0.0003311634063720703 segundos.

Foi me informado, nos comentários, que essa não é a maneira correta de medir o desempenho em python. Então aqui vai a pergunta-titulo, qual a maneira correta de realizar testes de desempenho em Python?
Comment: Quando for algo da linguagem em geral, melhor usar a tag "Python" - "python3.x" pode se ruma tag complementar, e nem ser usada na grande amioria das vezes, já que essa é a versão padrão da linguagem.
Comment: Cara, o teste que esta tentando realizar nessa questão do print e irrelevante, porque digo isso? vamos por parte, o __+ (mais)__ junta as strings, a __, (virgula)__ passar argumentos separados onde o __print__ utilizar digamos o __*args__ para receber uma lista de variáveis e depois jogar e alinhar no print, o restante é manipulação da string por isso leva mais tempo, resumindo, são para uso diferentes que no seu caso tem a mesma saída, é só questão entender o que cada um faz
Comment: Sim, por isso deixei apenas um comentário para tentar esclarecer qualquer tipo de duvida, mas não uma reposta, em questão de performance já complica um pouco para responder, como o @Woss disse acima, Qual desempenho..., pois para cada objetivo pode se ter uma reposta e um resultado diferente, são coisas que podem até depender da sua maquina, Tempo de execução? uso de memoria? entre outros. não há um geral, e caso deseje tudo, teria que coletar cada informação separadamente e depois utilizar uma regressão a fim de encontrar uma media entre tudo.
Comment: Para deixar claro, qual desempenho estamos falando? Apenas tempo de execução ou gostaria de avaliar utilização de recursos, número de operações, etc?
Comment: @Woss, Seria interessante saber como fazer uma avaliação completa de um fragmento de código.
Comment: @Woss Eu andei pesquisando os módulos [`dis`](https://docs.python.org/3/library/dis.html) . e[`timeit`](https://docs.python.org/3.8/library/timeit.html), ia ler agora o [`profile`](https://docs.python.org/3.8/library/profile.html)
Comment: Já me falaram isso @GuilhermeFrançadeOliveira, a pergunta é qual a maneira correta de se fazer um teste de performance em python. Outra coisa não é print que está sendo mesurado são as formas de concatenação de strings.
Answer: Essencialmente tens duas formas rápidas para testar a performance de cada método.
Podes optar por usar correr cada função dentro da função timeit.timeit():
def foo():
    # ...

duration = timeit.timeit(foo, number=1000)

Caso possas usar IPython, tens acesso à função %timeit:
In [2]: %timeit função1()
773 µs ± 46.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [3]: %timeit função2()
278 µs ± 3.91 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [4]: %timeit função3()
135 µs ± 763 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [5]: %timeit função4()
126 µs ± 1.31 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Comment: Uma questão que levantei na outra resposta era a independência dos testes. Fazê-los juntos dará um resultado diferente do que executar os testes separados. O que pode dizer sobre isso?


Alternatives of OpenID/OAuth2.0 for first-party (main) application without redirect to login page?

Question:
I would like to know if there exists alternative for OpenID/Oauth2.0 for first-party apps like public SPA without redirecting user to OpenID login page?
I know there exists password grant type, but it's deprecated as written in Oauth2.0 docs.

And if there is no alterative solution, is it good choice to implement only JWT issuer (auth) service without OpenID on my own? Will it be still secure? If yes, then which details should I take into consideration?
Comment: Have you found a satisfactory answer to this question? I'm curious whether OAuth 2.0 (first-party) is still a viable choice for trusted first-party mobile app clients or a first-party trusted single-page application (SPA), and whether there is a way to obtain a token directly via an HTTP request flow using user credentials obtained from the native mobile app's login screen
Answer: If you have a first-party app, which only talks to your backend then it should be enough to use sessions. You don't need to implement OAuth and JWTs, and using sessions will solve some you some security issues with tokens (e.g. how to securely store them in the browser).
If you do decide to use access tokens I highly recommend implementing OAuth or OIDC, as this will mitigate some common security vulnerabilities.


Memory: how does the compiler choose where to store variables?

Question: Given two functions, func1 and f2, with the following signatures:
void func1(){
    int baba = 12345;
    // printf the value of baba here
}

void f2(){
    int loo;
    //printf the value of loo here
}

...if I run my int main, which only has func1 then f2:
int main(){
      func1();
      f2();
}

...then the printed value of both baba and loo will be 12345.  So my question is as follows:

Is this defined behaviour, or just something erroneous that my machine does?
If this isn't some erroneous thing my computer did, can you explain why the compiler chooses to store loo in the same address as baba?

EDIT:  I guess I should ask, if I have these EXACT two functions, will     baba and loo have the same value on ANY machine?
I understand loo's value is the result of baba's leftover  bits, and I understand that (on my machine, at least) the stacks of both are being laid out such that loo overlaps onto baba's old territory.  Is it true that every machine would lay these two function stacks out in such a manner that baba and loo overlap?  Using these two functions exactly as written, that is...
Comment: 1. Its UB. 2. Its an erroneous thing in the code, not the compiler. `loo` is indeterminate. Evaluating it invokes UB. Why the same address choice was used is implementation-dependent.
Comment: Think about how temporary local variables can be allocated on the stack and then it should be obvious.
Comment: I am puzzled why this question is marked as answered and linked to a different question. If it has been answered, it should be to a similar question.
Comment: If an interrupt happens between calling `func1()` and `f2()` the previous `12345` on the (below stack pointer) stack would not survive.
Comment: I think that this is undefined behaviour. The way that it works is that when you call func1 the stack is pushed and the value 12345 is put assigned to an address in the new stack frame. When you leave func1 the stack is popped back to the calling stack frame. When you call f2 the stack is again pushed and as you have the same number of parameters in both calls (none) the location in memory of loo is now where baba was, this bit of memory has not been wiped and contains the same data.
Comment: @PaulR can you explain?  I don't know much assembly so maybe I'm missing something.I know that during the creation/destruction of func1(), the space assigned to baba gets the int literal "12345" written into it.  When loo is created, it's taking that same address space.  I understand that's why the value is there, but I was wondering if it's merely coincidence that loo has the same address space.  I guess a better question would be, is loo guaranteed to always occupy that space (in THESE given functions, on every platform)
Comment: Thank you all very much for the insight!!!
Comment: @user3344003   Yeah, I was wondering the same. These are two very different questions, as mines about assembly and portability, whereas the linked one is about stacks and scope
Answer: In f2(), lolo is uninitialized.  It's content is hence undefined.
Most often however, the content appears to be the data that was on the stack.  By coincidence, you've first called func1(), which has exactly the same memory/stack layout than f2(). So by chance the variable contains the data that was previously stored at the same place.
This behavior is not guaranteed at all.  It only appears to work in this specific context because no other local variables were created between the two calls, and no other function call overwrites the data with other content (and the two functions have exactly the same memory layout).
Here a small picture to explain the situation in this specific case:
Comment: I use "undefined" as in "Undefined Behaviour" i.e. the c++ standard does not define a behaviour.  But undefined/indeterminate does not mean that it's random.  So I dare to maintain:  *"It works only in this specific case on this compiler with the same compiling switches with this operating system"*


Puppet: SSL certificate Error

Question: I did this
sudo puppet agent --test
err: Could not retrieve catalog from remote server: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed
warning: Not using cache on failed catalog
err: Could not retrieve catalog; skipping run

I deleted the ssl directory but nothing help. I read the docs and none seem to work out. Any suggestion where to tackle?
the client is signed on the master.
Thanks.

Is time sync? I checked date and they both seem okay.
openssl x509 -text -in /var/lib/puppet/ssl/certs/...

Weird... I don't have ssl directory?
What should I use to generate? There are too many commands ... I just wan to be careful.
This is the log for running sudo puppet master --debug --no-daemonize:
http://pastebin.com/TM3KHmzx
Then on client
admin@client:~$ sudo puppet agent --test
err: Could not retrieve catalog from remote server: Connection refused - connect(2)
warning: Not using cache on failed catalog
err: Could not retrieve catalog; skipping run

Here is my fileserver.conf
[blueprint1234]
path /etc/puppet/modules/blueprint1234/files
allow 10.10.0.0/12

Did I put the IP right? The internal IP of the client (it is a VM) is 10.10.0.12
Here is the site.pp
node blueprint1234 {
        include blueprint1234
}

node 'client' inherits blueprint1234 {
}

Thanks
Comment: Since puppet has the least helpful error messages I've ever come across on a program, you might want to do the following for us to try and help you: Stop your puppet master, then type `puppet master --debug --no-daemonize` on the console and run it. Then run the puppet agent. When you start seeing errors on the `Master`, copy and append them here.
Answer: The most common cause for that is that the time of both machines are different by more than a few seconds.
Answer: I've dealt with this a bunch of time and the solution that usually works is doing an rm -r on /var/lib/puppet/ssl (or whatever the ssldir is) on the puppet client (i.e. where you are running puppet agent commands). Then, on the puppet master, run sudo puppetca --clean FQDN where FQDN is the fully qualified domain name. That means not just blueprint1234 but blueprint1234.yourdomain.com or whatever. If you don't get any output from the clean command, then you don't have the correct name...if it worked you'll seeing something about removing the certificate that you specified.
Comment: I had a similar issue with a similar error. The problem I had was my hostnames were all messed up may just double check

Puppet: SSL certificate Error


How to compare date between 2 tibbles?

Question: mydf<-data.frame(x=as.Date("2017-1-1"))
mydf[1,1]-as.Date("2017-10-16")

Time difference of -288 days
mytb<-tibble(x=as.Date("2017-1-1"))
mytb[1,1]-as.Date("2017-10-16")

Error in mytb[1, 1] - as.Date("2017-10-16") :
  non-numeric argument to binary operator
In addition: Warning message:
Incompatible methods ("Ops.data.frame", "-.Date") for "-"
How to compare the date in tibble? I have a solution: convert tibble to dataframe, but is there any more feasible idea?
Comment: Not very clean but do the trick:  mytb$x[1] - as.Date("2017-10-16")
Comment: @Flo.P Your comments are part of the answer below, thanks anyway!
Answer: There is potentially a difference in behavior between data.frame vs. tibble/data_frame.  With data.frame, the drop = TRUE
mydf[1,1]
#[1] "2017-01-01"

changes the data.frame to a vector when there is subsetting of single row/column etc.
But, it is not the case with tibble
mytb[1,1]
# A tibble: 1 x 1
#  x
#   <date>
#1 2017-01-01

It is still a tibble.  So we need to extract it with either $ or [[
mytb[['x']][1]
#[1] "2017-01-01"

The tidyverse option would be pull
mytb %>%
     pull(x) %>%
     magrittr::extract(1) %>%
     magrittr::subtract(as.Date("2017-10-16"))
#Time difference of -288 days

Comment: It works, thanks! I just wanna know how to convert a tibble to vector.
Comment: @wasmetqall  You can use `unlist` or if it is a single column tibble, either `mytb$x` or `mytb[['x']]` would do it

How to compare date between 2 tibbles?


A secure single site JWT implementation

Question: I read a lot about JWTs and found that it is pretty hard to use them in a secure CSRF and XSS proof way.
Until I realized that my tokens will probably not leave my unique domain...
This led me to this idea of implementation:

Use a refresh token along with an access token. That way I can set short expiring time to the access token and limit the database calls to verify the user and only when the access token expires a simple verification by asking the database that the refresh token is not blacklisted before sending a new access token to the user.
I understood that if I store a token in the local/session storage it would be vulnerable to XSS attacks but if I store it in an HTTP-only cookie it would be vulnerable to CSRF attacks.
As I don't need to access the token inside the JavaScript and that I only need this token in one website, I thought that I could store the access token inside an HTTP-only cookie (that way it is protected from XSS) along with the secure flag and the same site flag set to strict (preventing CSRF).
And regarding the refresh token I could store it inside an HTTP-only cookie that has the same secure flag but without the same site flag this time. Because the server will never execute any action only based on the refresh token, I think that it will therefore not be susceptible to CSRF attacks. The only thing the server will do with a refresh token is to send back a new access token which, if I understood it well, could not be read from the CSRF attacker. The CSRF vulnerability allows the attacker to make a request to the server (which will automatically contain HTTP-only cookies) but he cannot read the response of this request.

I don't know if this implementation of JWTs would be secure or if I missed something...
This is what I'm asking you (JWTs and web security experts) would that be a good JWTs implementation ?
Comment: I think you just need a plain old session id with server-side sessions. A JWT has about zero benefit for your usecase, but the complexity does not help security.
Answer: First, a word on JWTs. An oldschool plain server-side session (with a long, random session id, correctly stored in a secure, httpOnly, maybe also SameSite cookie) is "more secure" than any JWT in most cases. The reason is that JWTs store state on the client, where it is more available to an attacker, offline attacks can be performed against the cryptography involved, also JWTs are plain text and only their integrity is protected (ie. they are protected against client-side change, but not against looking at the contents by default, though you could use JWE, and encrypted JWT too). Last but not least, implementation is more complex, and simplicity is great for security.
So you would use a JWT when you need a benefit that it provides.
One argument is that it's stateless. This is very often overrated though. First, in most applications the bottleneck will not be the database lookup needed to find the session data in the database. In some very high profile, high traffic applications it actually might be, but you are probably not developing something like that every day. Usually it's just ok to do a database lookup, and it makes the whole thing a lot simpler. Second, sometimes you need token revocation, ie. you want to be able to force-logout a user. Even if you used a JWT for statelessness, you would have to store something in a database, a list of revoked tokens for example, and checking that would also be a database roundtrip. Revoking JWTs simply cannot be implemented in a purely stateless way.
Another benefit is that you can use it for multiple origins. If you get a httpOnly session cookie, that will be managed by the browser, javascript cannot send it to other origins, like an API or something - that's the whole point, JS not having access. But sometimes you do need that, especially in single sign-on scenarios, where you have an identity provider (a component that provides logon), and services (eg. APIs) that you want to use your access token on. In this case a classic cookie would not work, and JWTs are very handy.
So in short, you would use a JWT when you really need statelessness, or the option to send the token to multiple origins. As a rule of thumb, if you can store the JWT in a httpOnly cookie, you most probably don't need it at all, and could just use a plain old server-side session.
And then let's say you decide to use JWTs, what about refresh tokens. They are another generally misunderstood feature of token-based authentication. The point in using refresh tokens is to be able to use short-lived access tokens, so if an access token get s compromised, it is at least time limited. But if you store the refresh token the same way as an access token, why would an attacker not get that too?
It only makes sense to have a refresh token, if you store it differently, otherwise you could just have long-lived access tokens, and that would not be less secure.
One typical thing is to have an identity provider ("login server", or IdP) that sets a refresh token (or just a plain old session id) in a httpOnly cookie for the identity provider origin, so whenever the client makes a request to the IdP, it "just works" if they are already logged in, and can provide a new access token without user interaction. The access token is then stored in something like localStorage (for the service origin), susceptible to XSS, but at least time limited. If you don't have this separation, a separate refresh token probably doesn't  make much sense.
As a final note, all of this should very rarely be implemented by yourself. Any language or framework you use probably already has one or more known good, maintained implementation for authentication. You should just use those, but it's still very much worth to understand it of course.
Please note that in any actual application there might be subtleties and certain circumstances that somewhat change what you want to do, but the above is a general way to think about secure authentication.
Comment: Thanks a lot! You are right, I should use sessions... I was attracted by the stateless side of JWTs but as I need revocation it isn't worth it... On top of that it's probably not that much of a cost to run a db query on each request.

A secure single site JWT implementation


Uncaught TypeError: number is not a function : While create dojo class

Question: I am learning dojo
i have created a dojo class using declare as below
require(
["dojo/_base/declare"],function(declare){
    return declare(null,{
      constructor : function(){
          alert("done");
      }
    });
});

and this is save in /learnDojo/root/test.js
and the index.html as below
<!DOCTYPE html>

<title></title>

i have the index.html in the /learnDojo which is in webapps folder of the tomcat
When i load this from browser i am getting the error "Uncaught TypeError: number is not a function"
Why? any issue with code or dojo syntax for creating the class
Answer: When defining Dojo modules you should be using define(), not require(). So your /learnDojo/root/test.js file would look like this:
define(
["dojo/_base/declare"],function(declare){
    return declare(null,{
      constructor : function(){
          alert("done");
      }
    });
});

The reason for this is that define() will actually return the object/value you returned in your callback (in this case the return declare(...) statement. A require() however will not return that value, causing strange errors.


Control Matrix from a generator matrix

Question: Given a [8,4]-Code over field $\mathbb{Z}_2$ and it's basis, I need to calculae the control matrix.
In my homework, we are given (0,0,0,0,1,1,1,1), (0,0,1,1,0,0,1,1), (0,1,0,1,0,1,0,1), and (1,1,0,0,1,1,0,0) as basis.
I've already constructed one of the possible generator matrices, by simply putting those vectors as rows in to the generator matrix.
Now, I probably have to do some matrix manipulations to get it to the standard form $G = [I_{k\times k} \mid (P^T)_{k\times(n-k)}]$
from which I could get control matrix $H$ as $H=[-P^T|I]$, but I'm not sure how to proceeed, and if there is any easier way to do that.
Answer: Just so we're on the same page, here's the definition of control matrix I'm familiar with.

Definition: Let $C$ be a $[n,k]$ linear code over a field $F$ with generator matrix $G$, so that $C = \{ mG \mid m \in F^k \}$. If $H$ is a matrix such that
$$C = \{ x \in F^n \mid Hx^T = 0 \},$$
then $H$ is called a control matrix of $C$.

First, we need a small lemma. You may have already seen this in your class.

Lemma: Let $C$ be a $[n,k]$ linear code over a field $F$ with generator matrix $G$ and let $S$ be an invertible matrix. Let $D$ be the code with generator matrix $GS$. If $H$ is a control matrix of $D$, then $HS^T$ is a control matrix of $C$.
Proof: Since $D$ has generator matrix $GS$ and control matrix $H$, we have
$$ D = \{ mGS \mid m \in F^k \} = \{ x \in F^n \mid Hx^T = 0 \}. $$
Note that $C = \{ mG \mid m \in F^k \}$. Define $X = \{ x \in F^n \mid HS^T x^T = 0 \}$. We will show that $C = X$.

($C \subseteq X$) Consider any $c \in C$. Then $cS \in D$, so $HS^T c^T = H(cS)^T = 0$, and so $c \in X$.
($C \supseteq X$) Let $x \in F^n$ and $HS^T x^T = H(xS)^T = 0$. Then $xS \in D$, so there is some $m \in F^k$ such that $mGS = xS$. Since $S$ is invertible, we have $mG = x$, so $x \in C$.

Since $C = X = \{ x \in F^n \mid HS^T x^T = 0 \}$, we have that $HS^T$ is a control matrix for $C$.

Back to your problem. Let
$$
G = \begin{bmatrix}
0&0&0&0&1&1&1&1\\
0&0&1&1&0&0&1&1\\
0&1&0&1&0&1&0&1\\
1&1&0&0&1&1&0&0
\end{bmatrix}.
$$
Put $G$ in reduced row echelon form to get a matrix
$$
G' = \begin{bmatrix}
1&0&0&1&0&1&1&0\\
0&1&0&1&0&1&0&1\\
0&0&1&1&0&0&1&1\\
0&0&0&0&1&1&1&1
\end{bmatrix}.
$$ Note that the row space of $G$ and $G'$ are the same, so they're both generator matrices of $C$. The problem here is $G'$ isn't in the form $[I|P^T]$. Let $S$ be the $8 \times 8$ permutation matrix that swaps columns 4 and 5:
$$
S = \begin{bmatrix}
1&0&0&0&0&0&0&0\\
0&1&0&0&0&0&0&0\\
0&0&1&0&0&0&0&0\\
0&0&0&0&1&0&0&0\\
0&0&0&1&0&0&0&0\\
0&0&0&0&0&1&0&0\\
0&0&0&0&0&0&1&0\\
0&0&0&0&0&0&0&1\\
\end{bmatrix}.
$$
Then $G'S = [I|P]$ for some matrix $P$, so the code with generator matrix $G'S$ has control matrix $[-P^T|I]$. By the lemma, $[-P^T|I]S^T$ is then a control matrix for $C$.

TL;DR: Let $C$ have generator matrix $G$. Put $G$ in RREF. Swap columns until it's in the form $[I|P]$. Let $H = [-P^T|I]$. Swap the same columns in $H$ in the reverse order. The resulting matrix is a control matrix of $C$.

Control Matrix from a generator matrix


Problema na execução das Threads , usando flags

Question: Estou com uns problemas no entendimento completo do código pois sou novo na utilização do java em thread. O que código vai fazer é controlar o fluxo, fazendo 55 iterações dividindo entre a thread e programa principal (main):
Resultado:
Main Thread.: 1
New Thread..: 2
Main Thread.: 3
New Thread..: 4
...
Main Thread.: 51
New Thread..: 52
Main Thread.: 53
New Thread..: 54

Até aí tudo bem , o problema está , quando em certa execução o programa entra em alguns loop infinito e não para de executar outra vezes ele completa a execução , queria ajuda para entender este problema.
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 /
package testando;

/*
 *
 * @author Márcio
 */
public class Testando {
static int value = 0;
static int flag = 1;

@SuppressWarnings("empty-statement")
    public static void main(String[] args) {

                class MyThread extends Thread {

                        @Override
                        public void run() {
                                while(flag == 1);
                                while(++value < 55) {
                                        System.out.println("New Thread..: " + value);
                                        flag = 1;
                                        while( value < 55 && flag == 1);
                                }
                        }
                }

                Thread thread1 = new MyThread();
                thread1.start();
                System.out.println(flag == 0);
                while(flag == 0);
                while(++value < 55) {
                        System.out.println("Main Thread.: " + value);
                        flag = 0;
                        while( value < 55 && flag == 0);
                }
        }
    }

Comment: `while(flag == 1);` pra que isso?
Comment: Meu estava testando aqui, vir o código executar sem está função,  e sem também `while(flag == 0);` , peço que desconsidere esta parte.
Comment: Poderia remover as tags desnecessárias dentro da sua pergunta e do código?
Answer: O que está causando racing conditions no seu código é o fato do acesso às variáveis não ser atômica, isto é, elas são acessadas concorrentemente por mais de um thread. Se você quer que essas variáveis sejam usadas pelo código sem que a operação executada em um thread afete a operação executada pelo outro, você deve encapsular as operações de leitura e alteração do valor das variáveis em blocos synchronized (dentro dos quais somente pode entrar um thread de cada vez) ou então usar objetos que garantam a atomicidade da operação como por exemplo AtomicInteger.
Comment: Ah, sim. Provavelmente o OP necessita de uma solução com `wait()` e `notify()/notifyAll()` para permitir que os _threads_ se alternem no incremento da variável, dispensando uma `flag` de controle.
Comment: O problema é esse mesmo, mas acho que `AtomicInteger` não vai adiantar nesse caso porque o incremento e o teste da variável acontecem em locais separados.
Comment: É verdade. Mas as operações de incremento e teste não precisam ser dentro do mesmo bloco `synchronized`, apenas cada uma delas deve ser atômica, não? A API de `AtomicInteger` talvez resolva isso, com métodos como por exemplo `compareAndSet()`. Ou essa mesma API pode permitir que o par de ações em si seja atômico.
Comment: Não havia analisado o código com calma. Se for reescrito de maneira adequada o `AtomicInteger` provavelmente resolve. O problema é que o código está meio gambiarrado, esses *loops* "infinitos" ali para fazer sincronização não me cheiram bem.
Comment: Um [Semaphore](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Semaphore.html), um [CountDownLatch](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html) ou uma [ReentrantLock](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/ReentrantLock.html) com duas [Conditions](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Condition.html) também podem ser usados para evitar a espera ocupada e a flag.


Using Dreampie with Revit

Question: I'm new to using python on Autodesk Revit. My favorite prompt for using python is a little app called Dreampie. It works with python and ironPython.
http://www.dreampie.org/
I was wondering if there is a way to connect this application to Revit instead of the RevitPythonShell (RPS window is modal and does not have as many features as dreampie)...
Thanks in advance
Answer: I think it can't be done. Different construction - DreamPie is standalone program and RevitPythonShell seems to be plugin (embbed element) with access to Revit.
But RevitPythonShell is Open Source and you can make modifiactions in it.
Comment: As far as I know about programming if a simple plugin can get the Revit handler from revit and then lunch Dreampie it would be great... I'm not sure though. Thanks for response.
Comment: I think, you can run `Dreampie` on your own and you get the same result as lunching it from plugin.
Comment: I tried that. Even loaded the Dlls that 'RevitPythonShell', uses. But don't know how to connect it to the running instance of application. Don't know much about. NET
Comment: And `Dreampie` doesn't know it too. It has no build-in functions to do that. I use Dreampie but I don't use Revit so I can be wrong.
Comment: Well `dreampie` is only a shell for a shell. I'm using it with IronPython 2.7 but don't know much about. NET and can't figure out how to find the instance of Revit through the .net platform.

Using Dreampie with Revit


Determining whether or not an element is integral over $\mathbb Z$

Question: I want to prove that $\alpha=\frac{\sqrt[3]{2}}{2}$ is not integral over $\mathbb{Z}$ (i.e. not an algebraic integer). Is there a way to modify the following reasoning to make it work?
A quick check shows that $P(x)=4x^3-1$ is the minimal polynomial of this $\alpha$ over $\mathbb Q$. So I set $I=\{p(x)\in \mathbb Q[x]:p(\alpha)=0\} =(P(x)) \triangleleft \mathbb Q[x]$. I claim that if $q(x)$ is a monic polynomial in $\mathbb Z[x]\cap I$ then $P(x)|q(x)$ in $\mathbb Z[x],$ not just in $\mathbb Q[x]$. I.e. I claim that if $P(x)p(x)=q(x)$ for some $p(x)\in \mathbb Q[x]$, we also have $p(x) \in \mathbb Z[x].$ But $p(x)$ is a root of the polynomial $P(x)y-q(x) \in \mathbb Z[x][y]$ and so $p(x)$ is integral over $\mathbb Z[x]$. But $\mathbb Z[x]$ is integrally closed, since it's a UFD and therefore $p(x)\in \mathbb Q[x] \implies p(x) \in \mathbb Z[x]$.
I have realised that after writing this, $p(x)$ actually isn't integral as the polynomial  $P(x)y-q(x)$ is not monic. Is there any way of salvaging this argument, or proving the result a different way? I want to say something like "If the monic minimal polynomial of $\alpha \in\mathbb C$ over $\mathbb Q$ does not have integer coefficients (In my above example, this polynomial would be $ x^3-\frac{1}{4} \notin\mathbb Z[x]$) then this $\alpha$ is not an algebraic integer."
Answer: If $\alpha$ is integral over $\mathbb{Z}$, then the $\mathbb{Z}$-module generated by 1, $\alpha$, $\alpha^2$, $\alpha^3$ ... is a finitely generated $\mathbb{Z}$-module, but this is obviously false for your $\alpha$ (the denominators get arbitrarily large).
Answer: Hint: If $\alpha$ is an integral over $\mathbb Z$, then $\alpha^3$ is also integral over $\mathbb Z$.
Now if a number is rational and integral over $\mathbb Z$, then....
Answer: In general I think this follows, more or less straightly, from Gauss's Lemma, yet , in your case we can try as follows:
Suppose $\;\alpha\;$ is an alg. integer, so that there exists a monic polynomial $\;f(x)\in\Bbb Z[x]\;$ s.t. $\;f(\alpha)=0\;$ . But $\;p(x)=x^3-\dfrac14\;$ is the minimal polynomial of $\;\alpha\;$ over $\;\Bbb Q\;$, and of course $\;\Bbb Z\subset\Bbb Q\;$ , so that we have that $\;p\mid f\;$ . Yet in order to have $\;f\;$ as a multiple of $\;p(x)\;$ we must get rid of that $\;\frac14\;$ there, and this can't be done without violating the fact that $\;f\;$ is monic.
Fill in details.
Answer: Another perspective is to use valuations.  The $2$-adic valuation $\nu_2$ extends (in general nonuniquely) to a valuation on $\mathbb{Q}(\sqrt[3]{2})$.  Actually, you can show that there is only one prime lying over $2$ here with ramification index $3$, so the extension is unique. You have $\nu_{2}(\sqrt[3]{2}) = \frac{1}{3} \nu_2(2)$, with $\nu_2(2) = 1$.  Thus $$\nu_2(\frac{\sqrt[3]{2}}{2}) = \nu_2(\sqrt[3]{2}) - \nu_2(2)  < 0$$ so $\frac{\sqrt[3]{2}}{2}$ can't be integral over $\mathbb{Z}$ (to be integral, it has to have nonnegative value at every prime).


Tricolor columns-only Hackenbush boards: must adding the "rainbow" board eventually stabilize?

Question: This is a question about "columns-only three-color Hackenbush." Formally, a board is a finite formal sum (or multiset if one prefers) of finite strings from $\{1,2,3\}$. For $i\in\{1,2,3\}$ and a board $B$, a legal move in $B$ for player $i$ consists of replacing one occurrence of a string $\sigma\in B$ with one occurrence of a string $\tau$ such that $\tau i\preccurlyeq\sigma$. (Intuitively, a string $\sigma$ occurring in $B$ represents a "stack of edges" labelled according to $\sigma$ from the ground up.) As in an earlier MO question of mine, define the "basic type" of a board $B$ to be the set $bt(B)$ of pairs $(x,A)$ such that $x\in \{1,2,3\}$, $A$ is a nonempty proper subset of $\{1,2,3\}$, and there are strategies $\pi_a$ for $a\in A$ which when followed ensure that the first player to be unable to move will not be in $A$ assuming player $x$ starts and move ordered proceeds in the obvious cyclic order from then on. (Intuitively, $(x,A)\in bt(B)$ means "team $A$ can avoid losing in $B$ if $x$ goes first.")
Now let ${\bf z}=\langle 1\rangle+\langle 2\rangle+\langle 3\rangle$ be the "rainbow" board. Interestingly, and in contrast with the two-color version, adding ${\bf z}$ does not preserve basic type. For example, we have $(1,\{3\})\in bt(\langle 123\rangle)$ but $(1,\{3\})\not\in bt(\langle 123\rangle+{\bf z}$). Essentially, adding a copy of ${\bf z}$ lets players $1$ and $2$ swap roles for one round, and that helps them beat $3$ if $1$ goes first.
Despite this, I'm curious whether adding ${\bf z}$ does eventually preserve basic type:

For a board $B$, is there necessarily a natural number $k$ such that $$bt(B+m{\bf z})=bt(B+n{\bf z})$$ whenever $m,n\ge k$?

Here $aC=C+C+C+...+C$ ($a$ times) for $a\in\mathbb{N}$ and $C$ a board. I would also be interested in the answer to the analogous question for $p>3$ players.
Answer: Yes, the basic type of $B+n{\bf z}$ always stabilizes.
For teams $A$ of size $2$, adding a copy of ${\bf z}$ is always weakly beneficial to $A$. To be precise, for all $x\in\{1,2,3\}$, if $(x,A)\in bt(B)$, then $(x,A)\in bt(B+{\bf z})$. This is because team $A$ can ignore the ${\bf z}$ component, using their winning strategy for $B$ part, and respond to the third player playing in ${\bf z}$ by playing in ${\bf z}$ for the next two turns.
For the same reason, for teams of size $1$, adding a copy of  is never helpful, since the opponent is a team of size $2$.
In either case, we have shown that the membership status of $(x,A)$
in $bt(B+n{\bf z})$ as $n\rightarrow\infty$ must converge.

In fact, this is true for any number of players:
Let $p$ be the number of players, let $x\in\{1,\dots,p\}$, and let $A$ be a nonempty proper team. Divide the game into rounds, where each round is a sequence of $p$ consecutive moves starting with the initial player, $x$. For a game played on $B+n{\bf z}$, call a round boring if all $p$ moves of that round are played in one of the ${\bf z}$ components. Under optimal play, you can assume that all boring rounds happen at the end of the game. Indeed, suppose there is an optimal line of play in which round number $i$ is boring, but round number $i+1$ is interesting. Suppose team $A$ was the first team in round $i+1$ to make a move in the $B$ component; then team $A$ could have just made that same move in round $i$. If you repeat this logic, you can move all boring rounds to the end.
Now, let $e$ be the total number of edges in $B$. There can be at most $e$ interesting rounds in any game of the form $B+n{\bf z}$. Therefore, for any $n>0$, optimal play on $B+(e+n){\bf z}$ is identical to optimal play on $B+e{\bf z}$, followed by $n$ boring rounds. This means they have the same outcome, so that adding $e$ copies of ${\bf z}$ is sufficient to stabilize the basic type.

Finally, even when $p=3$ there do exist boards such that the time you have to wait for stabilization is arbitrarily high. For any $n,k\in \mathbb N$, consider the board
$$
\langle1^n2^n\rangle+\langle3^{n-1}\rangle+k{\bf z}
$$
with players $1$ and $2$ teamed up, with $1$ going first. In order to avoid losing, player $2$ has to make $n$ separate moves in the $\langle1^n2^n\rangle$ component. Since any move by player $1$ in $\langle1^n2^n\rangle$ would destroy all of $2$'s potential moves, player $1$ needs to make $n$ moves in the ${\bf z}$ components. That is, the team can win if and only if $k\ge n$.
Comment: Ah yes, I was overcomplicating things. That said, do you have any idea what happens with $p>3$ players? At a glance the argument here doesn't work in general, since more complicated coalitions are possible with more players.
Comment: I am pretty sure I have solved it for any number of players, have a look.
Comment: I don't understand the sentence "Suppose team $A$ was the first team in round $i+1$ to make a move in the  component; then team $A$ could have just made that same move in round $i$." Can you elaborate?
Comment: @NoahSchweber I agree that that part is lacking in detail, I will work on writing up something clear.
Comment: I've taken the liberty of adding back in the argument for the $p=3$ special case, since that's the part I agree with completely and that answers the question as posed.


How to log exception in Java

Question: I am running a complex multithreaded Java application and facing some issue with logging exceptions.
There's a class ExceptionLogger which handles exception, here's the code snippet.
public class ExceptionLogger {

    private enum EXTYPE {
        ERROR, INFO, WARNING
    }

    private static Logger logger;;
private  static void log(String message, EXTYPE msgtype) {

    boolean append = true;
    try {
        FileHandler fh = new FileHandler("messages.log", append);
        fh.setFormatter(new Formatter() {
            @Override
            public String format(LogRecord rec) {
                StringBuffer buf = new StringBuffer(1000);
                buf.append(new java.util.Date());
                buf.append(' ');
                buf.append(rec.getLevel());
                buf.append(' ');
                buf.append(formatMessage(rec));
                buf.append('\n');
                return buf.toString();
            }
        });
        logger = Logger.getLogger("messages");
        logger.addHandler(fh);

        switch (msgtype) {
        case WARNING:
            logger.warning(message);
            break;
        case ERROR:
            logger.severe(message);
            break;
        case INFO:
            logger.info(message);
            break;
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    public static synchronized void logEx(Exception e) {
        // if(e.getMessage().compareTo("Widget is disposed")==0) return;
        log("Error message :" + e.getMessage(), EXTYPE.ERROR);
        e.printStackTrace();
        log("cause :" + e.getCause(), EXTYPE.INFO);

    }

}

Now the issue is that when multiple thread log exceptions multiple files are created like messages.log.1 messages.log.2 ...
Even though I have declared it as synchronized function, shouldn't the threads wait to log their exception, instead of creating new files.
Also 1 more thing with the e.getMessage() just gets me message like null pointer exception... No reference to class or line no. is there. How to get that as well. The code is soon going into production and I cannot rely on e.printStacktrace for debugging.
Comment: Why not use one of several mature logging frameworks for java? There's the [`java.util.logging`](http://download.oracle.com/javase/6/docs/api/java/util/logging/package-summary.html) package, [log4j](http://logging.apache.org/log4j/1.2/), [slf4j](http://www.slf4j.org/), etc. You won't have to concern yourself with threading issues.
Answer: I see that you use java.util.logging.Logger. Instead of creating FileHandler on every call to log, do it in static section of ExceptionLogger. And initialize logger when you declare it.
private static Logger logger = Logger.getLogger("messages");
static {
    FileHandler fh = new FileHandler("messages.log", append);
    fh.setFormatter(new Formatter() {
        @Override
        public String format(LogRecord rec) {
            StringBuffer buf = new StringBuffer(1000);
            buf.append(new java.util.Date());
            buf.append(' ');
            buf.append(rec.getLevel());
            buf.append(' ');
            buf.append(formatMessage(rec));
            buf.append('\n');
            return buf.toString();
        }
    });
    logger = Logger.getLogger("messages");
    logger.addHandler(fh);
}

Then instead of having your custom signature for log, just use
public void log(Level level,
                String msg)

for regular messages or
public void log(Level level,
                String msg,
                Throwable thrown)

for exceptions.
See http://download.oracle.com/javase/6/docs/api/java/util/logging/Logger.html
And there are much better ways to configure it via properties.
Ultimately, you probably don't need custom class as you can just use Logger directly.

How to log exception in Java


Group users and display the group on the profile page

Question: How can I create a group/role/taxonomy term or anything else to group specific users ? I also want to display the "group/role/taxonomy term or anything else" on the users profile.
For example: I go to example.com/user/1 and I see all of his details AND that he has the administrator-"group/role/taxonomy term or anything else".
Thanks in advance (I am a noob here)
Comment: Welcome to the Drupal Stack Exchange community!
Answer: Roles have a set of permissions, so they are ideal if you will have a set of users  editing certain types of content,
 like blog posts, and another group of user commenting on the content.
 You can create both new roles and permissions.

Roles: /admin/people/roles
Permissions: /admin/people/permissions

You can also add fields to the users, like a taxonomy where they choose whether they are a dog person or a cat person.

Manage fields: /admin/config/people/accounts/fields
Manage form display: /admin/config/people/accounts/form-display

Then, you can choose which fields will be displayed on the user profile page

Manage display: /admin/config/people/accounts/display
Comment: A combination out of roles and taxonomy terms worked great, thanks!


Matlab logical operation on array

Question: My question should be fairly easy, but I can't get it to work.
I want to take from a matrix only the relevant rows by using logical operators and then storing those rows only.
I'm used to doing this with a for-loop in other languages, but in Matlab it should be faster to run this over the entire array or matrix at once.
This is an example of what I think should work, but all my similar attempts generate different errors, and I'm not sure what to do.
Mrelevant = Matrix(Matrix.no_refs > 100)

Edit: Matrix is actually a table with headers, I want to keep only the rows that fulfil certain requirements, like the value in the column with header 'no_refs' should be above 100.
I hope this is clear enough, thanks!
Comment: Please see: [mcve]
Comment: Apparently `Matrix` is not a matrix but a struct of some type. Please add code to create a sample `Matrix` and the output you expect for this data.
Comment: See here a close example: https://stackoverflow.com/questions/45526311/find-the-largest-value-in-a-column/45526702#45526702
Answer: Now that you specified Matrix is a table, the answer is clear. You forgot an additional colon index argument to include all variables for the given rows you are selecting:
Mrelevant = Matrix(Matrix.no_refs > 100, :);

This will give you a new table Mrelevant that includes only those rows from Matrix where the no_refs variable is greater than 100. See here for all of the ways to access data in a table by row and/or variable.
Answer: The syntax you are showing here should work, though I do not know what the purpose of the no_refs might be. The correct syntax is:
Mrelevant = matrixName(matrixName > 100)

However, this will create a single column containing the values that meet the condition. For example,
testMatrix =
0.8147    0.0975    0.1576    0.1419    0.6557
0.9058    0.2785    0.9706    0.4218    0.0357
0.1270    0.5469    0.9572    0.9157    0.8491
0.9134    0.9575    0.4854    0.7922    0.9340
0.6324    0.9649    0.8003    0.9595    0.6787

relevant = testMatrix(testMatrix > .5)

relevant =
0.8147
0.9058
0.9134
0.6324
0.5469
0.9575
0.9649
0.9706
0.9572
0.8003
0.9157
0.7922
0.9595
0.6557
0.8491
0.9340
0.6787

However, when you say

only the relevant rows by using logical operators and then storing
  those rows

do you mean storing only rows where all elements in the row meet the condition? In that case, the syntax would be
 relevant = testMatrix
 % Delete all rows that don't meet the requirement
 relevant(any(relevant<=100, 2),:) = [];

This will simply erase any row containing values that don't meet your requirement.
Comment: I'm getting _Matrix index is out of range for deletion._ Any clue why that would be the case?
Comment: Could be because a particular matrix wasn't formed correctly. If you could post your command line or your script to the point that the error occurred, I can help debug it further.

Matlab logical operation on array


Putting an array value into a string in powershell

Question: I was having difficulty understanding how String values work with arrays in powershell. I wanted to know the correct syntax for placing an array into a string. Currently, this is what I am trying. The square brackets seem to be registered as part of the string rather than the variable.
$array = @(2,3,5)

$string = " I have $array[2] apples"

This outputs:  I have 2 3 5[2] apples
Comment: Use $($array[2]) the $() runs whatever is inside as powershell
Comment: There's also the `-f` operator; e.g.: `"I have {0} apples" -f $array[2]`
Answer: The [2] is being read as a string. Use $($array[2]) in order to run that part as powershell.
$array = @(2,3,5)

"I have $($array[2]) apples"

This outputs I have 5 apples.
In the comments you asked how to do a for loop for this.
In powershell you should pipe whenever you can, the pipe command is |
@(2,3,5) | foreach-object{
    "I have $_ apples"
}

Comment: Thanks! I was wondering if this would also apply to $(array[$i]) where $i is the variable declared by a for loop.
Comment: I answered your comment in the solution
Comment: @J.Tam answer your question from comment yourself `$array = @(2,3,5);for($i=0;$i -le 2;$i++){"I have $($array[$i]) apples"}`
Comment: For in-memory collections I suggest not recommending use of the pipeline, at least not without explaining the performance implications.
Comment: I know this is pretty old, but what might those performance implications be? I typically use C#, but am doing some PowerShell right now and was about to just do a for loop as I normally would, but came across this answer and was going to use the above "PowerShell way" and pipe it, but then I saw this comment, and now I don't know what I should use.
Comment: @MostHated There is a performance hit when you use Linq because it has overhead.
 Here is a example...If I measure how long it takes to cycle through a array of 1000 objects. ForEach-Object takes 64 milliseconds, ForEach() takes 16 milliseconds and For() takes 2 milliseconds
Comment: Ah, I understand. While I should have, I didn't realize that using pipe methods like that would end up being Linq. Definitely glad that I do know that for sure now, so thanks.


How to predict in advance that a smart meter is failing?

Question: I have an electricity consumption data set collected by smart meters over a year and a half for every hour. The objective is to predict whether the meter could fail earlier than it actually fails.I have three columns CUSTOMER_ID, DATE/TIME-STAMP, CONSUMPTION. Meter reading degradation could point out that failure is about to happen, is there any way to detect this by using any algorithm? possibly any outliers or anomaly detection algorithm?
Comment: It could be helpful to link this to your own older, related [question](http://stats.stackexchange.com/questions/140786/which-method-to-use-for-load-forecasting).
Comment: It is unclear to me what you mean by reading degradation.
Comment: @kasterma degradation in the sense the smart meter might start generating anomalous data before it actually breaks down. I need to know which algorithms to try out to detect that.
Answer: Do you have any idea of what is characteristic to a meter that is about to fail? Perhaps it stops working for a while and does so every now and then with increasing frequency? Then you would see periods of zero consumption in the data. If that happens when the consumption is normally high (in light of historical data), that could be an indication of meter failure. Or perhaps it shows unusually high values that are very unlikely or even technically impossible? You should be able to see that relatively easily (compare with historical peaks and/or technical upper limit).
The general idea would be to estimate some characteristics of the historical data (mean, variance, autocorrelations at different lags etc.) and see how the new data fits in, i.e. whether it has similar characteristics or not. The similarity could be quantified if you estimated some confidence bounds for the historical characteristics. You could use rolling windows over the historical data and collect the historical characteristics across all of them. Then you would have "clouds" of values and would be able to see the new value in the context of the "cloud". If the new value is close to the edge of the "cloud" or beyond it, it is an indication that something has changed, perhaps the meter went crazy.
If your data has a decent signal-to-noise ratio, you could try modelling your data. Again, use rolling windows to estimate a model, then predict a few points into the future. This way you will collect a set of predictions and the corresponding realized values (while still in the historical sample). You will see how well your model predicts in terms of, say, root mean squared error (RMSE), mean absolute percentage error (MAPE), mean absolute scaled error (MASE) etc. Then make a forecast from the last observed window of data. When new data comes in, you could see how well they accord with the forecast. If the forecast is much more off than typical in the light of historical data, you have a reason to suspect that either the meter is going nuts or the electricity consumption behaviour has changed.
Comment: First of all, Richard i would like to thank you for going through my query and responding, the answer has thrown light to further research. well I assumed that a meter would fail if it starts generating values that is not in sync with the user's usage pattern, so what i thought was to forecast the load and check for prediction errors, which is also what you stated. The problem now is that what algorithm? time series or Neural networks or SVM to use for load forecast.....will continue in next comment(Stack exchange doesnt allow me to type infinite characters ;) )
Comment: After going through few research papers, it seems several factors like weather,month,day of week, holidays,time of day all have effect on electricity consumption. Since i dont have any data related to weather but having all data related to rest mentioned above, i want to know which algorithm will be good to use and will have less MAPE. ....thanks in advance
Comment: I do not have experience with electricity load forecasting but I know there is a large literature out there. But perhaps most of it is not about individual users, so maybe it is irrelevant. Anyhow, [here](https://www.otexts.org/book/elf) is a whole free online textbook about electricity load forecasting. Maybe you will get some good ideas from there. With regards to different algorithms, the obvious (but also perhaps the most tedious) way is just to try out different methods on historical data and pick the one that performs best (to prevent overfitting, use training and validation).
Comment: I doubt you would be able to pick the best method without trying the candidate methods out on the historical data...
Comment: Thanks a lot Richard....i will try implementing all the algorithms....is there any other way to reach you, i might have doubts in working with time series in R.
Comment: I suggest you keep using Cross Validated and Stack Overflow instead of relying on me only for R help. I normally follow Cross Validated quite frequently, so perhaps I will notice your new question. Good luck!
Comment: @user3146895 I think you should be able to get the information related to weather from the general usage pattern (if it gets warm and ACs use more electricity, this is similar for most users).  This depends of course on how geographically disperse your users are (or if you can get geographic info on your users).
Comment: @katerma unfortunately all those datas are unavailable, we simply need to make predictions based on this.
Comment: @RichardHardy i have posted a new question about time series representation in R pls go through and any help is appreciated.


Crystal Report Entire Row height increase

Question: (Broken image was here)
The growth increases the height of the one row column but it doesn't increase the height of the entire row. i have checked and it can grow for all the fields, one of the field has been  greyed out and cannot be checked. The "keep object together" box is checked in the format field properties of the field. I checked and the "Keep Together" field was checked inthe field properties and in the section expert. i tried all different ways,and don't know what kind of formula I would use to get the whole row growth while at least one field height increases in a row.
Comment: I don't see any image.  Do you have multiple rows in a single detail section, however?  Is that the issue?
Comment: sorry! I was not able to attach the image the site did not able as i am a new user.i have only one row in the detail section of designer. i have lla rows set to can grow but on increse of height of one field in the row the entire row dosent increase in height.
Comment: Yeah, unfortunately I think without a picture I'm not going to be of much help.  If a row is set to `Can Grow`, the entire row should grow as well, so I'm not sure why the rows aren't increasing in height in your case.
Answer:
You can solve this issue by using boxes and lines instead of fixed borders around the fields.

Place a box around your fields spanning the header and details sections then right click and format box. Tick/check 'Extend to bottom of section when printing'.

Place separator lines vertically between each field making sure they touch the top of the box (don't worry about touching the bottom). Now right click each vertical line and format line.
Tick/check 'Extend to bottom of section when printing'.

Now when your can grow field is more than 1 line the fields will appear to have borders as you wish! -

For More Reference - Click here

Another reason for no increase in height of whole row when one column/field value grows is that..a fixed horizontal separator line would be just touching the details field. Make sure if there is any horizontal separator line added by you then it should be aloof from the fields added. (i.e, Clearance Margin must be there between the line and the data field column added).

This solution worked for me big time :)


Flutter upgrade error: Your local changes to the following files would be overwritten

Question: Upgrading the Flutter SDK and packages
    My-Mac:~ admin$ flutter upgrade

    Upgrading Flutter from /Users/admin/Desktop/SDK/flutter...
    error: Your local changes to the following files would be overwritten by merge:
        packages/flutter/lib/src/services/message_codecs.dart
    Please commit your changes or stash them before you merge.
    Aborting
    Updating 2eeeXXXe9..7XXXbf4aX

I have gone on the flutter SDK and check status and got below things
My-Mac:flutter admin$  git status
On branch master
Your branch is behind 'origin/master' by 565 commits, and can be fast-forwarded.
  (use "git pull" to update your local branch)

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)
modified:   dev/automated_tests/pubspec.yaml
modified:   dev/benchmarks/complex_layout/pubspec.yaml
modified:   dev/benchmarks/macrobenchmarks/pubspec.yaml
modified:   dev/benchmarks/microbenchmarks/pubspec.yaml
modified:   dev/bots/pubspec.yaml
modified:   dev/devicelab/pubspec.yaml
modified:   dev/integration_tests/android_semantics_testing/pubspec.yaml
modified:   dev/integration_tests/android_views/pubspec.yaml
modified:   dev/integration_tests/channels/pubspec.yaml
modified:   dev/integration_tests/external_ui/pubspec.yaml
modified:   dev/integration_tests/flavors/pubspec.yaml
modified:   dev/integration_tests/platform_interaction/pubspec.yaml
modified:   dev/integration_tests/ui/pubspec.yaml
modified:   dev/manual_tests/pubspec.yaml
modified:   dev/snippets/pubspec.yaml
modified:   dev/tools/pubspec.yaml
modified:   dev/tools/vitool/pubspec.yaml
modified:   examples/catalog/pubspec.yaml
modified:   examples/flutter_gallery/pubspec.yaml
modified:   examples/hello_world/pubspec.yaml
modified:   examples/layers/pubspec.yaml
modified:   examples/platform_channel/pubspec.yaml
modified:   examples/platform_channel_swift/pubspec.yaml
modified:   examples/stocks/pubspec.yaml
modified:   packages/flutter/lib/src/services/message_codecs.dart
modified:   packages/flutter/pubspec.yaml
modified:   packages/flutter_driver/pubspec.yaml
modified:   packages/flutter_goldens/pubspec.yaml
modified:   packages/flutter_localizations/pubspec.yaml
modified:   packages/flutter_test/pubspec.yaml
modified:   packages/flutter_tools/pubspec.yaml
modified:   packages/fuchsia_remote_debug_protocol/pubspec.yaml

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    OLDSDK.zip

no changes added to commit (use "git add" and/or "git commit -a")

After do above task now try to upgrade again Flutter but got again error mentioned below
My-Mac:flutter admin$ flutter upgrade
    Building flutter tool...
    Because flutter_tools depends on sockjs_client 0.3.5 which doesn't match any versions, version solving failed.
    Error: Unable to 'pub upgrade' flutter tool. Retrying in five seconds... (9 tries left)
    .
    .
    Error: Unable to 'pub upgrade' flutter tool. Retrying in five seconds... (1 tries left)
    Command 'pub upgrade' still failed after 10 tries, giving up.

Answer: Flutter uses git for SDK management.
You'd need to review your repository located in $HOME/development/flutter.
You can use git command to check your repostory status.
For example,
$ git status

To see your local change
$ git branch

To see which branch you are using.
Following steps might help you when you find you've changed something uncommitted, but you would like to undo all changed to simply switch to latest version (master).
$ git reset --hard HEAD

To undo all your changes.
$ git checkout master

To switch to master branch
$ git pull

To pull down and sync all commit on server.
Answer: You have some uncomitted changes in the flutter SDK, If You want to remove those changes and upgrade flutter, then you can force upgrade
flutter upgrade -f

Force upgrade the flutter branch, potentially discarding local changes.
Comment: This only works if there is a new version. If you are on the latest version this does not do anything,.
Comment: This ended up working for me
Comment: @under when you are already on the latest version what is it supposed to do?
Answer: You are maybe accidentally edit flutter code.
To fix it, go to your flutter folder, it should be /Users/admin/Desktop/SDK/flutter
and check any changes by run
git status

If anything changes, in your case you made change packages/flutter/lib/src/services/message_codecs.dart, just revert it by :
git checkout -- packages/flutter/lib/src/services/message_codecs.dart


C#: Rectangles drawn with DrawRectangle on a non-primary monitor doesn't render top and left borders

Question: I have a full screen form and in the handler for the Paint event I am drawing a 2px border around the entire form. I create one of these forms for each screen attached to the computer. For some reason, the top and left borders are not drawing on any non-primary monitors. The form's background covers the entire screen but I can't see to draw (using GDI) on area about 3px down from the top and 3px in from the left of the screen.
My Paint event handler code is below.
private void OnPaint(object sender, PaintEventArgs e)
    {
        using (Graphics g = this.CreateGraphics())
        {
            int border = 2;
            int startPos = 0;
            // offset used to correctly paint all the way to the right and bottom edges
            int offset = 1;
            Rectangle rect = new Rectangle(startPos, startPos, this.Width - border + offset, this.Height - border + offset);
            Pen pen = new Pen(Color.Red, border);

            // draw a border
            g.DrawRectangle(pen, rect);
        }
    }

Has anyone seen this before?
Comment: Why are you creating a new Graphics Object? There is one in the EventArgs.
Comment: Nice catch. I have updated to use the Graphics object in the PaintEventArgs.
Answer: Your code works Correct.
You should know when you are using this.Width or this.Height, these values calculating with the frame that surround your form.
For the Height, the height of your form controls added to calculated height.
You can using this code :
using (Graphics g = this.CreateGraphics())
            {
                int border = 2;
                int startPos = 0;
                // offset used to correctly paint all the way to the right and bottom edges
                int offset = 1;
                Rectangle rect = new Rectangle(startPos, startPos, this.Width-20, this.Height-40);
                Pen pen = new Pen(Color.Red, border);

                // draw a border
                g.DrawRectangle(pen, rect);
            }

UPDATE :
If you want to calculating exact size you can use this code :
 int width,height;
    public Form1()
    {
        InitializeComponent();
        PictureBox pc = new PictureBox();
        pc.Dock = DockStyle.Fill;
        this.Controls.Add(pc);
        pc.Visible = false;
        width = pc.Width;
        height = pc.Height;
        pc.Dispose();
    }
    private void Form1_Paint(object sender, PaintEventArgs e)
    {

        using (Graphics g = this.CreateGraphics())
        {
            int border = 2;
            int startPos = 0;
            // offset used to correctly paint all the way to the right and bottom edges
            int offset = 1;
            Rectangle rect = new Rectangle(startPos, startPos, width,height);
            Pen pen = new Pen(Color.Red, border);

            // draw a border
            g.DrawRectangle(pen, rect);
        }

    }

Comment: I don't get it. The Graphics Object and the usable Rectangle is in the EventArgs. Why not simply take and use them?


Problemas com Implementação de View Model

Question: Estou tentando utilizar o conceito de View Model Pattern, porém quando estou implementando o compilador está apresentando um erro de conversão.
Abaixo segue abordagem que utilizei:
Estrutura da viewmodel
public class EvolucaoViewModel
{
    public Chamado ChamadoAtual { get; set; }
    public virtual ICollection<Evolucao> Evolucoes { get; set; }
}

Implementação no controller
public ActionResult DetalharChamado(int? id)
{
    EvolucaoViewModel model = new EvolucaoViewModel();

    model.ChamadoAtual = _contexto.Chamados.Find(id);
    model.Evolucoes = _contexto.Evolucoes.Where(e => e.id_chamado == id);

    ViewBag.id_usuario = new SelectList(_contexto.Usuarios, "id_usuario", "nome_usuario", model.ChamadoAtual.id_usuario).OrderBy(p => p.Text);
    ViewBag.id_chamado = id;
    ViewBag.id_setor = new SelectList(_contexto.Setores, "id_setor", "nome_setor", model.ChamadoAtual.id_setor);
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    if (model == null)
    {
        return HttpNotFound();
    }
    return View(model);
}

Quando tento fazer essa atribuição o VS me apresenta a mensagem abaixo:
model.Evolucoes = _contexto.Evolucoes.Where(e => e.id_chamado == id);

Erro 3 Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.ICollection'. An explicit conversion exists (are you missing a cast?) E:\DevSpace\Projetos\Albasi.Atende\Albasi.Atende.Web\Controllers\ChamadoController.cs 77 31 Albasi.Atende.Web

O que preciso modificar?
Comment: Deu certo, jovem?
Comment: Olá jbueno, para o controller sim, porém para exibição na view só consegui por meio do helper Gridview. Não tem como eu utilizar HTMLHelper?
Comment: Marcelo, ótimo então. Mas eu não faço ideia sobre este novo problema. Aliás, ele deve ser resolvido em outra publicação, ok? Abra uma [nova pergunta](https://pt.stackoverflow.com/questions/ask) com sua dúvida atual, explicando o seu cenário e marque a resposta que mais te ajudou como correta usando o **✓** do lado esquerdo da resposta (você só pode marcar uma como correta).
Answer: A propriedade Evolucoes da ViewModel declara uma ICollection e o retorno do método Where (ao menos quando aplicado a um IQueryable) é sempre um IQueryable, ou seja, você está tentando fazer um ICollection receber um IQueryable, isso está errado.
É preciso converter o retorno do Where para algum tipo que implemente ICollection, como List ou outros.
O que você precisa trocar é
Esta linha
model.Evolucoes = _contexto.Evolucoes.Where(e => e.id_chamado == id);

Para
model.Evolucoes = _contexto.Evolucoes.Where(e => e.id_chamado == id).ToList();

Answer: Utilize a conversão para lista ".ToList()" no trecho abaixo:
model.Evolucoes = _contexto.Evolucoes.Where(e => e.id_chamado == id).ToList();

Comment: Obrigado jbueno e Elton. Situação parcialmente resolvida... me deparei agora com uma nova situação, dessa vez na view. Lá não consegui utilizar HTMLHelpers para exibir as informações da coleção Evoluções. Só consegui fazê-lo utilizando uma WebGrid. Como poderia fazer para utilizar algo como @Html.DisplayNameFor(model => model.Evolucoes.texto_evolucao) ???
Comment: Por que você simplesmente copiou a minha resposta, Elton?
Comment: @jbueno, provavelmente eu não vi a sua resposta. Note que ela é bem simples, apenas um "ToList" resolve o problema de cast e também o intervalo entre a minha e a sua publicação foi bem pequeno. ok?
Comment: Estranho, são 57 minutos de diferença, mas eu acredito em você. Perguntei mesmo porque as vezes o pessoal que chega novo acaba confundindo algumas coisas...
Comment: @jbueno, zelar por qualidade e cumprimento das regras é uma virtude! Parabéns pelo seu trabalho na comunidade. Se acha que a resposta é repedita, eu excluo numa boa! o que acha?
Comment: Nah, é uma linha de código só e a solução é realmente essa, faz sentido termos pensado na mesma coisa. Pode manter ela e, como tá certa, vou deixar um voto positivo.
Comment: @jbueno, deixei o meu voto no seu ;)
Answer: Tenta assim:
model.ChamadoAtual = _contexto.Chamados.Include(i => i.Evolucoes).Find(id);

e remove o
model.Evolucoes = _contexto.Evolucoes.Where(e => e.id_chamado == id);

Comment: Tentando dessa forma o compilador apresenta o seguinte erro:
Erro 5 Cannot convert lambda expression to type 'string' because it is not a delegate type
Comment: Está faltando dar using System.Data.Entity; ou também dá para tentar:

    model.ChamadoAtual = _contexto.Chamados.Include("Evolucoes").Find(id);
Comment: Já estou utilizando o using System.Data.Entity;

Com a modificação sugerida o compilador apresenta o seguinte erro:
Erro 4 'System.Data.Entity.Infrastructure.DbQuery' does not contain a definition for 'Find' and no extension method 'Find' accepting a first argument of type 'System.Data.Entity.Infrastructure.DbQuery' could be found (are you missing a using directive or an assembly reference?)