Android System.currentTimeMillis() value is different on firebase database than generated on app logcat

Question: I am submitting a user last seen on Firebase Realtime Database and before setting value at firebase database I am generating a log with timestamp by System.currentTimeMillis() but when I compare it with logcat and database timestamp it submits a different timestamp on the server.
Look at the logcat it shows the correct timestamp and it should be on the server too
Disconnect with the firebase server
Offline Time 5:01 pm 1639308715905

Firebase Realtime Database Value of Timestamp
1639308009264

Both Values are different that's how I get wrong last seen of the user
1639308715905 - App one
1639308009264 - Server One

The code I am using for log and to set a value on the server.
public class MainActivity extends AppCompatActivity {

    public static final String TAG = "Main Activity";

    FirebaseDatabase DatabaseInstance;
    DatabaseReference infoConnected;

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "On Resume Running");
        DatabaseInstance.goOnline();

    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "ON STOP CALLING");
        DatabaseInstance.goOffline();

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DatabaseInstance = FirebaseDatabase.getInstance(); // Single Instance
        infoConnected = DatabaseInstance.getReference(".info/connected"); // To check firebase connection state
        initialiseOnlineStatus();

        setContentView(R.layout.main);
    }

    private void initialiseOnlineStatus() {
        final DatabaseReference Online = DatabaseInstance.getReference("Users/" + userID + "/Online");
        final DatabaseReference lastOnline = DatabaseInstance.getReference("Users/" + userID + "/lastSeen");

        infoConnected.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                boolean connected = dataSnapshot.getValue(Boolean.class);

                if (connected) {
                    Online.setValue(Boolean.TRUE);
                    lastOnline.removeValue();

                    Log.d(TAG, "Connected To Firebase Server ");
                } else {
                    Log.d(TAG, "Disconnect with firebase server ");
                    Online.onDisconnect().setValue(Boolean.FALSE);
                    String offlineTime = String.valueOf(System.currentTimeMillis());
                    Log.d(TAG, "Offline Time " + App_Functions.getLocalDeviceTimestamp(Long.parseLong(offlineTime)) + " " + offlineTime); // Get local device time from milliseconds
                    lastOnline.onDisconnect().setValue(offlineTime);

                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }

}

Update: I noticed that the last timestamp (generated by an app) is uploading not the current one, I really don't understand how my last seen is not updating by the current timestamp. Please check gist too for the complete code
I also noticed that on the launch of my activity, the firebase function call twice, first with value boolean connected = dataSnapshot.getValue(Boolean. class); false than true. So with the false value, I am getting the first timestamp which should not update when activity onStop calls and when the app calls onStop it updates the timestamp which was first created on app launch.
Comment: There's a little more than 10 minutes between your two example timestamps. Could one of the clocks be running inaccurately?
Comment: @ole My android device create both timestamp as you can see in code above. It's not clock thing, in code above I'm first getting timestamp from device then upload it to the server, and before uploading I'm generating log in Android studio then upload it on server and when i compare server timestamp with logcat, it's shows the difference between both. I don't understand why because I'm uploading same as in logcat
Answer: I want to say thanks to @argzdev and @frank For helping me out at github. The solution i got from Github by @argzdev:

The reason this doesn't work is because you're trying
to set a value after you've already disconnected the connection, it's
bound to cause issues.
What you can do is change the logic of how you store the timestamp.
Simply store the timestamp BEFORE you sever the connection. There
shouldn't be any difference in time, even if there was, it would only
be miniscule.
Relevant code:

 @Override
>     protected void onResume() {
>         super.onResume();
>         Log.d(TAG, "On Resume Running");
>
>         Online.setValue(Boolean.TRUE);
>         lastOnline.removeValue();
>         DatabaseInstance.goOnline();
>     }
>
> @Override
>     protected void onStop() {
>         super.onStop();
>         Log.d(TAG, "ON STOP CALLING");
>
>         Online.setValue(Boolean.FALSE);
>         lastOnline.setValue("" + System.currentTimeMillis());
>         DatabaseInstance.goOffline();
>     }
>

Then you can simply remove the onDisconnect in your
ValueEventListener.
Answer: When you call this in your code:
lastOnline.onDisconnect().setValue(offlineTime);

This sends a literal value to the server, with the instruction to write that value when it detects that the client has disconnected. The server has no knowledge of the meaning of the value, and can't make any changes to it.
So if a different value is being written on the server than is being logged in the client, the only reason I can think of is that your calling onDisconnect (elsewhere?) too with a different value.
Comment: Keep in mind that we can only see what you share in your code, and the initialization of `infoConnected` is not in there. Assuming it is  listening to `.info/connected`, it is indeed expected to change value a few times when the app starts - as the SDK is establishing a connection to the correct server. But this goes back to the last sentence of my answer: "So if a different value is being written on the server than is being logged in the client, the only reason I can think of is that your calling `onDisconnect` (elsewhere?) too with a different value."
Comment: ` lastOnline.onDisconnect().setValue(offlineTime);` I also tried to add suffix to the value to check if value is setting on some other place. I got the suffix value to server but `offlineTime` is changed. I don't understand how? I am also disconnecting and connecting to the server at onPause and `onResume`
Comment: I noticed that last timestamp (generated by app) is uploading not the current one, i really don't understand how my last seen is not updating the current one even i tired `lastOnline.onDisconnect().setValue(System.currentTimeMillis())` directly
Comment: Can you please suggest issue in my code. I created a gist of firebase database you can check https://gist.github.com/varun7952/d6475a1b2dfe1b9b964bd829d53405b8
Comment: There really doesn't seem to be anything more going on there. Since you're passing the value to write directly from your code, the database can't be modifying it. Are you sure that is the value you're looking at though? I noticed you're passing the value as a string, but I'm not sure if in the screenshot in your question that is actually a string.
Comment: Please look at it again, the value i had was long not string,i was testing with long value, you also can reproduce issue by gist i mentioned. I think it's onDisconnect causing this issue which taking last value of System.currentmTimeMillis(), it's not string or long.
Comment: I update the question.I also noticed that on launch of my activity, the firebase function call twice, first with value `boolean connected = dataSnapshot.getValue(Boolean.class);` false then true. So with the false value i am getting the first timestamp which should not update when activity `onStop` calls and when app calls `onStop` it update the timestamp which first created on app launch.
Comment: Sorry i post complete firebasae related code in my activity . Please take a look and i don't have any other `onDisconnect` anywhere else
Comment: It's most probably a bug in Firebase. I create a new project with only firebase code and i am still getting same issue. I raised a issue at github too, please see if you can answer https://github.com/firebase/firebase-android-sdk/issues/3248#
Comment: Raising the same problem with the same code there is unlikely to help. If you want to prove that this is a bug in the SDK (which I doubt, given that the server has no way to make up a value like that), simplify the code. For example, how about attaching the `onDisconnect` only once in the top level of `initialiseOnlineStatus`?
Comment: On GitHub you can reproduce the issue with the given code, and also noticed it's not about the time stamp it can be any random digits. With GitHub minimal code you can reproduce the code and I'm not using any other library or anything else which can effect code. I'm Having onDisconnect only once where I'm setting the values
Answer: System.currentTimeMillis() will get you the epoch time of your emulator , meaning whatever the emulator or the phone system time it will give it to you
Comment: I know about the `System.currentTimeMillis()` working. You need to read question again
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


sum of logarithms

Question: I have to solve find the value of
$$\sum_{k=1}^{n/2} k\log k$$
as a part of question.
How should I proceed on this ?
Comment: $log(1^1) + log(2^2) + log(3^3) + ... + log((n/2)^{n/2}) = log(1*4*27*...)$?
Comment: I doubt you will find a "closed form" formula. Maybe an asymptotic approximation?
Comment: @user8250: It's submission or summation.
Comment: I may be asking a silly question, but what is a "submission"?
Comment: @DJC srry :) it was a typo .... i meant sigma and i am reading more on how to use tags to write equations here....
Comment: Just checking! :)
Comment: Can I create an upper bound of it ?? I reached the same stage as @The Chaz
Comment: Just an idea if anybody could expand on it .... We can write k as n/2 in each of them .... then it would be that                       O(n/2 * log((n/2)factorial)) ..... Can anybody concise this expression more....
Answer: Got it.  The constant in Moron's answer is $C = \log A$, where $A$ is the Glaisher-Kinkelin constant.  Thus $C = \frac{1}{12} - \zeta'(-1)$.
The expression $H(n) = \prod_{k=1}^n k^k$ is called the hyperfactorial, and it has the known asymptotic expansion
$$H(n) = A e^{-n^2/4} n^{n(n+1)/2+1/12} \left(1 + \frac{1}{720n^2} - \frac{1433}{7257600n^4} + \cdots \right).$$
Taking logs and using the fact that $\log (1 + x) = O(x)$ yields an asymptotic expression for the OP's sum
$$\sum_{k=1}^n k \log k = C - \frac{n^2}{4} + \frac{n(n+1)}{2} \log n + \frac{\log n}{12} + O \left(\frac{1}{n^2}\right),$$
the same as the one Aryabhata obtained with Euler-Maclaurin summation.

Added: Finding an asymptotic formula for the hyperfactorial is Problem 9.28 in Concrete Mathematics (2nd ed.).  The answer they give uses Euler-Maclaurin, just as Aryabhata's answer does.  They also mention that a derivation of the value of $C$ is in N. G. de Bruijn's Asymptotic Methods in Analysis, $\S$3.7.
Comment: @Moron: Thanks! It's satisfying to have finally figured out what that constant is. :)
Comment: I suppose one proof of this would be to start from $\zeta'(s) = -\sum \log k/k^s$ for $Re(s) \gt 1$ and extend it for all $s$ (which can be done using Euler McLaurin I believe), similar to the Riemann Zeta function.
Comment: +1: Very nice ! :-) I am surprised the Plouffe inverter does not have this, though.
Comment: @Moron: It looks like Plouffe does have it (or a scaled version of it) after all.  The numerical estimate I was using before wasn't precise enough.
Comment: I see. I was about to suggest maybe you should add it there :-)
Comment: @Moron: That sounds like it would work.
Answer: Here is an asymptotic expression using EulerMcLaurin Summation.
$$ \sum _{k=1}^{n} k \log k = \int_{1}^{n} x \log x\ \text{d}x + (n\log n)/2 + C' + (\log n + 1)/12+ \mathcal{O}(1/n^2)$$
$$ = n^2(2 \log n - 1)/4 + (n\log n)/2 + (\log n)/12 + C + \mathcal{O}(1/n^2)$$
for some constant $C$.
Comment: But you're right that the same procedure for finding Stirling's constant ought to work here.  There's got to be a way to get this! :)
Comment: +1, although I get $C = \frac{1}{4}$, $(\log n)/12$ rather than $(\log n)/18$, and $O(\frac{1}{n^2})$.  (And I have verified this numerically.)
Comment: @MIke: You are correct. I have edited the answer. Thanks. That C=1/4 would need a proof, but that is a neat value for that constant.
Comment: @Moron: You're right to be suspicious of $C = 1/4$.  It's not correct.  The value of $C$ to six decimal places appears to be $0.248755$ - close to $1/4$ but not quite $1/4$.  I'm not sure how to prove that or get an explicit expression, though.
Comment: @Mike: Perhaps the Plouffe inverter has something. We would probably need more than 6 digits though.
Comment: I tried Plouffe, with the more precise estimate $0.24875448644$, but I didn't get anything exact.  Just so you know, this number comes from using Mathematica to find the difference between the OP's sum and your estimate for large values of $n$.
Comment: @Mike: There is an infinite series representation using the $B_{2k}$ which comes from the Euler McLaurin formula. It might be easier to use that to calculate the expression and might also lead us to a "closed" form expression. It is very similar (but not quite the same) to the series we get for $\sum \log k$ which gives us the Stirling's constant $\sqrt{2\pi}$, I believe.
Comment: I tried that, but I got $1/4 + \sum_{k=2}^{\infty} \frac{B_{2k}}{(2k)!} (2k-3)!$, which doesn't converge.  I could have made a mistake, though.
Comment: @Mike: You are right that it does not converge! I didn't actually try to work it out. Sorry about that.

sum of logarithms


Is it possible to embed a SWF in a form using swfobject 2+ in IE6+?

Question: I've been having endless problems embedding a dynamically loaded SWF into a HTML Form within IE 6,7,8 using swfobject.embedSwf.
All the proposed manual workarounds for the problem involve creating a reference to the Object DOM element from the window object. For example:
window[id] = document.getElementById(id);

Where id is the id of the swf object dom element. In my case I cannot set window[id] to the swf object id because it hasn't been created yet!
The line in swfobject that's causing the javascript errors is:
el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';

As the SWF movie sets up its Javascript external interface it tries to access window[id]. Since this doesn't exist, it fails.
If I apply the workaround mentioned above and populate window[id] with the DOM element that's being replaced by embedSwf it still fails beacuse it's trying to call Flash specific methods on a div DOM element rather than an object DOM element.
I find it amazing that this problem hasn't been fixed since Flash 8 and IE6!
Answer: i'm not sure where you're having a problem. ExternalInterface and SWFObject work in IE6/7/8 just fine. See this example (explanations for the example are here)
when you say 'embed a swf in a form', what exactly are you trying to do? if you're embedding the swf into a div, it shouldn't matter whether the div is in a form or anywhere else in the body.
here's an example of a SWF in a form
as for window[id], that's a deprecated approach and should be replaced by document.getElementById(id). a lot of old Flash tutorials/documentation say to use window[id] when working with ExternalInterface, but that advice is safe to ignore now that every major browser supports the W3C standard document.getElementbyId. This includes IE6/7/8, Firefox, Safari/Webkit, Opera, etc.
As far as the element existing before trying to find it, that's a timing issue. SWFObject embeds the SWF at domready/onload, which means you shouldn't try to invoke ExternalInterface until after the SWF has loaded.  You can do this by placing whatever code you're writing in a domready function:
swfobject.addDomLoadEvent(function (){
  //safe to execute code on your embedded SWF in here
});

SWFObject 2.2 has a new callback feature that lets you invoke a function as soon as the SWF has been embedded. Bobby Van der Sluis has an example you can 'view source' on. The SWFObject API documentation covers its usage.
hope that helps
--philip


Comparação de datas da database com data do sistema

Question: Olá!
Preciso comparar o mês de cadastro de informações presentes em uma tabela do banco de dados com o mês atual fornecido pelo sistema.
No banco de dados eu cadastro em uma coluna o número referente ao mês. Por exemplo:
No dia 16/12/2016 cadastrei um produto, na tabela consta o nome do produto, preço e número do mês. Preciso somar os valores dos produtos do mês atual, ou seja, os preços dos produtos do mês fornecidos pelo sistema através desse código:
string mes = DateTime.Now.Month.ToString();

Portanto, se no mês de dezembro cadastrei 10 produtos com preço de 10 reais preciso que o sistema compare a coluna 'mes' do banco de dados com o mês do computador, realize a soma dos valores da coluna 'preco' cuja linha seja o mês em questão.
Answer: Pelo que entendi, você quer o valor do banco para o c#, certo?
Então, segue um código ilustrando como retornar do banco o valor somado de todos os produtos do mês retornado pelo sistema.
string mes = DateTime.Now.Month.ToString();
string pesquisa = "SELECT SUM(Preco) FROM PRODUTOS WHERE MES = " + mes;
using (System.Data.IDbCommand comando = new System.Data.OleDb.OleDbCommand(pesquisa, DBconn))
{
   object resultado = comando.ExecuteScalar();
   ValorTotal.Text = Convert.ToString(resultado);
}

O valor somado será armazenado na propriedade Text do controle ValorTotal.
A forma de conexão ao banco foi apenas um exemplo.
Comment: Modifiquei de acordo com meu código e deu certo! Agradeço!


Piano - Playing the G# Key with left hand

Question: I'm only a month into using SimplyPiano and there are a few songs that have left hand combos of E and G#.
The numbers suggest I use 1-3, but I can't get my thumb up to G# unless I slide all the way to the top of the keyboard.  It's easier to just use my index finger and slide over, but that's then 2-3.  I am trying not to come up with bad finger techniques... so this is where a real teacher comes in :-)
Advice would be appreciated.  I see the G# Major chord is played with the "slide up", but surprised SimplyPiano would introduce those notes without a lesson on it.
Edit > this is an example of just one.  I could shift positions and "cheat" some, but it sounds like the "shift up" is proper, but just haven't learned it.  There aren't a ton of these, just happened to stumble on it.  Any other thoughts are appreciated.
Comment: This is a strange fingering to recommend for a beginner. Can you post the context? There might be a specific reason for it, or it might be a mistake either in the material you're looking at or your interpretation of it.
Comment: Could the figerings be back to front? Pinky=1, middle=3?
Comment: Not leaving this as an answer, because I feel like the question is more about playing the black key with your thumb, which has been answered. However, as mentioned by others, this fingering is quite strange and doesn't necessarily teach the best practices. I would suggest 1-5, 2-4, 1-2 instead.
Answer: Dont be afraid to use the entire key to play things, it is IMPOSSIBLE to stay on the edge for everything BECAUSE BLACK NOTES EXIST
If you avoid sliding into the key, you run into terrible positions like this:

Isn't that disgusting? My entire hand feels contorted and I am just begging for carpal tunnel syndrome. Instead, compare the beauty of a good hand position:

So much nicer, isn't it? Do not be afraid to slide into the piano to reach black notes with your thumb. Whatever your fingers, you cannot sacrifice the form of your hand and wrist in the process
Comment: +1 for the photos. Love photos! (The all caps bold-face is a bit much, though. Maybe just the bold?)
Comment: Thank you for the thorough information.  I had not considered carpal tunnels and pain issues yet, just speed/proficiency in moving, but this makes sense.
Answer: UPDATE: Now that the example is posted in the OP: I suggest using 5-3 for the E-G#. It will be more comfortable, and it will prepare the hand for the A-C that follows.

To play E and G# with left-hand fingers 3 and 1, the correct technique is to slide your hand toward the back end of the keys, as you're doing.
However, this is an odd fingering to use, especially for a beginner. It would be standard for the right hand, but for the left hand, 5 (on E) and 3 (on G#) would be more typical and not require a shift in hand position.
The 2-3 combination you tried might be used in a specific context that demanded it, but it would be context-specific, not a general way to play those notes.
Comment: This is where my ignorance will show.  I only "know" the C and F position.  The 5-3 you describe sounds like an E position or something, that I haven't been introduced to.  I'll be giving the slide up a shot.  Thanks!
Comment: Follow up, that 5-3 is much more comfortable and easy.  Is that a "cheat"'as a beginner?  It's technically not C or F position.  Am I being needlessly strict?  Again, this is where self-teaching has its limits.  Thanks for all the help!
Comment: @Sureshoe The 5-3 fingering is standard piano practice -- no cheat there. In general, piano finger is "whatever is most comfortable and effective for you", but using "positions" like C and F is a common technique for teaching beginners to help learn basic patterns.
Comment: That makes sense and where the real teaching is going to be needed at some point vs. just playing Guitar Hero on the piano :-)
Answer: I'd be more inclined to use 4-2 for the E and G♯, setting the hand up nicely for 3-1 on A and C.
3-1 on E and G♯ isn't ridiculous - yes you'd have to move your hand forward, but that's legitimate piano technique.   But in this context it seems clumsy.
Answer: Fingering of one particular moment depends on what comes before and after. There isn't one correct fingering. So, you need to have a rationale for your fingering choices. I did this as my first thought...

Generally you want to make fingering changes to place new fingers on adjacent keys or substitute new fingers on one key, because once a finger is down on a key it's fairly easy to place another finger on an adjacent key or make a finger substitution. By comparison, if you lift your whole hand off the keyboard, you loose the spatial point of reference of an already placed finger and it harder to hit the target keys.
The rationale: 5 1 is just a 5-finger position on a perfect fifth, then 5 3 involves crossing the thumb under and placing finger 3 adjacent to the thumb on the G# key, then 2 1 just involves placing finger 2 adjacent finger 3 on the A key. Each of those moves involves and easy, adjacent placement of fingers.
The problem I see in the SimplyPiano fingering is all of the moves involve a lift of the thumb. G to G# for the thumb isn't difficult, because it's just moving up to the next key, but it leaves you in a bad position for the next change. To get to A C you need to lift the whole hand and go up a fourth. That too may not be very difficult, but it doesn't take advantage of easier moves.
If you make moves using new fingers/adjacent keys, you don't really need to look at the keyboard.

...surprised SimplyPiano would introduce those notes without a lesson on it.

The fingering given by this software application reminds me of software determined guitar tab. Such software probably follows some general principle of numerically smallest movements. But sometimes the results just don't feel right. I think you need to assume such software will give you bad fingerings and you need to develop the judgement to make better choices.
Look for a traditional, classical piano method book that gives scale, arpeggio, and double note fingers in all keys. Study the fingers given and use them as a point of reference to figure out the fingering of passages.
Comment: It didn't occur to me the fingering might be computer generated.  It makes sense.  I might be a little less rigid because it's actually made playing some of the songs harder.


Angular - Typescript filter em array

Question: Tenho um json das cidades brasileiras.
Para obter todas as cidades do estado que exista no ARRAY idEstado com ÚNICO item, faço da seguinte forma:
<code>getCidades(idEstado: any): Observable<any> {
    return this.http.get<Cidade[]>('assets/dados/cidades.json')
      .pipe(
        map((cidades: Cidade[]) => cidades.filter(c => c.estado == idEstado))
      );
}
</code>
Este código não funciona se eu tiver mais de um estado no ARRAY idEstado.
Como fazer para que me seja retornado as cidades de todos os estados que estejam no array?
Comment: Provavelmente utilizando `map((cidades: Cidade[]) => cidades.filter(c => Array.isArray(idEstado) ? idEstado.includes(c.estado) : idEstado == c.estado))`, mas essa pergunta está longe de ser clara.
Comment: Perfeito! Era isto mesmo que eu procurava. Funcionou corretamente, muito obrigado e me desculpe pela falta de clareza na pergunta, oportunamente procurarei melhorar.
Answer: Para fins de registro e, quem sabe, ser útil a outros, segue a solução conforme resposta do user140808
<code>  getCidades(idEstado: any): Observable<any> {
    return this.http.get<Cidade[]>('assets/dados/cidades.json')
      .pipe(
        map((cidades: Cidade[]) => cidades.filter(c => Array.isArray(idEstado) ? idEstado.includes(c.estado) : idEstado == c.estado))
      );
  }
</code>
Desta forma, são retornadas todas as cidades cujos estados estejam no array idEstado.

Angular - Typescript filter em array


Create only an opening div tag using jquery

Question: Okay, so I have searched this site quite a bit and I can't seem to find the answer, so I am going to ask the same question with a better reason. I am trying to use jquery to add an opening div tag. When I try to use the after I end up with . I understand that jquery does not like to natively create tags like I want. However, here is the situation:
I have a dynamic form generator that I am using to display a form. There are several  headers I am using as section headers from within the form. I want to use the jquery accordion, and it wants to see a div element wrap the contents of the accordian frame, and it wants to see it directly after my . The problem is that the number of elements in between the opening and closing div tag is dynamic. So I can't just wrap something and be done with it. What I want to do is something like this:

Section 1

...Dynamic code section here

Section 2

I want to use jquery to end up with something like this:

Section 1

Dynamic code section here

Section 2

More dynamic code

I know that I can find elements that I know of (the h3 tags) and insert the html. The problem is that jquery won't let me. Apparently it doesn't trust me enough to balance things out on my own. Anyone have any ideas on how to get this to work??
Comment: I'm open to suggestion. If you are going to say something like that, at least point out where you think the bad design is or provide a solution if you know better.
Comment: when you hit problems like this, usually is because bad design, you should think in a redesign
Answer: Use .wrapAll()
$('h3').each(function(){
   $(this).nextUntil('h3').wrapAll(document.createElement('div'));
});

DEMO: http://jsfiddle.net/ph8D2/
Comment: Thanks! I tried that and it didn't work. Interesting though. I am not a jquery expert. Is that basically saying "start at one h3 set and go to the next h3 set and then wrap the whole thing in a div tag"? If so, it's close but not quite what I need. The h3 tags need to be outside the wrapping div. The accordian looks for the h3 tag and then looks for a sibling container to represent the panel.
Comment: Yeah, it basically selects an `h3`, goes to the next sibling, and then selects from this sibling until the next `h3`, and wraps them all in a div... Let me update my answer though, for multiple h3's.
Comment: Thanks! I updated the demo fiddle to more accurately represent what I am trying to do. When you look at it, notice that the accordian does not work. Am I missing something? http://jsfiddle.net/ph8D2/1/
Comment: Actually, I played around a little bit more and updated the fiddle again and I think I got it to work. http://jsfiddle.net/ph8D2/2/ Now to test this on my actual code....
Comment: ahren - You are awesome and you saved my bacon! I need to tweak the styling a bit, but it works awesomely!!!!!!!!
Comment: @AndrewCasey: Make sure that you understand what is happening here - from your other comments it looks like it would be great if you could rethink what everyone here said when answering your question. This answer works for you, but make sure you understand, why it does not work the way you stated in the question.
Answer: Nope, it's literally impossible to insert an opening or closing tag, thank god. It's not jquery that's preventing you, it's the DOM api. It doesn't make any sense to insert an opening tag because that's not a valid entity.
Just do something like

Section 1

and
$('.dynamic').html( .. your dynamic content ..)

Comment: Completely right. Although there were browsers that were actually able to receive HTML part-by-part and at the end construct the DOM as if these parts were passed all as one string. I am not sure, which one was it: Opera or IE.
Comment: @AndrewCasey: At the moment you will inject the HTML into the document, it must be processed by the browser. And because browser needs some object structure and forgives mistakes of web developers, it will treat your code as final and will correct it. At the end, you will have DOM elements (and you cannot have eg. half or 23% of DOM element, so you cannot just finish it later with closing tag). And jQuery is based on JavaScript - learn it first, it is important. And stop thinking on the document as HTML - for your code it is already Document Object Model.
Comment: I can't do what you suggested. The entire page is a dynamic form, and I need to integrate the accordian into the form in such a way that the different panels make up different sections of the same form.
Comment: One other thing. It may not make sense to insert an opening tag in that fraction of a second, but the closing tag will also be inserted at a later point. I'm actually trying to create balanced html here. And I thought the whole point of jquery was to be able to manipulate the DOM?? Don't get me wrong, I understand the need to create a balanced DOM, and it's exactly what I want to do. I also understand that I am not trying to do something "out of the box", so to speak. If I was, I wouldn't be asking the question.
Comment: @AndyRay: I am upvoting your answer, it is worth it.


Android Button abaixo de um ViewPager sem tamanho fixo

Question: Estou criando um layout onde preciso de um botão abaixo do ViewPager, neste layout eu também carregos abas, como na imagem abaixo:

O que ocorre é que não consigo deixar desta forma sem ser fixando o tamanho do ViewPager, segue o xml do layout.
<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.TabLayout
    android:id="@+id/tlTabs"
    app:tabGravity="fill"
    app:tabIndicatorColor="@color/orange"
    app:tabMode="fixed"
    app:tabSelectedTextColor="@color/orange"
    app:tabTextColor="@color/white"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/azulForte">
</android.support.design.widget.TabLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/vpPager"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
</android.support.v4.view.ViewPager>

<Button
    android:layout_width="wrap_content"
    android:layout_height="67dp"
    android:text="New Button"
    android:id="@+id/button"
    android:layout_gravity="center_horizontal"/>

Da forma que fiz o botão não é exibido, como posso corrigir isto? Obrigado.
EDITADO
Layout MainActivity
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/orange"
    android:id="@+id/toolbar"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:title="Drawer With Swipe Tabs" />

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:id="@+id/drawerLayout">

    <FrameLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/containerView">
    </FrameLayout>

    <android.support.design.widget.NavigationView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:id="@+id/shitstuff"
        app:itemTextColor="@color/black"
        app:menu="@menu/drawermenu"
        android:layout_marginTop="-24dp"
        />

</android.support.v4.widget.DrawerLayout>

Layout Fragment Tab
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/white"
            tools:context=".fragments.TabFragment">

<android.support.design.widget.TabLayout
    android:id="@+id/tlTabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/azulForte"
    app:tabGravity="fill"
    app:tabIndicatorColor="@color/orange"
    app:tabMode="scrollable"
    app:tabSelectedTextColor="@color/orange"
    app:tabTextColor="@color/white">
</android.support.design.widget.TabLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/vpPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</android.support.v4.view.ViewPager>

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="67dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_gravity="center_horizontal"
    android:text="New Button"/>
</RelativeLayout>

Answer: Fala Renan,
Provavelmente não está sendo exibido por que você está usando LinearLayout no seu layout da tela.
Tente alterá-lo para RelativeLayout que ele vai aparecer.
Obs: Se não for isso, é melhor você postar o código todo do seu XML.
Abraços.
Comment: Opa Leonardo, eu mudei para o RelativeLayout e o botão apareceu, porém as abas do TabLayout sumiram, eu fiz um teste mantendo RelativeLayout e removendo o botão e as abas ainda continuavam escondidas. Eu editei minha pergunta e adicionei todo o código do XML. Obrigado.
Comment: Adiciona isso aqui no seu ViewPager **android:layout_below="@id/tlTabs"** e altera o height para **wrap_content**
Comment: Funcionou perfeitamente Leonardo, muito obrigado.


Preventing AIX mount point from writing to root file system

Question: Is there a way to make the mount point unwritable? I can't write a script or anything to check, but thought there might be a way to do this via permissions. On Linux you could make it immutable. The problem is that a backup process is filling up the root file system when the mount point fails.
Comment: Why can't you write a script to make the check?  Many backup tools allow you to run pre/post backup scripts that can perform this sort of check (and abort the backup if necessary).
Comment: Its an application level backup unfortunatly. The functionality baked in and cannot be modified.
Answer: Does AIX let you mount a filesystem over an existing filesystem?  Under Linux, you could do something like this:
<code># mount -t tmpfs -o ro none /mnt/fs
</code>
So now <code>/mnt/fs</code> is a read-only filesystem:
<code># touch /mnt/fs
touch: cannot touch `/mnt/fs/foo': Read-only file system
</code>
But you can mount something over it like this:
<code># mount /dev/myvg/mylv /mnt/fs
</code>
And that filesystem is writable:
<code># touch /mnt/fs/foo
# ls /mnt/fs
foo
</code>
If the second mount fails, you're still left with a read-only filesystem.  If AIX supports this sort of overlapping mount this might do what you want.


*NgFor não está percorrendo o array no html

Question: Estou consumindo a API da Wirecard para realizar uma integração, no momento em que tento retornar todos os cartões que estão cadastrados para um cliente, eu consigo obtê-los apenas no menu console.log, quando tento percorrer este array e mostrar os seus dados no meu html, simplesmente não aparece nada. Gostaria de ajuda para ver no que estou errando.
  this.pacientesSubscription = this.pacienteProvider.buscarPacientes().subscribe(result => {
  result.filter(data => {
    if (data.uidUsuario == this.usuarioLogadoUid) {
      this.paciente = data;
      this.idUsuario = data.idMoip; //Id do usuário na plataforma moip
      this.moip.customer.getOne(data.idMoip) //Vou na api da moip e retorno o cliente que possui este id
        .then((response => {
          this.qtdCartoes = response.body.fundingInstruments.length;
          this.formasPagamento = response.body.fundingInstruments; //Retorna todas as formas de pagamento (debito, credito, etc...)
          let cartoesDeCredito: Array<any> = [];
          cartoesDeCredito = this.formasPagamento.filter(result => {
            return result.method == 'CREDIT_CARD'; //Filtro apenas os cartões de crédito
          })
          this.cartoesCredito = cartoesDeCredito.map(data => {
            return data.creditCard; //Mapeio o array de cartões de crédito e crio um array de objetos
          })
          console.log(this.cartoesCredito); //Aqui me retorna normalmente o array de objetos (no caso cartões)
        })).catch((err) => {
          console.log(err);
        })
    }
  })
})

O retorno do meu console.log é o seguinte:

Meu html é o seguinte:
<ion-content padding>
  <ion-item *ngFor="let teste of cartoesCredito">{{teste}}</ion-item>

     Nenhuma forma de pagamento cadastrada, clique abaixo para cadastrar uma
     forma de pagamento e utilizar os nossos
     serviços

</ion-content>

A minha view, não retorna nada conforme pode ser visto aqui:
Comment: Olhando melhor, talvez a sua var teste devesse ser assim: {{ teste.brand }}
Comment: Já tentou colocar o resultado na view, como texto, apenas para debug: {{ cartoesCredito | json}}
Comment: Se faço {{cartoesCredito | json}} me retorna apenas isso [].
Comment: E mesmo colocando o teste.brand ainda não aparece nada
Comment: estranho, consegue prover um pouco mais de informações da sua classe?
Comment: Coloque toda a classe do componente
Comment: Pessoal, estranhamente agora apareceu. Honestamente não sei o que era, pois é o código que uso habitualmente em todos os projetos. Mas agradeço muito a ajuda e o tempo de vocês para responder.
Answer: testei novamente aqui e agora rodando no próprio dispositivo e não no navegador. No dispositivo funciona normalmente, o único problema em questão parece ser no navegador que demorou aproximadamente uns 40 minutos para aparecerem as informações, enfim não sei o que é e o que foi. Mas de qualquer forma agora está funcionando normalmente. Obrigado a todos pela ajuda.


Android License response "Respond normally"

Question: I am implementing android license for a paid app. Test response can be set to be "Respond normally". What is the expected behavior when response is set to "Respond normally"? Do we need to set response to be "Respond normally" when our application is official published?
Answer: I believe the response specifications only apply to accounts/emails that have been entered into your "Test Accounts" list, on the publisher edit page.  When you publish your app, genuine licensed apps will receive the proper response, unless those users exist in your Test Accounts list, in which case they will receive the response that you have specified.
The Test Accounts list is for testing how your app will respond when it receives, for example, a "LICENSED" response from the server.  To test how your app will respond when it receives a response of "UNLICENSED", simply change the dropdown item to UNLICENSED, or whichever response you are trying to test.
Also be aware that the server can take a little while to register a test account, and it can also take a little while to unregister one as well.  Hope this helps.
Comment: Thanks for the answer, however, i am still not sure what response i would expect when setting to "Respond normally".
Comment: Respond normally means it will evaluate it the way it normally would.  So if you have a license, it responds with "LICENSED", if you don't, it responds with "NOT_LICENSED" etc.
Answer: For me it was because i was using the same email as of the publisher account. i.e the email address of the tester and that of the publisher account was same.
I added a new email address to tester account and used that account to install and test the application. It worked.


Create a facebook application programmatically

Question: I'm trying to programmatically create an application in Facebook. I can do that with this:
https://www.facebook.com/connect/create_app.php?api_key=[key]&name=app_name
However, there's always a popup that says "Allow [Root App] to integrate Facebook functionality for you?" ... OK.
Is it possible for the "Root App" to create the application on the user's behalf without the popup via some previous permission which they have allowed, like stream_publish ...etc or maybe a session_token or ??
Someone said I can create child apps via "admin.setAppProperties" but couldn't get it working. I've also tried "FB.Connect.createApplication" and "Facebook.createApplication" but also failed.
Can anyone help? Maybe with some sample code.
Comment: An app that makes apps. You trying to put us out of work?  :)
Comment: I would be surprised if Facebook is okay with creating applications programmatically. That's just asking for them to be spammed with apps.
Comment: Do you have the documentation for /connect/create_app.php? Couldn't find it.
Comment: @Kai Chan did you manage to get this working? I've used Facebook.createApplication but its a bit messy. What was your 'almost got a solution to my problem now'??
Comment: @Kai Chan, I'm also wondering if you came up with a solution
Comment: Interesting question for sure !
Comment: Define "failed". There are such methods and they should work
Answer: There used to be an API for this but I think it has been discontinued. You can see if you can hack it together from the information available here:
http://blog.programmableweb.com/2009/10/15/facebook-lets-you-easily-integrate-into-sites-and-widgets-with-new-create-application-api/
Answer: Child applications (I believe they called them 'fourth party applications') intentionally need user interactions to create.
Answer: The documentation for https://www.facebook.com/connect/create_app.php?api_key=[key]&name=app_name is scarce to none. Are you able to access the API key of the newly created application somehow? Or set further app settings such as site-url?
I'm thinking you would need the user's permission to view <code>/accounts</code> then monitor before/after state to detect which one was created.
Answer:
Is it possible for the "Root App" to create the application on the
  user's behalf without the popup via some previous permission which
  they have allowed, like stream_publish ...etc or maybe a session_token
  or ??

If you create a Facebook application that only pulls someone's profile information, and then you add new functionality that allows it to automatically post on people's walls; you would have to require the user to re-authenticate themselves to give you those extra permissions.
It's hard to understand what you meant by that question.


Diameter hypothesis of Cantor's Intersection Theorem on a complete metric space.

Question: Cantor's Theorem states: "Suppose that X is a non-empty complete metric space, and $C_n$ is a sequence of closed nested subsets of X whose diameters tend to zero:
$\lim_{n \rightarrow \infty} diam(C_n) = 0$
Where $diam(C_n) = sup \{d(x,y): x,y \in C_n\}$
Then the intersection of the $C_n$'s contains exactly one point:
$\cap^{\infty}_{n=1} C_n = \{x\}$."
For an assignment I have to show that the hypothesis that the diameter tends to zero is needed for the theorem by showing if $\lim_{n \rightarrow \infty} diam(C_n) \neq 0$ the intersection becomes empty.
This seems incorrect to me because intuitively if diameter of set is always non-zero then a set must contain at least two distinct points, and the intersection of nested sets which always contain at least two points is should not be empty. Right?
My suspicion is that my intuition about this is incorrect, because it's more likely that I am wrong than that the question is.
Can someone help me understand this better? Thank you for your help.
Answer: The claim should be that the intersection can be empty if this condition is dropped, not that it always will be.
Consider $X = \mathbb{N}$ with the discrete metric, and $C_n = \{n, n+1, n+2, \dots\}$.
A similar example would be $X=\mathbb{R}$ and $C_n = [n,+\infty)$.
Just because each of the sets $C_n$ contains at least two points (infinitely many, in these examples), does not mean that any one of those points has be common to all the sets, which is what would be necessary for the intersection to be nonempty.
Comment: @MatthewRiley: "Infinity" is not an element of $\mathbb{N}$.  It's true that the intersection of all the $C_n$ is the empty set, which has a diameter of zero (or maybe undefined), but each $C_n$ has diameter infinity.  So the diameter of the intersection doesn't have to equal the limit of the diameters, and you have no basis for thinking that it should.
Comment: Maybe this is a dumb question, but in your first example wouldn't $C_{\infty}$ contain only infinity and therefore have a diameter of zero, meaning that the limit of the sequence as a whole tended towards 0?
Comment: I did not know that, thank you.


Convexity properties of $ \frac{1}{2\pi} \cdot \int_{S_1(0)} \Vert x -y \Vert d \mathbb{\lambda}^1(y) $

Question: Let $S_1(0)$ be the unit sphere in $\mathbb{R}^2$. For a point $x \in B_1(0)$ define the function $f(x)$ to be $$ \frac{1}{2\pi} \cdot \int_{S_1(0)} \Vert x -y  \Vert d \mathbb{\lambda}^1(y) $$
i.e for a point $x$ we are computing the distance to every point on the circle and integrating. The function is obviously rotational symmetric and has a minimum at $0$. What can be said about convexity of this function?
I have tried to compute the function explicitly, therefore I have tried to solve the integral
$$ f(t)= \int_0^{2 \pi} \sqrt{1+t^2 - 2t \cos(x)} dx $$
for values $t \in [0,1]$. This is the value of the function at a point x=(0,t) and by symmetry therefore the value of any point with $\Vert x \Vert =t$. I have not been able to solve this integral. Does there exist an analytical solution?
Comment: There is solution but it involves elliptic integrals.
Comment: Do there exist formulas for the derivative of elliptic Integrals? If that would be true, one could try to compute the hessian of $f((x,y))=f(\Vert (x,y) \Vert)$.
Comment: There are but they involve elliptic integrals again.
Comment: Considering the answer you accepted, the question should be renamed, since you obviously did not need an analytic expression for the integral
Comment: I will rename the question shortly.
Answer: Rewriting $$1+t^2-2t\cos(x)=(1-t)^2+2t\big(1-cos(x)\big)=(1-t)^2+4t^2 \sin^2\big(\frac x 2\big)$$ we then find that $$\int \sqrt{1+t^2-2t\cos(x)}\,dx=2 (1-t)\, E\left(\frac{x}{2}|-\frac{4 t}{(1-t)^2}\right)$$ where appears the elliptic integral of the second kind.
Then $$f(t)=\int_0^{2\pi} \sqrt{1+t^2-2t\cos(x)}\,dx=4 (1-t) E\left(-\frac{4 t}{(1-t)^2}\right)$$
Comment: @Near, why do you think it's not defined? See for example for $t=0.25$ [here](http://www.wolframalpha.com/input/?i=Integrate%5BSqrt%5B1%2B0.25%5E2-2*0.25+Cos%5Bx%5D%5D,%7Bx,0,2+Pi%7D%5D)
Comment: Could you elaborate on $E\left(-\frac{4 t}{(1-t)^2}\right)$? As far as I understood from Wikipedia, you mean the Elliptic integral of the second kind. However it is not defined for negative values.
Comment: @Near. Could you tell how you thought that it is not defined ? May be some misunderstanding somewhere ?
Comment: @ClaudeLeibovici, it's probably $k^2$ vs $k$ interplay
Comment: @YuriyS. You are totally right ! Always the same story; now I remember. Thanks.
Comment: Using your formula in the answer one has $$f(t)=\int_0^{2\pi} \sqrt{1+t^2-2t\cos(x)}\,dx= (1-t) \int_0^{2\pi} \sqrt{1 + \left(\frac{2t }{1-t} \right)^2 \sin^2(x/2) } dx$$ which is not an elliptic integral of second kind, since the sign does not agree compare to $\int_0^{2\pi} \sqrt{1 - k^2 \sin^2(x/2)}$ the original definition from wiki. Therefore I do not understand what the elliptic integral of second kind with negative values is.
Comment: It is a question of notation, using $k$ or $k^2$. Have a look at http://mathworld.wolfram.com/EllipticIntegraloftheSecondKind.html
Comment: Okay so from the formula from mathworld we get $$ E(k) = \int_0^{\pi/2} \sqrt {1 - k^2 \sin^2(x)}dx = \int_0^{\pi/2} \sqrt {1 - (-k)^2 \sin^2(x)}dx = E(-k)$$ Is that correct?

However as I pointed out in my last comment one has $$ E(-k)=  E(k)= \int_0^{\pi/2} \sqrt {1 - k^2 \sin^2(x)}dx \neq \int_0^{\pi/2} \sqrt {1 + k^2 \sin^2(x)}dx $$ But the integral you computed in your answer would be of the last type.
Answer: There is no need to deal with elliptic integrals to prove the convexity of our function.
For any $z$ in the unit disk, let
$$ f(z) = \frac{1}{2\pi}\int_{S^1} \|z-x\|\,dx \tag{1}$$
the average distance from the unit circle. Quite obviously, $f(z)$ is a continuous function, hence to prove its convexity it is enough to prove its midpoint-convexity, but
$$ f(z_1)+f(z_2)\geq 2\,f\left(\frac{z_1+z_2}{2}\right) \tag{2}$$
just follows from the definition $(1)$ and the triangle inequality in the form
$$ \|a\|+\|b\|\geq 2 \left\|\frac{a+b}{2}\right\|.\tag{3}$$

As an alternative, the analytic function defined on $(-1,1)$ by
$$ g(t) = \frac{1}{2\pi}\int_{0}^{2\pi}\sqrt{1+t^2-2t\cos x}\,dx $$
has a remarkable property: it is an even function and every coefficient of the Taylor series at $t=0$ is non-negative. Convexity is a straightforward consequence.
$$ g(t) = 1+\frac{t^2}{4}+\frac{t^4}{64}+\frac{t^6}{256}+\ldots \tag{4} $$
Since $f(z)$ is a radial function, we may use $(4)$ to provide lower bounds ($\lambda=\frac{1}{2}$) for the hessian matrix eigenvalues, too.
Comment: @Near: for such a task, I think my $(4)$ is more than enough: $\lambda=\frac{1}{2}$ is a lower bound for the eigenvalues of the hessian.
Comment: By the formulation "What can be said about convexity" I meant whether the function is $\lambda$-convex, i.e. $f(z_1) + f(z_2) \geq 2 f\left(\frac{z_1 +z_2}{2} \right) + \frac{\lambda}{2} \cdot \Vert z_1 - z_2 \Vert ^2/2$ which means that the eigenvalues of the hessian are bounded below by $\lambda$.


How many Pythagorean triangles which have hypotenuse equal to $2859545$

Question: By using the trail and error, I could find these triangle
$$20572, 2859471, 2859545$$$$27056, 2859417, 2859545$$
I couldn't continue to find the others triangles  because they need more time.
Is there an easy method to find the others triangles?
Answer: $c = 2859545$ factors as $5 \times 13 \times 29 \times 37 \times 41$.  Each of these primes is congruent to $1$ mod $4$, so they factor over the Gaussian integers:
$$5 = \left( 1+2\,i \right)  \left( 1-2\,i \right) , 13 = \left( 3+2\,i
 \right)  \left( 3-2\,i \right) , 29 =  \left( 5+2\,i \right)  \left( 5-2\,
i \right) , \\37 = \left( 1+6\,i \right)  \left( 1-6\,i \right) , 41 = \left( 5+4
\,i \right)  \left( 5-4\,i \right)$$
For each of the five primes $p = (a_p + i b_p)(a_p - i b_p)$, let $f_p$ be either
$(a_p + i b_p)^2$, $(a_p + i b_p)(a_p - i b_p)$, or $(a_p - i b_p)^2$.
Then $f_1 f_2 \ldots f_5$ is a Gaussian integer $x + i y$ such that $x^2 + y^2 = c^2$.  There are $3^5 = 243$ possibilities, but we won't count the trivial case
$x = c$, $y=0$, and taking account of complex conjugation that leaves $242/2 = 121$ different solutions.
$$  \begin {array}{cccc}  \left\{ 20572,2859471 \right\} &
 \left\{ 24388,2859441 \right\} & \left\{ 27056,2859417 \right\} &
 \left\{ 54636,2859023 \right\} \\  \left\{ 78329,
2858472 \right\} & \left\{ 102705,2857700 \right\} & \left\{ 112377,
2857336 \right\} & \left\{ 151536,2855527 \right\}
\\  \left\{ 157287,2855216 \right\} & \left\{ 159951
,2855068 \right\} & \left\{ 163761,2854852 \right\} & \left\{ 184295,
2853600 \right\} \\  \left\{ 233044,2850033
 \right\} & \left\{ 241900,2849295 \right\} & \left\{ 262392,2847481
 \right\} & \left\{ 290567,2844744 \right\} \\
 \left\{ 296296,2844153 \right\} & \left\{ 311025,2842580 \right\} &
 \left\{ 335257,2839824 \right\} & \left\{ 340976,2839143 \right\}
\\  \left\{ 389455,2832900 \right\} & \left\{ 398257
,2831676 \right\} & \left\{ 412920,2829575 \right\} & \left\{ 446600,
2824455 \right\} \\  \left\{ 466908,2821169
 \right\} & \left\{ 473304,2820103 \right\} & \left\{ 478983,2819144
 \right\} & \left\{ 493580,2816625 \right\} \\
 \left\{ 517584,2812313 \right\} & \left\{ 527100,2810545 \right\} &
 \left\{ 550375,2806080 \right\} & \left\{ 574287,2801284 \right\}
\\  \left\{ 594425,2797080 \right\} & \left\{ 603889
,2795052 \right\} & \left\{ 627705,2789800 \right\} & \left\{ 642148,
2786511 \right\} \\  \left\{ 647759,2785212
 \right\} & \left\{ 654073,2783736 \right\} & \left\{ 703888,2771559
 \right\} & \left\{ 727500,2765455 \right\} \\
 \left\{ 730080,2764775 \right\} & \left\{ 774663,2752616 \right\} &
 \left\{ 777231,2751892 \right\} & \left\{ 782772,2750321 \right\}
\\  \left\{ 806200,2743545 \right\} & \left\{ 820401
,2739332 \right\} & \left\{ 852977,2729364 \right\} & \left\{ 861455,
2726700 \right\} \\  \left\{ 875568,2722201
 \right\} & \left\{ 881049,2720432 \right\} & \left\{ 907936,2711577
 \right\} & \left\{ 927420,2704975 \right\} \\
 \left\{ 946856,2698233 \right\} & \left\{ 950456,2696967 \right\} &
 \left\{ 952972,2696079 \right\} & \left\{ 1001167,2678556 \right\}
\\  \left\{ 1023975,2669920 \right\} & \left\{
1049191,2660112 \right\} & \left\{ 1074801,2649868 \right\} & \left\{
1077273,2648864 \right\} \\  \left\{ 1080807,2647424
 \right\} & \left\{ 1099825,2639580 \right\} & \left\{ 1122297,2630104
 \right\} & \left\{ 1152920,2616825 \right\} \\
 \left\{ 1171716,2608463 \right\} & \left\{ 1175196,2606897 \right\} &
 \left\{ 1193920,2598375 \right\} & \left\{ 1202708,2594319 \right\}
\\  \left\{ 1238159,2577588 \right\} & \left\{
1243348,2575089 \right\} & \left\{ 1249184,2572263 \right\} & \left\{
1264647,2564696 \right\} \\  \left\{ 1295111,2549448
 \right\} & \left\{ 1308300,2542705 \right\} & \left\{ 1319175,2537080
 \right\} & \left\{ 1337393,2527524 \right\} \\
 \left\{ 1362348,2514161 \right\} & \left\{ 1367409,2511412 \right\} &
 \left\{ 1380400,2504295 \right\} & \left\{ 1388176,2499993 \right\}
\\  \left\{ 1401708,2492431 \right\} & \left\{
1430705,2475900 \right\} & \left\{ 1451769,2463608 \right\} & \left\{
1456728,2460679 \right\} \\  \left\{ 1469455,2453100
 \right\} & \left\{ 1498575,2435420 \right\} & \left\{ 1516057,2424576
 \right\} & \left\{ 1521551,2421132 \right\} \\
 \left\{ 1564724,2393457 \right\} & \left\{ 1585080,2380025 \right\} &
 \left\{ 1587300,2378545 \right\} & \left\{ 1607528,2364921 \right\}
\\  \left\{ 1624500,2353295 \right\} & \left\{
1632456,2347783 \right\} & \left\{ 1652420,2333775 \right\} & \left\{
1664487,2325184 \right\} \\  \left\{ 1671705,2320000
 \right\} & \left\{ 1699225,2299920 \right\} & \left\{ 1711116,2291087
 \right\} & \left\{ 1715727,2287636 \right\} \\
 \left\{ 1735175,2272920 \right\} & \left\{ 1737295,2271300 \right\} &
 \left\{ 1773772,2242929 \right\} & \left\{ 1775864,2241273 \right\}
\\  \left\{ 1796784,2224537 \right\} & \left\{
1834545,2193500 \right\} & \left\{ 1843920,2185625 \right\} & \left\{
1855217,2176044 \right\} \\  \left\{ 1859596,2172303
 \right\} & \left\{ 1881009,2153788 \right\} & \left\{ 1896455,2140200
 \right\} & \left\{ 1903097,2134296 \right\} \\
 \left\{ 1914639,2123948 \right\} & \left\{ 1932176,2108007 \right\} &
 \left\{ 1939300,2101455 \right\} & \left\{ 1954368,2087449 \right\}
\\  \left\{ 1957152,2084839 \right\} & \left\{
1972100,2070705 \right\} & \left\{ 1991604,2051953 \right\} & \left\{
2011304,2032647 \right\} \\  \left\{ 2015908,2028081
 \right\} &&&\\ \end{array}
$$
Comment: Just as I said.  For example, if you choose $(1+2i)^2$, $(-3+2i)(-3-2i)$, $(5+2i)^2$, $(1+6i)^2$ and $(5-4i)(5+4i)$, the product is $2514161-1362348 i$, and this gives you the triangle $(2514161, 1362348, 2859545)$
(which is in this list with $a$ and $b$ interchanged).
Comment: this is good.Now how can I find the $121$ triangles?
Comment: How can you calculate these possibilities?
Answer: Factor $2859545 = 5 \cdot 13 \cdot 29 \cdot 37 \cdot 41$.
All these primes are of the form $4k+1$ and so can be expressed as sums of two squares in essentially one way.
You can combine the solutions for each prime into several different solutions for $2859545$ using Brahmagupta's identity.
Comment: See also http://math.stackexchange.com/q/5877/ and http://math.stackexchange.com/q/208060/.
Comment: There should be $121$, I think.
Answer: In your examples, $GCD(20572,2859471,2859545)=37$ but the other is primitive and included as the last member of this list of primitives. You can find the other hundreds of multiples of primitives by plugging in all the factors of $2859545$ into the formula and then multiplying each term by the respective cofactors.
For all valid $C$-values, there are $2^{n-1}$ matching primitive Pythagorean triples where $n$ is the number of prime factors of $C$.  There may be multiples of triple too.
$$2859545=5×13×29×37×41\quad\text{ (5 distinct prime factors)}$$
Here is how you find at least the primitive triples, using Euclid's formula.
$$f(m,k)=\quad  A=m^2-k^2\qquad B=2mk\qquad C=m^2+k^2$$
Matching side C using $F(m,k)$
\begin{equation}
C=m^2+k^2\implies k=\sqrt{C-m^2}\\
\text{for}\qquad \bigg\lfloor\frac{ 1+\sqrt{2C-1}}{2}\bigg\rfloor \le m \le \lfloor\sqrt{C-1}\rfloor
\end{equation}
The lower limit ensures $m>k$ and the upper limit ensures $k\in\mathbb{N}$.
$$C=65\implies \bigg\lfloor\frac{ 1+\sqrt{130-1}}{2}\bigg\rfloor=6 \le m \le \lfloor\sqrt{65-1}\rfloor=8\\
\land \quad m\in\{7,8\}\Rightarrow k\in\{4,1\}\\$$
$$F(7,4)=(33,56,65)\qquad \qquad F(8,1)=(63,16,65) $$
Below are $2^4=16$ triples found by this method.
$$f(1219,1172)=(112377,2857336,2859545)$$
$$f(1292,1091)=(478983,2819144,2859545)$$
$$f(1348,1021)=(774663,2752616,2859545)$$
$$f(1403,944)=(1077273,2648864,2859545)$$
$$f(1411,932)=(1122297,2630104,2859545)$$
$$f(1436,893)=(1264647,2564696,2859545)$$
$$f(1504,773)=(1664487,2325184,2859545)$$
$$f(1564,643)=(2032647,2011304,2859545)$$
$$f(1576,613)=(2108007,1932176,2859545)$$
$$f(1597,556)=(2241273,1775864,2859545)$$
$$f(1637,424)=(2499993,1388176,2859545)$$
$$f(1648,379)=(2572263,1249184,2859545)$$
$$f(1667,284)=(2698233,946856,2859545)$$
$$f(1669,272)=(2711577,907936,2859545)$$
$$f(1688,101)=(2839143,340976,2859545)$$
$$f(1691,8)=(2859417,27056,2859545)$$


Adicionar um link de URL a uma classe CSS via JS

Question: É possível adicionar um link de url à minha classe CSS via JS?
Porque não posso editar meu arquivo HTML.
Eu tenho esse CSS para mudar meu logotipo quando rola:
.she-header .logo img {
visibility: hidden;
    }

.she-header .logo {
    content:url(https://example.com/Logo2.png) !important;
    margin-left: 30px;
    height: 101px;
    width: 185px;
    }

Mas quando ele rola pra baixo eu perco o link do URL para minha home.
Alguém pode me ajudar? Tem uma maneira de fazer isso com JS?
Comment: Como assim amigo vc perde o link? Tem alguma tag `` envolta do logo? Ela tem algum ID por acaso ou alguma classe só aplicada nesse link? Não ficou claro o problema...
Answer: Não da para entender bem o que vc quer. Mas o que acredito é quer é trocar um href de um link...
Então vc pode pegar o  que vc quer pelo ID ou Classe e trocar o valor do href como no exemplo abaixo.

var a = document.querySelector("a.ouClasse");
a.href = "http://link.novo"
link
Answer: Via JQuery fica da seguinte forma:

$(document).ready(function(){
   $(".logo").attr({style: "content:url(https://example.com/Logo2.png)" });
}


How to skate backwards -- for efficiency and speed

Question: I saw quite a lot of tutorials about backward skating -- how to stop, start, turn, spin, crossover, crossunder, you name it. But no single tutorial show how to skate backwards in a "straight" line.
So my question is, assume you have to skate 1 km in a straight line, you no longer learning, it is not an edge drill or whatever, just skating. You have to be efficient (I am not looking for figure skating) -- so time is an important factor. Safety as well, in a sense, that with normal skating you have other skaters behind you (so it is not speed skating in reverse).
The most guys I saw skate in a mini-slalom fashion, they are zig-zaging backwards, without raising their skates off the ice. The trail would not look like
<code>| |
| |
| |
| |
</code>
but rather
<code>/ /
\ \
/ /
\ \
/ /
\ \
</code>
with their butt slightly waving from side to side.
I can skate the same way, but I am wondering if this should be my goal of best (efficiency) skating backwards?
I use ice-hockey skates, but I don't play hockey (and I won't be), I am looking to master ice skating perfectly for recreation, and fun.
Answer: You ideally want to be pushing your feet from an imaginary line down the centre of your body, outwards. This is pretty much the opposite of skating forwards.
The reason these people skate slalom style backwards without lifting skates up is because that way you are getting the power from both of your legs at the same time, not one and then the other.
If you want to skate backwards fast and in a straight line then you ideally want to be doing the zigzag, but keeping it tight towards the centre because the more you push outwards, the further you will go overall.
If you wish to learn start with out and in, then just keep your feet together when you do it.
Answer: No one has mentioned the "C-cut" style of backwards skating (video), which leaves tracks something like this:
<code> ||
 | \
 | /
 ||
/ |
\ |
 ||
</code>
I believe this style has greater potential for efficient backwards skating, because it eliminates side-to-side motion. It also takes advantage of weight shifts from leg to leg, giving each leg time to rest, and mimicking natural human locomotion patterns.
Comment: Martyn's answer says the zigzag is "ideal" and "gives you power from both of your legs at one time", which led me to believe that his "pushing your feet outward from an imaginary line" comment was also supporting the slalom method. ASCII art will help any who misunderstand.
Answer: You could backward outside edges if you were on figure skates. Or just one leg pulls. With proper technique it would generate the most speed.
3rd best is sculling I would say. And this one you can also do efficiently on hockey skates.
Answer: You must change edge to generate power efficiently.  This is why the tracing of the blade cannot be in a straight line.  A correct stroke starts with a push from the free leg.  There is a second push which occurs when the skating leg changes edge.  You can see this because the curvature of the tracing reverses.  This applies for forwards and backwards stroking.
In a slalom, only the second push is performed, but it is done with both feet.


Filtering Properties from Jackson JSON

Question: I am using Spring MVC Annotations to create a JSON Rest API that has methods defined like:
@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public @ResponseBody AuthenticationResponse authenticate(@RequestBody final DeviceInformation deviceInformation)
            throws AuthenticationException {
    return createAuthenticationResponse(deviceInformation, false);
}

For dealing with different client Versions I want to exclude or include properties of the serialized beans by using an Annotation like
class AuthenticationResponse {
    @InterfaceVersion(max = 2)
    String old;

    @InterfaceVersion(min = 3)
    String new;
}

So if the client calls with InterfaceVersion 2 he will not get the new property and if he calls with 3 he will not get the old property.
I already found the the Jackson library (which is used by Spring for JSON) provides Features like JsonView, JsonFilter and so on but I could not figure out where and how I have to configure these things.
Answer: I use @JsonFilter to selectively filter out properties on the same object, Spring didn't (and still doesn't?) support this at the time, so I registered a custom MappingJackson2HttpMessageConverter which inspects the return type, and if it is a filter wrapper type, I take the filter out and apply it.
public class JsonFilterAwareMappingJackson2HttpMessageConverter extends
    MappingJackson2HttpMessageConverter {

private boolean prefixJson = false;

@Override
public void setPrefixJson(boolean prefixJson) {
    this.prefixJson = prefixJson;
    super.setPrefixJson(prefixJson);
}

@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
        throws IOException, HttpMessageNotReadableException {

    JavaType javaType = getJavaType(clazz);
    try {
        return this.getObjectMapper().readValue(inputMessage.getBody(), javaType);
    }
    catch (IOException ex) {
        logger.error("Could not read JSON: " + ex.getMessage());
        throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
    }

}

@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {
    JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
    ObjectMapper objectMapper = getObjectMapper();
    JsonGenerator jsonGenerator =
            objectMapper.getJsonFactory().createJsonGenerator(outputMessage.getBody(), encoding);

    // A workaround for JsonGenerators not applying serialization features
    // https://github.com/FasterXML/jackson-databind/issues/12
    if (objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
        jsonGenerator.useDefaultPrettyPrinter();
    }

    try {
        if (this.prefixJson) {
            jsonGenerator.writeRaw("{} && ");
        }

        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        if (object instanceof FilterAppliedJsonObject) {
            FilterAppliedJsonObject viewObject = FilterAppliedJsonObject.class.cast(object);
            objectMapper.setFilters(viewObject.getFilters());
            objectMapper.writeValue(jsonGenerator, viewObject.getObject());
        } else if (object == null) {
            jsonGenerator.writeNull();

        } else {
            objectMapper.writeValue(jsonGenerator, object);
        }
    }
    catch (JsonProcessingException ex) {
        logger.error("Could not write JSON: " + ex.getMessage());
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
}

}

I use java @config instead of xml configuration as much as I can, so I do:
@Override
public void configureMessageConverters(
        List<HttpMessageConverter<?>> converters) {
    converters.add(new JsonFilterAwareMappingJackson2HttpMessageConverter());
    super.configureMessageConverters(converters);
}

I think this post will help you if you want to register this kind of conversion in xml

Filtering Properties from Jackson JSON


How can I set a certain cck value to selected nodes using View Bulk Operation (VBO)?

Question: I have a text type cck filed (checkbox widget) allowing multiple values.
I need to add one of the values of this field to selected nodes using VBO.
I suppose Modify node fields (views_bulk_operations_fields_action) is the way to go but how can I exactly do it?
I need to add just one value but keeping the existing values the nodes currently have.
Answer: Create a view, and add Bulk Operation to the field.
In the configuration field: Bulk Operations: Content
  Bulk Operations -> Selected Operations,  you can choose the operations you would like to perform in bulk.
  Once you done, save the view, and go to the view page.

Select the nodes you would like to edit
Choose an operation, click Execute
Select the field you like to edit
You got the rest.
Comment: Thanks.Is there way to do it without overriding the existing values? I also edited the description.
Comment: aw, I see. So you wanna select additional values to selected nodes. Sry, I'm still kinda new. I didn't find an option in the settings that meets your need.
Comment: I guess you can try directly manipulate the database if you wanna just add one more value to all the nodes.
Comment: They said it's supposed to provide an option that allows you to prevent the override, but I don't see it anywhere. Here's the [link](http://drupal.org/node/1105494)


Get user input from input field in react similar to getElementById in react native using props

Question: I am doing a loan calculation app and i run into the trouble since i am new to react native and previously i have been manipulating the DOM using querySelector or getElementById functions. However this does not work in react, and i am using state to store the value from the user, but i just can't seem to get it right, What am i doing wrong?
I've inserted the calculation element that is later rendered in app.js. All elements are showing up with no error, but the problem is to get user input data and then be able to use that data and do calculations.

Here is my Class

class LanKalkylElement extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        loanAmount: 20000,
        loanInterest: 2.5,
        loanYear: 10,
    };
  }

  changeAmount(loanAmount) {
    this.setState(() => {
      return {
        loanAmount: parseFloat(loanAmount),
      };
    });
  }

  changeInterest(loanInterest) {
    this.setState(() => {
      return {
        loanInterest: parseFloat(loanInterest),
      };
    });
  }

  changeYear(loanYear) {
    this.setState(() => {
      return {
        loanYear: parseFloat(loanYear),
      };
    });
  }

calcButton() {
    Alert.alert(this.props.loanAmount);
}

buttonHomeFunc() {
    this.props.navigation.navigate('Start');
}

render() {
    const {loanAmount, loanInterest, loanYear} = this.state;
    return(
        <View  style={styles.contentStyle}>

            <Text style={styles.text}> Lånebelopp </Text>
            <TextInput  style={styles.numericInput}
                        onBlur={Keyboard.dismiss}
                        keyboardType={'numeric'}
                        value={loanAmount}
                        onValueChange={this.changeAmount.bind(this)} />

            <Text style={styles.text}> Ränta </Text>
            <TextInput  style={styles.numericInput}
                        onBlur={Keyboard.dismiss}
                        keyboardType={'numeric'}
                        value={loanInterest}
                        onValueChange={this.changeInterest.bind(this)} />

            <Text style={styles.text}> Antal år: {String(loanYear)}</Text>
            <Slider step={1}
                    maximumValue={15}
                    value={loanYear}
                    onValueChange={this.changeYear.bind(this)} />

            <Button title='Kalkylera' onPress={() => this.calcButton()}/>
            <Text style={styles.textResult}>Total summa att återbetala:</Text>
            <Text style={styles.textResult}>varav räntekostnad:</Text>
            <Button title='Tillbaka' onPress={() => this.buttonHomeFunc()}/>

        </View>
    )
}
}
export default withNavigation(LanKalkylElement);

Comment: Sorry what's the issue exactly?
Answer: When a user changes a value in a text input, onValueChange is called. You have bound this prop to functions that modify the state for this component.
This means the value in the text input will always match the value in the state. Therefore, if you need to access the value in a text input you would simply retrieve it from the state, like this:
const loanAmount = this.state.loanAmount;
doSomethingWithLoanAmount(loanAmount);

Comment: Thanks for putting it in a simple context, managed to solve it with your input :)


What is a scale consisting of Root, m2, m3, P4, d5, M6, M7 called?

Question: Root, m2, m3, P4, d5, M6, M7
G, A flat, B flat,  C, D flat,  E, F#
Comment: Closest I could find was G dorian b2 or "Javanese scale".. not sure if the F# fits though. Its the second mode of the melodic minor. http://www.scales-chords.com/fscale_res_en.php?rn1=G&rn2=G%23%2FAb&rn3=A%23%2FBb&rn4=C&rn5=C%23%2FDb&rn6=E&rn7=F%23%2FGb&rn8=&rn9=&normal=1&greek=1&greekalt=1&other=1&etnic=1&c1=&t1=&c2=&t2=&c3=&t3=
Answer: You can ask WolframAlpha to identify scales for you.
When we ask it about your scale, it tells us that the scale is an F harmonic Neapolitan minor scale. Unfortunately, it doesn't suggest any scales centered around G (except the chromatic scale, but that contains every note).
Comment: I doubt it can be an F harmonic Neapolitan minor scale if the scale doesn't even contain an F! (Maybe the OP changed the question in the meantime ...)
Comment: No, you're right. I think WolframAlpha counts all scales that contain the requested notes, even if they include other notes.
Comment: But even then it's doesn't work out because F Neapolitan minor has no G. I guess WolframAlpha is better at math than at music ... :)
Comment: WolframAlpha can handle quite a few queries about music. Here's a list of examples: http://www.wolframalpha.com/examples/Music.html
Answer: The closest scale I've found was the Neapolitan Major Scale, but the fifth is perfect instead of diminished. There is a possibility that this scale is unnamed because this combination does not come up too much in music. If you really wanted, you could probably call that scale Neapolitan Major b5 since it is only one note off.
Comment: Wound't it be a Neapolitan minor scale, since the 3rd is flat? And could we make it a Neapolitan harmonic minor, since the 7th is raised?
Comment: @Kevin No since the Major Neapolitan scale has `root, m2, m3, P4, P5, M6, M7` and the Minor has `root, m2, m3, P4, P5, m6, M7`.
Answer: I'm not sure if it has a name, but from the aug 2nd between Db and E, it clearly isn't a diatonic scale. However, the m2 and dim5 do suggest a similarity to the Locrian Mode. In fact, the only difference to the Locrian mode is the raised 6th and 7th scale degrees. This is similar to the raised 6th and 7th scale degrees in the (ascending) melodic minor, so perhaps this is some form of Melodic Locrian scale? (And yes, that is quite the oxymoron).
Googling for that term, I found this list of heptatonic (7-note) scales. Using it's interval-based notation, your scale translates as "013569E" (T and E stand for Ten and Eleven, respectively), which it indeed lists as a Melodic Locrian.
DISCLAIMER: That page says that it uses an algorithm to assign names to scales where needed:

an algorithm attempts to give a name for each viable mode.

so this may not be a standard terminology.
EDIT: Your scale also shows up on this huge list of heptatonic scales, at position #132. It isn't given a name. Given that this scale doesn't seem to have a proper name, I think either Locrian #6 #7 or Dom's suggested Neapolitan Major b5 would be an adequate description.


Dados não estão sendo mostrados na view

Question: Estou tentando renderizar alguns dados em uma tabela, usando VueJS. Estou fazendo uma requisição com o axios da seguinte maneira:
export default {
data() {
     return {
         movimentos: []
     };
},
mounted() {
        axios.get('urlDaAPIAqui/movimento')
        .then((response) => {
            console.log(response.data)
            this.movimentos = response.data
        })
    }
}

Os dados estão vindo em um Array, mas estou com problemas para renderizar na tabela:

                Código
                Descrição
                Tipo
                Valor

                    {{ movimento.mov_codigo }}
                    {{  }}
                    {{  }}
                    {{  }}

Array retornado:

Os dados retornados da requisição são mov_codigo, mov_descricao, mov_tipo e mov_valor, já tentei utilizar todos dentro dos td's e não funcionou.
Resposta do Postman:
{
    "movimento": [
        {
            "mov_codigo": "m01",
            "cta_codigo": 1,
            "mov_tipo": "D",
            "mov_descricao": "Combustivel",
            "mov_valor": 154.56
        },

Espero que alguém possa me ajudar, obrigado desde já.
Comment: Já tentou dar um **push** no movimentos invés de atribuir o valor do response?
Comment: tipo this.movimentos.push(response.data) ?
Comment: Ahan, Isso mesmo.
Comment: Tentei agora e não funcionou, no meu console.log a resposta é essa: {error: false, data: Array(12)} Um array com 12 itens.
Comment: Então tem algum problema com o response. Posta o array que é retornado aí na pergunta.
Comment: Vou postar uma foto de como ele se parece porque fica ruim de pegar no console.log.
Comment: Cara ta meio estranho isso aí, se abrir o mov_codigo tem o que, dentro desses parenteses?
Comment: Cara abre esse response aí inteiro pra gente analisar, to achando que o response não é um array não.
Comment: @LeAndrade abri no postman, parece que é um objeto, e dentro tem um Array. Vou botar um exemplo.
Comment: Então, foi o que suspeitei, é um array de objetos, aí já muda tudo!
Comment: Hmmm, pois é. Alguma sugestão pra iterar?
Comment: Resolvi aqui, passei response.data.movimento e funcionou, muito obrigado de qualquer forma pessoal!
Answer: Problema resolvido adicionando o response.data.movimento à requisição no axios:
axios.get('https://projeto-bolsa.herokuapp.com/movimento')
            .then((response) => {
                console.log(response.data.movimento)
                this.movimentos = response.data.movimento
            })
            .catch(error => {
                console.log(error)
            })

Dados não estão sendo mostrados na view


The set of all real functions defined on [0,1] has cardinal number $2^c$

Question: Prove that the set of all real functions defined on the closed unit interval [0,1] has cardinal number $2^c$.
it is easy to see that there exists as many as such functions i.e. the characteristic functions but I cannot prove the exact cardinality. so comments will be helpful
Comment: Any function can be identified with its graph, so the cardinality is at most that of the power set of $[0,1]\times\mathbb R$, i.e. $2^c$
Comment: Use the [fact that $\mathfrak c^\mathfrak c=2^\mathfrak c$](http://math.stackexchange.com/questions/57389/how-to-prove-cardinality-equality-mathfrak-c-mathfrak-c-2-mathfrak-c) and $[0,1]\sim \Bbb R$.
Comment: @SHIBASHIS Then just open the link above.
Comment: Just below my comment above it says 'Trivial answer converted to comment'. Can anyone else see that?
Comment: @AsafKaragila Thanks. It disappeared to me too as soon as I posted my question.
Comment: it is true that $c^c=2^c$, but I want to prove this @Git Gud
Answer: HINT: Use the fact that $|A^B|=|A|^{|B|}$, and show that $|\Bbb{R^R}|=2^{|\Bbb R|}$.
Answer: To expand on Etienne's comment, we have the following argument:
We have an injection from $\mathcal P([0,1])$ to the set of real functions on $[0,1]$ (which I will call $S$ for convenience) since each subset of $[0,1]$ can be mapped to a unique corresponding characteristic function.
On the other hand, we have an injection from $S$ to $\mathcal P([0,1]\times \mathbb R)$ since each real function in $S$ can be mapped to its unique graph in $[0,1]\times\mathbb R$.
From there, we have only to show that $\left|[0,1]\right|=\left|[0,1]\times\mathbb R\right|$
With the above, we have
$$
\left|\mathcal P([0,1])\right|\leq \left| S\right| \leq \left|\mathcal P([0,1]\times \mathbb R) \right|=\left|\mathcal P([0,1]) \right|
$$
Thus, $\mathcal P([0,1])$ and $S$ have equal cardinalities.


Como formatar o CPF corretamente em Python?

Question: Eu tenho o seguinte código:
test = input ("CPF: ")

Quando o digitado o CPF fica:
12345678900

Mas quando eu retornar esse input ele volte:
123.456.789-00

Como que eu faço isso em Python?
Comment: Para nada precisa criar classe. Nada. Classe é algo que pode ser útil em casos específicos apenas por uma questão de organização de código, mas elas são sempre opcionais. Sempre.
Comment: Veja https://wiki.python.org.br/Cpf , é tranquilo aplicar a mask
Comment: é só pegar os grupos de números e concatenar com a pontuação.
Comment: Ah! Pra esse caso eu tenho que criar uma classe só para o CPF.
Answer: Deve ser incluído um teste se o CPF possui 11 dígitos e preencher com zeros a esquerda se forem menos dígitos, desta forma a formatação fica correta para CPFs que começam com zero
teste = input("CPF: ") # 12345678900
if len(teste) < 11:
    teste = teste.zfill(11)
cpf = '{}.{}.{}-{}'.format(teste[:3], teste[3:6], teste[6:9], teste[9:])
print(cpf) # 123.456.789-00

Comment: Refatorando essa solução chegamos em
```cpf = '{}{}{}.{}{}{}.{}{}{}-{}{}'.format(*cpf)```
Answer: Se for mesmo essa formatação sempre, então concordo com o @Maniero em comentário, não precisa de classe para isso de todo, podes fazer assim:
teste = input("CPF: ") # 12345678900
cpf = '{}.{}.{}-{}'.format(teste[:3], teste[3:6], teste[6:9], teste[9:])
print(cpf) # 123.456.789-00

DEMONSTRAÇÃO
Answer: É simples assim:
test = input("CPF: ")
cpf = test[:3] + "." + test[3:6] + "." + test[6:9] + "-" + test[9:]
print(cpf)

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: @SandsonCosta nunca cai de amores por classes. Só as use quando dominar muito bem o procedural, quando entender **muito** sobre OOP e quando for realmente útil. O pessoa faz tudo assim porque caem em martketing. Fazem sem saber porque estão fazendo. Nunca faça nada que não sabe porque está fazendo, porque é útil e benéfico. O arroz com feijão resolve melhor a maioria das coisas. O que não quer dizer que não tenha que evoluir sempre.
Comment: Hehe, exatamente o mesmo
Comment: Não tem como inventar
Comment: Sim, bigown e Miguel! Pra mim essa é a forma mais simples. Já que eu estou aprendendo a linguagem agora.

O método de criar uma classe que o Antharis passou já acho mais evoluído pra mim.

Essa concatenação em Python é muito simples! Pelo amor de Deus! Python é bom demais!

Valeu galera pelas dicas! Trabalho do tamanho do mundo que o professor passou.
Comment: Exato, de acordo
Comment: @Miguel não apaga não
Comment: Era só para não haver duas iguais, mas vou usar format na minha para ficar diferente @bigown, obgado
Answer: Se desejas utilizar f-String para formatar a saída do CPF, pode utilizar o seguinte algoritmo...
cpf = input('Digite o CPF: ')
if len(cpf) < 11:
    cpf = cpf.zfill(11)
print(f'{cpf[:3]}.{cpf[3:6]}.{cpf[6:9]}-{cpf[9:]}')

Veja aqui o funcionamento do algoritmo.
Answer: O código abaixo aceita texto e número como entrada:
import re
def format_cpf(cpf):
    cpf = "{:0>11}".format(int(cpf))
    return re.sub("(\d{3})(\d{3})(\d{3})(\d{2})",
                  "\\1.\\2.\\3-\\4",
                  cpf)

format_cpf("123")

'000.000.001-23'

Answer: Olá, há várias formas de se fazer isso. Mas irei te passar uma que me ajudou a pensar mais fora da caixa!
cpf = (input ("CPF: "))

def formatcpf(cpf):
    vezes = 0
    novo = ""
    for quantidade in range(11):
        numero = cpf[quantidade]
        novo += numero
        vezes += 1
        if(quantidade == 8):
            novo += "-"
            vezes -= 3
        if(vezes == 3):
            novo += "."
            vezes -= 3
    return novo

print(formatcpf(cpf))

Explicação: Primeiro abri uma input que irá pegar os números de cpf que o usuário digitar, depois criei 2 variáveis: "vezes" -> que irá salvar a quantidade de vezes que o segundo loop for passado; "novo" -> que irá salvar o cpf já formatado. Criei um loop que irá ser repetido 11 vezes, que é a quantidade de números de um cpf. Dentro desse loop abri a variável "numero" que será responsável por salvar um número de cada vez do cpf temporariamente, a cada repetição 1 número de CPF é adicionado na variável novo e é somado +1 número na variável "vezes".
Posteriormente tem uma condição que será responsável por adicionar o traço do CPF na variável "novo", ela faz isso caso o número de repetições do laço seja igual a 8, decidi fazer isso pois antes dos últimos 2 números do cpf há um traço. Depois disso essa condição subtrai -3 vezes da variável "vezes". (Não se engane, pois o loop na verdade foi repetido 9 vezes, pois o range começa do 0)
A última condição é responsável por adicionar os pontos do cpf, caso o número de vezes seja igual a 3 ele irá adicionar 1 ponto na variável "novo" e subtrair -3 vezes da variável "vezes". Após isso adicionei um "return" identado antes de todos os loops, que irá ser responsável por entregar o resultado final ao usuário que será possível ser printado.
A lógica é que a cada 3 números seja adicionado um ponto, limitado a 3 vezes e, após 9 números seja adicionado um traço que é limitado a 1 vez.


Can the overlay be used as a popup?

Question: In Drupal 6 there was the Modal Frame API which made it to Drupal 7 core. However, I'm not sure how leverage the Overlay independent of being an administration screen. Is there any information about this?
Answer: Well, actually yes - overlay might be used too if needed. I have just done a quick write-up on this: http://zgadzaj.com/how-to-open-standard-content-pages-in-drupal-7s-administrative-overlay
Answer: No.
However, core also contains jQuery UI Dialog, so you can use that (Views and Media both use it)
Comment: Nothing especial about using it in Drupal 7, D7 just provides you the files, you do everything else yourself, like in every tutorial.
Comment: Are there any decent tutorials on how to use jQuery UI Dialog with Drupal 7?
Comment: See drupal_add_library() -- you should use that function to add the resources needed by the jQuery UI Dialog (or any other jQuery UI components) to the current page.
Answer: This tutorial might help: How to Add a jQuery UI Dialog to Drupal 7. The Simple Dialog module might prove useful too.

Can the overlay be used as a popup?


How do I ignore all hidden properties of class being inherited using reflection?

Question: Im having an issue where I need to get all properties from an object, then sort through the properties and send the values of certain properties to another service. Here is an example of the code:
public class Class1
{
    public string A { get; set; }
    public bool B  { get; set; }
}

public class Class2 : Class1
{
    public new bool? B { get; set; }
    public bool C { get; set; }
}

I need to get all the properties of Class2, however when using Class2.GetType().GetProperties(), the result contains B from Class2 AND Class1. This causes my issue as when looping through each property I am sending B twice, one with the default value of false since it was never set, then the other with the proper value that was set by my service. I need the result to contain B from Class2, A from Class1, and C from Class2 but ignore B from Class1 since it has been hidden with the new keyword.
I have tried looking through the binding flags I can use, but it has not helped. The closest flag I can find is the BindingFlags.DeclaredOnly flag, but that excludes A from Class1, so it will not work for me.
How would I go about ignoring the original property if it has been hidden?
Comment: Can you show us what have you tried so far?
Comment: Why do you need a property that hides another one? It isn't really a good practice.
Comment: Are you only interested in getting the base class's members? If class2 had a bool C would you want that as well?
Answer: You could use a LINQ query to filter out the hidden properties.
var allProps = typeof(Class2).GetProperties(
        BindingFlags.Instance | BindingFlags.Public
);

var thePropsYouWant =
        from p in allProps
        group p by p.Name into g
        select g.OrderByDescending(t => t.DeclaringType == typeof(Class2)).First();

See it running here: https://dotnetfiddle.net/V5sGIs
Comment: This (after you fix compilation error) will return you only one property (from class Class2). It looks like OP wants an `A` property from Class1 and B property from Class2
Comment: your code won't compile and seems won't work properly. did you test it?
Comment: Hmm, I missed that OP wants most properties from Class1.
Comment: @AleksAndreev is correct, I cannot use that binding flag as it would exclude A from Class1. Also this is just example code to get the concept across, did not test nor compile it. Not sure if what im asking is even possible, just spent a few days looking and thought id post here as a last stand
Comment: I fixed my code to actually compile and "work". Will delete this answer and ponder a bit more.
Comment: Ok, how's this?
Comment: This works perfectly! Just converted the linq to a lamba (just because I like how it looks) and boom, exactly what I needed. I tried both solutions and they both worked, guess I just need to think a little harder. Either way thanks so much!
Answer: If I understand you right you need all properties from Class2 and all properties from Class1 that not redefined in Class2
You can achive this with two calls to GetProperties: first select all defined in Class2 then visit type of Class1 and add any that missing
var type = typeof(Class2);
var list = new List<PropertyInfo>();
list.AddRange(type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly));

var baseType = type.BaseType;
if (baseType != null)
{
    foreach (var propertyInfo in baseType.GetProperties())
    {
        if (list.All(p => p.Name != propertyInfo.Name))
            list.Add(propertyInfo);
    }
}

If you print that list
foreach (var propertyInfo in list)
    Console.WriteLine($"From {propertyInfo.DeclaringType} > '{propertyInfo.Name}':{propertyInfo.PropertyType}");

You will see something like:

From Class2 > 'B':System.Nullable`1[System.Boolean]
  From Class1 > 'A':System.String
Answer: A simple LINQ based solution which works in a generic way for all class hierarchies:
   var propertiesWithoutHiddenOnes = GetProperties(objectToUpdate.GetType())
            .GroupBy(prop => prop.Name)
            .Select(group => group.Aggregate(
                     (mostSpecificProp, other) => mostSpecificProp.DeclaringType.IsSubclassOf(other.DeclaringType) ? mostSpecificProp : other))


Calculate $\operatorname{Ext}(\mathbb{Z}/n,\mathbb{Z}/m)$ for $n,m \geq 2$.

Question: I can easily find that a free presentation of $\mathbb{Z}/n$ is $\mathbb{Z}$ with $p:\mathbb{Z}\rightarrow\mathbb{Z}/n$ given by the quotient map. And obviously the kernel of this is $\ker(p)=n\mathbb{Z}$. Therefore we have a short exact sequence,
$$0\rightarrow n\mathbb{Z}\xrightarrow{i}\mathbb{Z}\xrightarrow{p}\mathbb{Z}/n\rightarrow 0$$
where $i$ is the inclusion. This gives us the exact sequence,
$$0\rightarrow\operatorname{Hom}(\mathbb{Z}/n,\mathbb{Z}/m)\xrightarrow{p^*}\operatorname{Hom}(\mathbb{Z},\mathbb{Z}/m)\xrightarrow{i^*}\operatorname{Hom}(n\mathbb{Z},\mathbb{Z}/m)$$
And we can define $\operatorname{Ext}(\mathbb{Z}/n,\mathbb{Z}/m)=\operatorname{Hom}(n\mathbb{Z},\mathbb{Z}/m)/\text{im}(i^*)$.

Does the above make sense, is this the right way to approach the problem?
If so, what is $\operatorname{Hom}(n\mathbb{Z},\mathbb{Z}/m)$ and what is the image of $i^*$?
Answer: It's better to consider $0\to\mathbb{Z}\xrightarrow{\mu_n}\mathbb{Z}\xrightarrow{p}\mathbb{Z}/n\mathbb{Z}\to 0$, where $\mu_n$ is the multiplication by $n$, because $\mu_n^*$ is again multiplication by $n$. Thus you get
$$
0\to
\operatorname{Hom}(\mathbb{Z}/n\mathbb{Z},\mathbb{Z}/m\mathbb{Z})
\xrightarrow{p^*}
\operatorname{Hom}(\mathbb{Z},\mathbb{Z}/m\mathbb{Z})
\xrightarrow{\mu_n}
\operatorname{Hom}(\mathbb{Z},\mathbb{Z}/m\mathbb{Z})
$$
Now you know that $\operatorname{Hom}(\mathbb{Z},\mathbb{Z}/m\mathbb{Z})\cong\mathbb{Z}/m\mathbb{Z}$ in a "canonical" way so what you need to compute the image of
$$
\mu_n\colon\mathbb{Z}/m\mathbb{Z}\to\mathbb{Z}/m\mathbb{Z}
$$
which is $(n\mathbb{Z}+m\mathbb{Z})/m\mathbb{Z}=d\mathbb{Z}/m\mathbb{Z}$, where $d=\gcd(m,n)$. Finally, $\operatorname{Ext}(\mathbb{Z}/n\mathbb{Z},\mathbb{Z}/m\mathbb{Z})\cong\mathbb{Z}/d\mathbb{Z}$.
Comment: Thanks for your response. I understand your method, but I don't understand why this gives Ext$(\mathbb{Z}/n,\mathbb{Z}/m)$. In my definition, we find any free presentation $p:F\rightarrow \mathbb{Z}/n$ and set $K=\ker(p)$. We then use the short exact sequence $0\rightarrow K\xrightarrow{i} F\xrightarrow{p} \mathbb{Z}/n\rightarrow 0$ to induce an exact sequence on Hom$(-,\mathbb{Z}/m)$. We define Ext$(\mathbb{Z}/n,\mathbb{Z}/m)=\operatorname{Hom}(K,\mathbb{Z}/m)/\operatorname{im}(i^*)$ as above. Am I using an incorrect definition or is your technique equivalent to this and I'm not seeing it?
Comment: @sam10269 Didn't I use a free presentation?
Comment: You have $K=\mathbb{Z}$, but if $\ker(p)=\mathbb{Z}$ then $p:\mathbb{Z}\rightarrow\mathbb{Z}/n$ would not surject, so wouldn't be a free presentation. Or is the $K=\ker(p)$ not necessary?
Comment: @sam10269 The map $\mu_n$ is injective and its image is $n\mathbb{Z}$, so the cokernel is $\mathbb{Z}/n\mathbb{Z}$.
Answer: Actually, its more generally true that
$${\rm Ext}(\mathbb{Z}/n\mathbb{Z},A)\cong A/nA$$
for any abelian group $A$. Here is the proof (essentially the generalization of @egreg's argument)
Consider the resolution $\mathbb{Z}\overset{\times n}{\to}\mathbb{Z}\to \mathbb{Z}/n$. Apply $\hom(-,A)$ to get the sequence
$$0\to \hom(\mathbb{Z},A)\overset{(\times n)^*}{\to} \hom(\mathbb{Z},A)\to 0\to ...$$
But $\hom(\mathbb{Z},A)\cong A$, since a homomorphism $\varphi:\mathbb{Z}\to A$ is uniquely determined by where it sends $1\in \mathbb{Z}$. The induced map $(\times n)^*$ sends an element $a\in A$ to $na\in A$. Hence,
$${\rm Ext}(\mathbb{Z}/n\mathbb{Z},A)\cong A/nA\;.$$
Applying that to $A=\mathbb{Z}/m\mathbb{Z}$, we get $\mathbb{Z}/\gcd(n,m)\mathbb{Z}$.


If statement confusion, what does [-1] mean?

Question: Here's the code I have confusion with
from tkinter import *
root = Tk()
root.geometry("100x200")

def changeOne():
    if B.config('text')[-1] == "ITE 003":
        B.config(text="Hello", fg="red")
    else:
        B.config(text="ITE 003", fg ="green")

def changeTwo():
    if label.config('text')[-1] == "Green Text":
        B2.config(fg ="red")
        label.config(text ="Red Text", fg = "red")
    else:
        B2.config(fg ="green")
        label.config(text ="Green Text", fg = "green")

B = Button(root, text = "Hello", fg="red", command=changeOne)

B2 = Button(root, text = "Click Me", fg="red", command=changeTwo)

label = Label(root, text ="Red Text", fg = "red")

B.place(x = 10,y = 10)
B2.place(x = 10, y = 40)
label.place(x = 10, y = 70)
root.mainloop()

The problem is with this part of the if condition:
if B.config('text')[-1] == "ITE 003":, the [-1]. I really don't understand how the [-1] helps retrieve the actual button's text value, why does it need the [-1]? Is it like an array thing?
Comment: It's an array thing.  `myarray[-1]`  will access the last element of `myarray` even if I don't know it's size
Comment: https://sopython.com/wiki/What_tutorial_should_I_read%3F
Answer: When you want to access the element of the list starting from the rightmost end, you can refer it using negative index values beginning from -1. Refer to sample examples mentioned below.
>>> li = [1,2,3,4]
>>> li[1]
2
>>> li[0]
1
>>> li[-1]
4
>>> li[-2]
3

Comment: I fully understand now, thanks so much!
Comment: Hey thanks for answering!

But does that mean the B.config('text') is an array? And the value for 'text' is at the right most end of its array? And if I want to get the value of different config options I would always have to use [-1]?
Comment: @Orenjie `B` is an object of type Button. When the method `config` is called with the parameter 'text', it returns a list of values. Now, from those returned list values, you know that the value you require is present at the last index of the list. But, you don't want to waste time calculating the length of the list and then check for the last value. To make things easier, you use negative indexing. If you want the value of different config option, you'll have to use either the same , or different index value.
Comment: Happy learning @Orenjie!