A regular curve on regular surface in $ \mathbb R^3 $ being of constant tangent length

Question: I was given this in diff. geometry on which I am stuck:

Let $ S \subset \mathbb R^3 $ be a regular orientable surface in $ \mathbb R^3 $ such that on it we define the regular curve $ \gamma : I \to S $ a regular curve on the surface S and we define the following positive basis for $ \mathbb R^3 $ as $ \{ T(t) = \gamma ' (t) \space \space ; \space \space N(t) = N(\gamma(t)) \space \space ; \space \space V(t) = N(t) \times T(t)  \} $ and we are to show there exists smooth functions on the curve a,b,c such that:
$ T' = aV+bN $
$ V' = -aT+cN $
$ N' = -bT-cV $

I know the approach is that all three basis elements are smooth and therefore differentiable and the vectors $ T' ; V' ; N' $ are in $\mathbb R^3 $ and therefore are linear combinations of the given basis and therefore I can write for the first one $ T' = aV+bN+dT $ taking inner product with the tangent T and using orthogonality we obtain $ \langle {T', T} \rangle = d \langle {T, T} \rangle $ and because of regularity I know the tangent never vanishes therefore for $ d=0 $ as desired I need to have $ \langle {T', T} \rangle = 0 $ which is equivalent to saying $ ||T|| = const $ which I am not sure if it holds with the given data I was given as I know I forgot nothing and typed it as it was given to me and you see where my block comes from, I certainly appreciate any helper's opinion on this, thanks
Answer: Review how the Frenet frame works. Any time you have a smoothly-varying orthonormal basis $e_1,e_2,e_3$ at each point of the curve, you're going to have $e_i'$ orthogonal to $e_i$ (by the argument you gave) and $\langle e_i',e_j\rangle  = -\langle e_j',e_i\rangle$ (by the same argument).
Comment: Yes, without constant length it won't be true. $T'$ will have a $T$ component if the length varies. $N$ is by definition a unit vector, and $V$ will have constant length if $T$ does. Ordinarily, curves are always taken to be arclength parametrized in the abstract setting.
Comment: Thank you this works for me but my problem is I was only told that the basis is orthogonal not orthonormal hence I do not know the tangent is of unit length, so that was my problem do you think the author's intention was that the basis be orthonormal? Meaning the tangent should have been normalized as no one told me it was of constant length
Comment: @zbigniew2015 as Ted Shifrin mentioned your curve must be parametrized by arc length. Also, the trihedron $\{T,N,V\}$ you have above is called the Darboux trihedron and the functions $a,b,c$ you will obtain are the geodesic curvature, the normal curvature and the geodesic torsion of the curve $\gamma$ respectively. For more see [here](https://en.wikipedia.org/wiki/Darboux_frame)


How to access a ZIP file asset directly (without storing unpacked file temporarily) in Flutter?

Question: I want to read a zip file which is in my asset folder. I do not want to write the unpacked version to storage, but to directly process the zip file stream. The zip file only contains one file (which is retrieved by archive.first). However, I fail to convert a ByteData to an InputStream.
Is this possible?
import 'dart:convert';
import 'dart:typed_data';

import 'package:archive/archive.dart';

  @override
  void initState() {
    super.initState();

    DefaultAssetBundle.of(context)
        .load("assets/data/WZ2008.zip")
        .then((ByteData value) {
      Uint8List wzzip =
          value.buffer.asUint8List(value.offsetInBytes, value.lengthInBytes);
      final archive = ZipDecoder().decodeBuffer(???);   <- How to solve this?
      ArchiveFile a = archive.first;
      WZ2008 = jsonDecode(a.content)["Inhalt"]
          .map<String>((e) => e["Stichwort"].toString())
          .toList();
    });
}

Thanks!
Answer: You can use the archive package:
DefaultAssetBundle.of(context)
    .load("assets/data/WZ2008.zip")
    .then((ByteData value) {
  Uint8List wzzip =
      value.buffer.asUint8List(value.offsetInBytes, value.lengthInBytes);
  InputStream ifs = InputStream(wzzip);
  final archive = ZipDecoder().decodeBuffer(ifs);
  ArchiveFile a = archive.first;
  OutputStream os = OutputStream();
  a.decompress(os);
  String decomp = utf8.decode(os.getBytes());
  dynamic json = jsonDecode(decomp);
  WZ2008 =
      json["Inhalt"].map<String>((e) => e["Stichwort"].toString()).toList();
  a.close();
  ifs.close();
});


Is there a way to pick up all the items around you with one button?

Question: Similar to how the console versions of Diablo work, where you press Circle or what not, and it picks up everything around you. Is this possible, with any macros or mappings, to do in Diablo 3 for PC?
Answer: No, there isn't a way to do this.
Certain items (gold, potions, blood shards) will be picked up automatically when you get within a certain range.
Everything else must be clicked one at a time to pick up.
It's fun...
Comment: right... fun...
Comment: Demon Hunter can summon a Ferret Companion, that pick up gold around you. Activating the Companion skill allows you to instantly vacuum up all gold and health globes 60 yards around you. There's no way to pick up other items, though.


gwt fileupload

Question: I would like to trigger a click on the browse button on a hidden FileUpload widget.
The following code works fine on IE 6+, but doesn't work in FireFox.
<code>final FileUpload upload = new FileUpload();

upload.setVisible(false);
upload.setName("uploadFormElement");
panel.add(upload);

panel.add( new Button("Select File", new ClickListener()
{ public void onClick(Widget pSender)
{ jsClickUpload( upload.getElement() ); } }));

native void jsClickUpload( Element pElement ) /*-{ pElement.click(); }-*/;
</code>
How can I achieve the same in FireFox (and possibly other browsers)?
Answer: The solution can be read here:
http://www.quirksmode.org/dom/inputfile.html
in the last paragraph:

The click() method allows you to
  simulate a click on a form field.
  Checkboxes get toggled, radios
  selected, and so on. Unfortunately
  Mozilla and Opera haven't added this
  method to file upload fields. I wonder
  why, adding it is not really a
  security risk since the worst that can
  happen is that the file selection
  window pops up.
Comment: the file popup is a modal dialog, so it can be used to spam and cause DoS attacks on the user - imagine a dialog u cant close!
Comment: Also, an evil script could trigger a browse dialog at a carefully chosen time to cause the user to send a file somewhere other than where they expected.

It's worth noting also, that this is no longer possible in flash as of Flash 10.
Answer: have you tried calling the onClick() method directly?
Comment: The FileUpload widget in GWT has no click method, so you have to go use inline native javascript to do it.
Answer: The click method is currently in the process of being implemented in FF 4.  It is being discussed what security rules will be implemented and it sounds like it will be similar to Window.open and must be the direct result of a user action and not a timer or load.

gwt fileupload


Linux kernel: why does this call to kstrtol crash?

Question: I am learning kernel programming and have a simple call to kstrtol I am using to convert a string to a number. However, everytime I compile this module and use insmod to place it in the kernel, I get "BUG: unable to handle kernel paging request at f862b026" and then a register and stack dump.
I'm following the definition from here: https://www.kernel.org/doc/htmldocs/kernel-api/API-kstrtol.html. It seems like a really simple call. What am I doing wrong here?
<code>#include <linux/kernel.h>

static int __init convert(void)
{
    long myLong;
    char *myNumber = "342";
    myNumber[2] = '\0'; //Overwriting the '2', just so I know for sure I have a terminating '\0'

    if (kstrtol(myNumber, 10, &myLong) == 0)
    {
        printk("We have a number!\n");
    }
return 0;
}

static void __exit convert_exit(void)
{
    printk("Module unloaded\n");
}

module_init(convert);
module_exit(convert_exit);
</code>
Comment: The problem may be with overwriting the 2. Literals are not supposed to be modified.
Answer: You cannot modify string literals. Copy it into an array firstly.
edit: use this instead
<code>char mystr[] = "abdc";
</code>
edit2:
the underlying reason for this is, that a char pointer to a string literal points to a data segment, usually readonly. If you alter this memory you might get a crash.
When you create an array of chars instead, the string literal gets copied into the array on the stack, where you safely can modify it.
Comment: `char *mystr[] = "abcde"; char *myptr = mystr;`
Comment: The problem with that is that I need to use char pointers for my strings, as eventually I'm going to need to parse parameter input coming into the module. I'm splitting a string (format like: 120;something) into the number and word. So, I store the number in a char *. How do I handle it in this case?
Comment: The array will decay into a pointer in almost any situation, so it should be compatible.
Comment: @H2CO3, because I'm taking the paramater, for example param = "1234;something" and splitting it into two new strings (after I allocate the memory)

strncpy(number, param, 0, 5) (and similar for the "something" part)

number[5] = '\0'; kstrtol(number, 10, &result) -- where result is a long.

Is this a bad approach? If so, what is the correct approach
Comment: @Maxthecat It's not a bad approach. But then you are working an array. Aren't you?


Subtract in set intervals across 2 values in Excel

Question: I am trying to write a PTO calculator in Excel and need help subtracting paid time off.  The part I can't get to work is it subtracts in quarter-hour increments, but instead of using an HH:MM format, the times are scaled to 100.
Example:
    |     A        |  B
  --|--------------|--------
   1| Bank         |50.00
   2| CY           | 6.40
    |--------------|--------
   3| Used         | 9.50
    |--------------|--------
   4| Bank Remain  |
   5| CY Remain    |

The Used would subtract from CY Accrued first until it is less than 0.25, then it will subtract the rest from Bank Accrued.
Thanks for the help.  I did look for similar questions, but the only ones I saw calculated time in standard format (15 min intervals) not time proportioned to a 100 scale.
Comment: Would help if you show us an example of how you have structured your data
Comment: @RicardoDiaz, I inserted a table similar to the answer below, but vertical, which is how it looks in my Excel sheet.  This way, it visually resembles a standard subtraction problem to see what I am trying to accomplish.  Thanks for the suggestion.
Answer: This assumes using a formula instead of VBA and I have laid out the data in a simple table (see below) where the CY Old Balance is in cell B2.
| |     A       |  B   |   C   |    D     |
| |-------------|------|-------|----------|
|1|             | CY   | BANK  | PTO Used |
|2| Old Balance | 6.4  | 50    | 9.5      |
|3| New Balance | 0.15 | 46.75 |          |

The formula for the CY New Balance cell (B3) is:
=IF(B2>=D2,B2-D2,B2-0.25*INT(B2/0.25))

If the CY Old Balance is greater than or equal to the PTO Used, then I have assumed that the entire used amount is subtracted.
The B2-0.25*INT(B2/0.25) portion calculates how many whole portions of .25 are in your Old Balance and then subtracts that from your Old Balance giving you the CY New Balance.
The formula for the BANK New Balance cell (C3) is similar:
=IF(B2>=D2,C2,C2-(D2-0.25*INT(B2/0.25)))

The first part of the IF is based on the same assumption as above.
The C2-(D2-0.25*INT(B2/0.25)) uses the same "whole portions of .25" approach, then subtracts that from PTO Used to get what remains.  That is then subtracted from BANK Old Balance to get the New Balance.
Comment: Thank you for the answer.  I actually figured it out after I walked away and stopped thinking about it for the night.  Your solution is close to mine, with minor differences like `TRUNC()` instead of `INT()`.  However, I think in your equation for BANK New Balance, the _value if true_ statement should not be zero.  This would return `0` and would make it look like the person lost all their BANK PTO if indeed `B2>=D2`.  In reality, they would have all of it so the function should probably be: `=IF(B2>=D2,C2,C2-(D2-0.25*INT(B2/0.25)))`
Comment: You are correct.  I have corrected the formula for the BANK New Balance cell (C3).  However, I didn't change the table format since you provided an answer for that configuration.
Answer: I'm not sure if this should go in it's own answer or not, since the principle is the same as the answer from @ReyJuna, but the execution is somewhat different.  Using the table from the question:
    |     A        |  B
  --|--------------|--------
   1| Bank         |50.00
   2| CY           | 6.40
    |--------------|--------
   3| Used         | 9.50
    |--------------|--------
   4| Bank Remain  |46.75
   5| CY Remain    | 0.15

Starting with finding CY Remain, if CY is greater than Used you don't have to worry about running out of 0.25 increment segments, so you can directly subtract using B2-B3 in the function below.
When CY is less than Used, you only want groups of exactly 0.25, so you can use the TRUNC() function to drop the decimals.  The function is:
=IF(B2<B3,B2-(TRUNC(B2/0.25)*0.25),B2-B3)
Since you want to stop subtracting at CY less than 0.25, all you have to do is get the number of 0.25 groups in CY and subtract that.  The rest that needs to be subtracted from Bank will be handled by this function:
=IF(B2<B3,B1-(B3-TRUNC(B2/0.25)*0.25),B1)
Notice the TRUNC(B2/0.25)*0.25 is the same, but is now subtracted from the value in Used.  This gives you what is left over after the correct amount has been subtracted from CY first.  Finally, when the Bank Remain function is false, meaning Bank PTO is not needed, then B1 is returned as it went unchanged.


Water stains in bathroom are black - water is clean

Question: Why are there black stains on my bathroom sink and when I rinse cups and turn over to air dry on paper towel a black ring mark is left and also the cup is dry but has black marks on the inside of the cup and wipe it is dried black also?  Sink also slow drain.
Comment: Would put water in a clear glass and leave it sit, probably something in the water.  Slow drain is another separate question, drain cleaner, plunging, and/or snake to fix.
Comment: Does it also smell bad? Sounds somewhat like black sulfur, but there are other things that make dark stains in the presence of oxygen after being clear dissolved in water, such as iron or manganese. Are you on a well or municipal water? A water test seems advisable if you are on a well. Public water you can request to look at the suppliers required tests.
Answer: You probably have high iron and manganese in your water.
https://water.unl.edu/article/drinking-water-wells/iron-and-manganese-water


Under what circumstances will RegistryKey.CreateSubKey(String) return null?

Question: So the doco for RegistryKey.CreateSubKey(String) http://msdn.microsoft.com/en-us/library/ad51f2dx(v=vs.110).aspx says

Return Value: The newly created subkey, or null if the operation failed. If a zero-length string is specified for subkey, the current RegistryKey object is returned.

However looking at the exception list

ArgumentNullException: when subkey is null.
SecurityException: When The user does not have the permissions required to create or open the registry key.
ObjectDisposedException:When The RegistryKey on which this method is being invoked is closed (closed keys cannot be accessed).
UnauthorizedAccessException: When The RegistryKey cannot be written to; for example, it was not opened as a writable key , or the user does not have the necessary access rights.
IOException: When The nesting level exceeds 510. -or- A system error occurred, such as deletion of the key, or an attempt to create a key in the LocalMachine root.

I cant think of a failure condition that would not fall into one of those exception cases.
So what am I missing?
Answer: You need to ignore this, it doesn't actually happen.  The underlying problem is that the native winapi functions for the registry are very unusual.  And don't in fact guarantee that the returned handle isn't null.  Putting it in C# terms, a "normal" winapi function is used like this:
HANDLE handle = CreateWidget(...);
if (handle == NULL) {
    int err = GetLastError();
    DealWithError(err);
}

But the registry functions work like this:
HANDLE handle;
int err = RegCreateKeyEx(..., out handle);
if (err != 0) DealWithError(err);

You probably see the difference, in the normal case there's a very hard guarantee that the handle won't be null if the function failed.  But the registry functions allow the loophole of returning a null handle but still returning a 0 error code.  The MSDN documentation cannot exclude that possibility because the winapi documentation doesn't exclude it.
In practice this never happens, an error code is always produced.
Not sure what the original reason behind this design quirk might be.  We need Raymond Chen to blog about it :)
Answer: Looking at CreateSubKey() in the reference source, there's only one code path that may return null:
When RegCreateKeyEx() returns 0 (ERROR_SUCCESS), but the resulting key handle (phkResult output parameter) is invalid (INVALID_HANDLE or NULL).
That code path contains an assertion:
BCLDebug.Assert(false, "Unexpected code path in RegistryKey::CreateSubKey");

So I guess this means that CreateSubKey() should never returns null.
Maybe the MSDN documentation was just copy-pasted from OpenSubKey, which returns null when the key is missing?


VBA - Want to put the sum result at the bottom automatically

Question: I need to put the result of the sum at the end of the last column on different sheets (Not the same number of columns and number of rows)
I need to fix the last part of the code to let that happen.
this is the code (I marked in the code what does not work):
Sub Sum_Dynamic_Rng()

Dim ws As Worksheet
Dim LastCell As Range

Dim ColumnNumber As Long
Dim ColumnLetter As String

ColumnNumber = Range("S3").End(xlToLeft).Column

ColumnLetter = Split(Cells(1, ColumnNumber).Address, "$")(1)

    For Each ws In ThisWorkbook.Worksheets

        Set LastCell = ws.Range(ColumnLetter & 2).End(xlDown).Offset(1, 0)

        **LastCell = WorksheetFunction.Sum(ws.Range(ws.Range(ColumnLetter & 2), ws.Range(ColumnLetter & 2).End(xlDown)))**

    Next ws

End Sub

Comment: A side note, but see [a better way to find the last cell](https://stackoverflow.com/questions/11169445/error-in-finding-last-used-cell-in-excel-with-vba).
Answer: Your code works one with two bugs

You searched for "LastCell" in the first sheet only because it was before the FOR loop. The spreadsheets have different dimensions from what you wrote, so I moved the search to a loop so that there is a re-check for each iteration.
Another (in my opinion) problem was the reboot which added up the previous calculations.
for example.
2 + 2 = 4, 2 + 2 + 4 = 8, 2 + 2 + 4 + 8 = 16 e.t.c.

My code is:
Sub Sum_Dynamic_Rng()

Dim ws As Worksheet
Dim LastCell As String  'I changed from Range to String
Dim ColumnNumber As Long
Dim ColumnLetter As String

    For Each ws In ThisWorkbook.Worksheets

        LastColumnNumber = ws.Range("s3").End(xlToLeft).Column
        LastColumnLetter = Split(Cells(1, LastColumnNumber).Address, "$")(1)
        LastRow = ws.Cells(ws.Rows.Count, "G").End(xlUp).Row

        LastCell = LastColumnLetter & LastRow + 1 ' (+1) - last but not the first empty

     ws.Range(LastCell) = WorksheetFunction.Sum(ws.Range(ws.Range(LastColumnLetter & 2), ws.Range(LastColumnLetter & LastRow)))
     ws.Range(LastCell).Interior.ColorIndex = 43   ''I added for better visualization
    Next ws

End Sub

If you are satisfied with the answer, give me a plus point from the answer and close the topic, unless you have any questions.
:)
Answer: IT'S OK I did some changes and now it's working!
Sub Sum_Dynamic_Rng()
Dim ws As Worksheet
Dim LastCell As String  'I changed from Range to String
Dim ColumnNumber As Long
Dim ColumnLetter As String
For Each ws In ThisWorkbook.Worksheets

    LastColumnNumber = ws.Range("s3").End(xlToLeft).Column
    LastColumnLetter = Split(Cells(1, LastColumnNumber).Address, "$")(1)
    LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row ***''REPLACE TO A FROM G IN THIS LINE***

    LastCell = LastColumnLetter & LastRow + 1 ' (+1) - last but not the first empty

 ws.Range(LastCell) = WorksheetFunction.Sum(ws.Range(ws.Range(LastColumnLetter & 2), ws.Range(LastColumnLetter & LastRow)))
 ws.Range(LastCell).Interior.ColorIndex = 43   ''I added for better visualization
Next ws

End Sub
Comment: If you are satisfied with the answer, give me a plus point from the answer and close the topic, unless you have any questions. :)


Does the certificate a SSL connection/state "points" to change if I load a new certificate in OpenSSL?

Question: I am building an application that will enable users to connect to the same server. Rather than the application/device using its own certificate/private key, it is important to ensure that each user has their own certificate/private key to use for encryption.
Now I know, from the OpenSSL website documents, that their internal certificate store of OpenSSL can hold one certificate/key pair for the RSA cipher. My question is this:
Presume I have a SSL struct named ssl1 that I created from my SSL_CTX where I didn't set the certificate/key to use in the SSL_CTX (thus not inheriting the certificate/key). I then go on to set the certificate/key for ssl1 that is associated with some user. Then suppose I have another SSL struct named ssl2 created from the same SSL_CTX. I then go on to set the certificate/key for ssl2 that is associated with a different user than the first one.
If at this point I call the SSL_connect() API on ssl1 will it use the certificate/key I set for ssl2? I ask since the store says it only holds one cert/key pair and I loaded the cert/key for ssl2 last, thus I presume it would overwrite the one I loaded first for ssl1.
Thanks for reading my post. I appreciate any help/wisdom/pointers you can provide.
Answer: First, I'm confused about the implementation details you're asking for. Second, I can't think of a circumstance in which different keys would be useful unless you're trying to authenticate your users by their certificates -- which you're apparently not doing (users needing different encryption, not authentication.
I believe what you really want to do is establish your connections using settings that provide for Perfect Forward Secrecy. To do that, you want to use TLS ciphers all have names that start with TLS_DHE_. Those use Diffie-Hellman key exchanges, thus making the role of the server's key basically one of authentication of the server to users.
Answer: As far as I understand the SSL_CTX acts as template for SSL objects. So when you create new SSL object it inherits the properties/attributes of the SSL_CTX from which it is created. This is clearly mentioned here
So for your question, both ssl1 and ssl2 objects will use their own certificate/key.


Prove by induction (formula for $\sum^n(3i-1)^2$)

Question: Anyone knows how to do this? The answer I'm getting is not correct.
Prove by induction that, for all integers $n\ge1$, $$\sum_{i=1}^n (3i-1)^2 = \frac12 n(6n^2 + 3n - 1). $$
Thanks
This Is what I have managed to get. After this I think I'm doing something wrong:
  $$ \frac12 n(6n^2 + 3n - 1 + 6n + 4) (3n +2). $$
Comment: Can you please show us what steps you have taken so we can try and help you more?
Comment: $\displaystyle \sum_{i=1}^{n+1} (3i - 1)^2 = \sum_{i=1}^n (3i-1)^2 + (3(n+1)-1)^2 $. You can now use the inductive step.
Comment: Yes Matt, that's what I've done. I think I am having a problem with simplifying
Answer: You prove it the usual way:
Base. Establish the result for $n=1$.
If $n=1$, then the left hand side is
$$\sum_{i=1}^1(3i-1)^2 = (3(1)-1)^2 = 4,$$
and the right hand side is
$$\frac{1}{2}(1)\left(6(1)^2 + 3(1) - 1\right) = \frac{1}{2}(8) = 4.$$
So we have equality.
Inductive Step.
Induction Hypothesis. The result holds for $k$; that is,
$$\sum_{i=1}^k(3i-1)^2 = \frac{1}{2}k(6k^2 + 3k - 1).$$
To prove. The result holds for $k+1$.
$$\begin{align*}
\sum_{i=1}^{k+1}(3i-1)^2 &= \left(\sum_{i=1}^k(3i-1)^2\right) + (3(k+1)-1)^2\\
&= \frac{1}{2}k(6k^2+3k-1) + (3(k+1)-1)^2 &\text{(by the Induction Hypothesis)}\\
&=\frac{1}{2}k(6k^2+3k-1) + (3k+2)^2\\
&=\frac{1}{2}k(6k^2+3k-1) + (9k^2 + 12k+4)\\
&= \frac{1}{2}\left(6k^3 + 3k^2 - k + 18k^2 + 24k + 8\right)\\
&= \frac{1}{2}\left(6k^3 + 21k^2 + 23k + 8\right)\\
&=\frac{1}{2}\left(6(k^3 + 3k^2 + 3k + 1) + 3k^2 + 5k + 2\right)\\
&=\frac{1}{2}\left(6(k+1)^3 + 3(k^2 + 2k + 1) -k - 1\right)\\
&=\frac{1}{2}\left(6(k+1)^3 + 3(k+1)^2 - (k+1)\right)\\
&=\frac{1}{2}(k+1)\left(6(k+1)^2 + 3(k+1) - 1\right).
\end{align*}$$
As this is exactly what we needed to show for $k+1$, this proves the inductive step.
Conclusion. The given formula holds for $n=1$; and if it holds for $k$, then it also holds for $k+1$. By mathematical induction, the given formula holds for all positive integers $n$. $\Box$
Comment: Thanks a lot Arturo. I owe you for this
Comment: @user1148677: The algebraic manipulations may seem unnatural. The key is that we know what the answer "should" be, so we manipulate towards that aim. We know it should be an expression "in $(k+1)$", so it is natural to try to write it as one; hence the sixth and following lines of the equality sequence.
Answer: Hint: use telescopy, i.e. a very simple telescopic induction proof yields
$$\rm\ f(n)\ =\ \sum_{i\: =\: 1}^n\:\ (3i-1)^2\ \  \iff\ \ \ f(n) - f(n-1)\ =\ (3n-1)^2,\quad\  f(0) = 0$$
So the proof reduces to showing that $\rm\:f(n) = n(6n^2 + 3n - 1)/2\:$ satisfies the RHS equations. Clearly $\rm\:f(0) = 0$. The other equality is between two quadratics, so to prove it we need only show they are equal at $3$ points, say $\rm\:n = 0,1,2.\:$ Since $\rm\:f(-1)=-1,\:f(0)=0,\:f(1)=4,\:f(2)=29$
$\rm\qquad\qquad n=0:\quad  f(0)-f(-1)= 0-(-1) =\: (3\cdot 0-1)^2$
$\rm\qquad\qquad n=1:\quad  f(1)\ -\ f(0)\:= 4\ \ -\ \ 0\ =\:\ (3\cdot 1 -1)^2$
$\rm\qquad\qquad n=2:\quad  f(2)\ -\ f(1)\:= 29\ -\ 4\: =\:\ (3\cdot 2 -1)^2\quad$ QED
Note that the above method yields a simple mechanical algorithm for constructing such proofs.
Answer: Check the statement for $n=1$ (this is the base case):
$$\sum_{i=1}^1(3i-1)^2=(3\cdot1-1)^2=2^2=\fbox{4}$$
$$\left(\frac{1}{2}(1)\right)(6\cdot1^2+3\cdot1-1)=\frac{1}{2}\cdot 8=\fbox{4}$$
So the statement is true for $n=1$!
Now we want to show that, any time the statement is true when $n=k$ (for some $k$), it will also necessarily be true when $n=k+1$.
So, let's suppose the statement is true when $n=k$ (this is the induction hypothesis). That is, suppose
$$\sum_{i=1}^k(3i-1)^2=\left(\frac{1}{2}(k)\right)(6k^2+3k-1).\qquad(*)$$
Our goal is to show, using this hypothesis, that the statement is true when $n=k+1$; that is,
$$\sum_{i=1}^{k+1}(3i-1)^2=\left(\frac{1}{2}(k+1)\right)(6(k+1)^2+3(k+1)-1).\qquad (**)$$
Observe that the difference between the left sides of equations $(*)$ and $(**)$ is
$$\left(\sum_{i=1}^{k+1}(3i-1)^2\right)-\left(\sum_{i=1}^k(3i-1)^2\right)=(3(k+1)-1)^2.$$
We are assuming that equation $(*)$ is valid; so $(**)$ can only be true if the difference on the right sides is also equal to this quantity. That is, in order to conclude that the statement is true for $n=k+1$, we must show that
$$\left(\frac{1}{2}(k+1)\right)(6(k+1)^2+3(k+1)-1)=\left(\frac{1}{2}(k)\right)(6k^2+3k-1)+(3(k+1)-1)^2$$
Expanding out, this is clear. Thus, we have proved the base case (true for $n=1$), and the induction step (true for $n=k$ implies true for $n=k+1$), so the statement is true by induction.
Comment: Glad to help, Adil. Downvoter, care to explain?
Comment: @chessmath: You're incorrect.
$$9\sum_{i=1}^n i^2 = 3n^3+\frac{9}{2}n^2+\frac{3}{2}n$$
$$-6\sum_{i=1}^n i = -3n^2-3n$$
$$\sum_{i=1}^n 1 = n$$
Add them up and you get $$3n^2+\frac{3}{2}n^2-\frac{1}{2}n = \left(\frac{1}{2}n\right)(6n^2+3n^2-1)$$
as I (and the original problem, and all the other answers here) claim.
Comment: $$\sum_{i=1}^n i^2=\frac{1}{6}(n(n+1)(2n+1))=\frac{1}{3}n^3+\frac{1}{2}n^2+\frac{1}{6}n$$
Multiplying by 9, we get
$$3n^3+\frac{9}{2}n^2+\frac{3}{2}n$$
Comment: That is right Chonoles do you know any work about the sums $\sum i^p$?
Answer: $$
\begin{align*}
\sum_{i=1}^n (3i-1)^2 &= \sum_{i=1}^n \left( (9i)^2 -6i +1 \right)\\
        &= 9 \frac{n(n+1)(2n+1)}{6} - 6\frac{n(n+1)}{2} + n\\
        &= 3n(n+1) \left( \frac{2n+1}{2} -1 \right) +n \\
        &= 3n(n+1) \left( \frac{2n-1}{2} \right) +n \\
        &= \frac{3n(n+1)(2n-1)+2n}{2}\\
        &= n \left(\frac{6n^2+3n-1}{2} \right)\\
        &= 3n^3+\frac{3n^2}{2}-\frac{n}{2}\\
\end{align*}
$$


Is it possible to update a parameter in AWS SSM parameter store from an SSM Command?

Question: As per a requirement, we want to store a parameter in SSM parameter store, and one should be able to update the parameter value through an SSM command.
From the initial research it is understood that we can run the SSM commands on Target EC2 instances. However not able to find a way to run the command with target as Parameter store. Please help.
Comment: Can you provide any example code showing what you are trying to achieve?
Answer: To read values to or from ssm parameter store you can use the aws cli.
For that to work you need to set it up:
https://docs.aws.amazon.com/de_de/cli/latest/userguide/install-cliv2.html
You will need to create an aws access key and an aws secret key, if you not already have that.
After you have configured your aws cli like that:
$ aws configure
AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Default region name [None]: eu-central-1
Default output format [None]: json

You should be able to execute this command to check if it works:
$ aws sts get-caller-identity
To store a value in ssm this command will work:
$ aws ssm put-parameter --name "test123" --type "String" --value "MyValue"
{
  "Version": 1,
  "Tier": "Standard"
}

To overwrite a value in ssm this command will work:
$ aws ssm put-parameter --name "test123" --type "String" --value "MyValue" --overwrite
{
  "Version": 2,
  "Tier": "Standard"
}

To read that parameter from ssm use this:
$ aws ssm get-parameter --name "test123" --query Parameter.Value
"MyValue"

Comment: If want to update an existing parameter, you need the option `--overwrite`. Check https://docs.aws.amazon.com/cli/latest/reference/ssm/put-parameter.html
Comment: Specifying a parameter type isn't required when updating a parameter. You must specify a parameter type when creating a parameter.
Answer: To update a parameter simply use the put-parameter method again with the --overwrite option. You do not need other options or set the type.
aws ssm put-parameter --name "my-param" --value "NewValue" --overwrite

The result will be something like this:
{
  "Version": 2,
  "Tier": "Standard"
}

Comment: did you check answer above


r-410a pressure problem, 285/120 psig

Question: i just installed a new split unit r-410a a/c system.   it is running at 285/120 psig.  the high side seems way low, should be about 420.  the correct orifice is installed.  this is a 1.5 ton condenser, 2 ton evaporator, and a 0.051 inch orifice.  thanks for any suggestions.
Comment: Is this a mini-split ductless a/c unit? What is the make and model? Is it 120 V or 240 V?
Comment: Window units used to use chilled condensed water from the evaporator to help cool the condenser coils and presumably this would greatly reduce high side pressure. Do mini-split systems use this technique?
Comment: 230 volt, in the attic ducted evaporator.  not a mini system, 1 of 2 systems for the house
Comment: What was the outside temperature when you measured the pressures? What is the temperature of the air coming out of the condensing unit?
Comment: Is the evaporator unit putting out cool air?
Comment: How did you decide on the 0.051 inch orifice? Was this the specified one for the condenser? My Carrier system has been in service for 26 years and works acceptably. It is an R-22 , 12 SEER, scroll, 3.5 ton condenser unit and (IIRC) a 4 ton evaporator. It has a TXV. Given that this unit is a bit undersized for our application (only unit for a poorly insulated 2000 ft^2 tract house in hot Dallas TX, but surrounded by mature tall trees), I would bet that a fixed orifice would be just fine, but we haven't had any problem with it.
Comment: Did you have a long line set? Or longer than mfg's listing. If a long line set sometimes additional charge is needed. Was the system pumped down below 500 um , non compressables will affect the pressures.
Answer: This may be normal for R-410a operating at an outside temperature of about 92 F [Edit: or maybe ambient of 75-80 F, so the air coming out of the condensing unit is 92 F].
See http://www.arkema.com/export/shared/.content/media/downloads/products-documentations/fluorochemicals/Forane-410A-Pressure-temperature-chart.pdf
EDIT
If you Google "operating pressures for R-410a" you will get 420 psi for the high side, assuming the air coming off the condenser is 120 F. What it the temp of the air coming off yours? Maybe your condensing unit has such an effective fan system that it cools the condenser better than the average fan.
There is of course the possibility that your system is not operating optimally and so not pumping enough heat to produce the proper condenser temperature. Is your evaporator unit/circulating fan producing the expected flow of chilled air?

r-410a pressure problem, 285/120 psig


MSR Partition causing Ubuntu instalation to be stucked?

Question: After i migrated windows 10 from my hdd to my ssd it worked fine.
But as i want to dualboot Ubuntu 14.04.03 i still have this task to do.
So i made a bootable usb stick for this Ubuntu version and wanted to install it. Therefore i created 3 partitions. 1 for the OS itself, 1 for the Home and 1 linux-swap partition. But gparted also shows me one partition, which filesystem can´t be detected. It´s 128 MB and i´m pretty sure it´s the MSR Partition for the ssd. So if i now want to install Ubuntu it stucks after i  need to check "Download Updates" and "Third-Party Software" and press Ok.
I´m pretty sure this happens because of the msr partition, but i don´t know what to do about it.
Please Help!
Thanks.
Answer: The acronym "MSR" means "Microsoft Reserved." This partition is a standard part of recent Windows installations. It's basically unused space that Microsoft wants to be present so that its disk utilities will have some "scratch space" to be used for certain operations, if and when the need arises. This partition is almost certainly not the source of your problem. As it's present on the vast majority of new Windows installations, it's present on huge numbers of Ubuntu installations, so if it were causing problems, the Internet would be flooded with problem reports concerning the partition. That hasn't happened.
Offhand, my initial guess about your problem is that the installer is having trouble accessing an archive site because of a bad Internet connection -- either a temporary problem or something more systemic. If so, you might do better to disconnect your computer completely when doing the installation. You won't be able to download updates while installing, but you can do so after installing, when you'll be better able to experiment with different repository sites to find one that works for you.
That's just my initial guess, though. It could be that something completely different is causing your problems. If so, you may need to debug the problem further, as described here:
https://wiki.ubuntu.com/DebuggingUbiquity


onTouchEvent for children of zoomed ViewGroup

Question: For my game Hashi I want to build a custom ViewGroup that allows zooming and scrolling (both axes), containing children that are affected on touches as well.

I have set setWillNotDraw(false) and overwritten draw(Canvas) to use canvas.scale(..) and canvas.translate(..):
@Override
public void draw(Canvas canvas)
{
    canvas.save();
    canvas.scale(mScaleFactor, mScaleFactor, mScaleCenter.x, mScaleCenter.y);
    canvas.translate(mTranslation.x * mScaleFactor, mTranslation.y * mScaleFactor);
    super.draw(canvas);
    canvas.restore();
}

But then I realized, that the MotionEvent parameter of the onTouchEvent for children is offset by the value I set with the translation (so they are detected, as if the container did not have any zoom or offset).
I tried to overwrite dispatchTouchEvent in the parent ViewGroup and adjust the coordinates of the event. But MotionEvent is final and can only be instantiated via MotionEvent.obtain(..). And there is no version of obtain to accept multiple coordinates, when there is more than one finger down.
Is there any way to modify the MotionEvent parameters, so I don't need to do it in the onTouchEvent methods of the child views (that would be much more complex), or even a better approach to implement zoom and scroll?
I implemented my own zoom container because I need to control the touches strictly (children also listen to swipe gestures, but need to be intercepted, when a second finger is down).
Answer: Don't try and create a new MotionEvent by providing coordinates.
Copy the existing event and then transform it using a matrix.
e.g. something like
// Matrix used for drawing the view
Matrix matrix = new Matrix();
matrix.setScale(scaleFactor, scaleFactor);
matrix.postTranslate(panX, panY);
// used with canvas.concat(matrix);

// Matrix for Touch events
Matrix mappingMatrix = new Matrix();
// Touch event matrix needs to be inverted
matrix.invert(mappingMatrix);

// Copy the touch Event that is being mapped
MotionEvent transformEvent = MotionEvent.obtain(ev);
// Apply it's event mapping matrix
transformEvent.transform(mappingMatrix);

Obtain copy documentation
I do something very similar in my custom viewgroup for scaling MotionEvents to children in my FixedHeaderTableLayout Library.
The MotionEvent copying is done here
Comment: After some hard hours I made it working, thanks to your inputs. Check my answer for a full solution, if you are interessted in.
Answer: So for those having the same problem I post my solution (thanks again Andrew for your help).
Update
Because I experienced input issues while testing, I decided to use onLayout instead of dispatchTouchEvent and draw methods to apply scale factor and translation, as the old solution did only apply it to the drawing and the input detection, but the container still declared the position of the children in the original place. This was causing espresso to execute the touches in the wrong place. With this solution the children are completely offset, so it also works with testing (and probably other things I did not consider).
Note that both solutions only work, when you embed (an) other layout container(s) that match the parents size.
If you want to change that, you need to change the implementation of onLayout.
public class ZoomContainer extends ViewGroup
{
    /**
     * Limit the maximum/minimum scrolling to prevent scrolling the container,
     * so that no more children are visible.
     * The value is relative to the size of the container (so 0.1 means 10% of the size of this container)
     */
    protected float mTranslationBounds = 0.1f;
    /**
     * The translation to be applied to the container
     */
    protected PointF mTranslation;
    /**
     * The the current zoom factor.
     * It is initialized with a value smaller than 1, to append some empty space around the view.
     */
    protected float mScaleFactor = 0.95f;
    /**
     * The minimum scale factor to prevent endless zooming
     */
    protected float mScaleFactorMin = 0.8f;
    /**
     * The maximum scale factor to prevent endless zooming.
     */
    protected float mScaleFactorMax = 5.0f;
    /**
     * Used to indicate, whether or not this is the first touch event, which has no differences yet.
     */
    protected boolean mIsTouchStarted = false;
    /**
     * Distance of the fingers from the last touch event
     */
    protected float mStartDistance = 0;
    /**
     * Center of the two fingers from the last touch event.
     */
    protected PointF mStartTouchPoint = new PointF(0, 0);

    public ZoomContainer(Context context)
    {
        super(context);
    }

    public ZoomContainer(Context context, @Nullable AttributeSet attrs)
    {
        super(context, attrs);
    }

    public ZoomContainer(Context context, @Nullable AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
    }

    /**
     * Cancel all child touch events, if there is more than one finger down.
     */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev)
    {
        boolean intercept = ev.getPointerCount() > 1;
        if (intercept)
        {
            Log.d("TableView", "Intercepted");
            mIsTouchStarted = false;
        }
        return intercept;
    }

    protected void initializeTranslation()
    {
        if (mTranslation == null)
        {
            mTranslation = new PointF(getWidth() * (1 - mScaleFactor) / 2f,
                    getHeight() * (1 - mScaleFactor) / 2f);
            Log.d("TableView", "Translation: " + mTranslation);
        }
    }

    /**
     * Calculate the new zoom and scroll respecting the difference to the last touch event.
     */
    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        switch (event.getAction())
        {
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                mIsTouchStarted = false;
                return true;
        }
        if (event.getPointerCount() <= 1)
        {
            mIsTouchStarted = false;
            return true;
        }
        float[] currentPointArray = new float[]{event.getX(0),
                event.getY(0),
                event.getX(1),
                event.getY(1)};
        float currentFingerDistance = getDistance(currentPointArray[0],
                currentPointArray[1],
                currentPointArray[2],
                currentPointArray[3]);
        // Read the current center of the fingers to determine the the new translation
        PointF currentPoint = getPoint(currentPointArray[0],
                currentPointArray[1],
                currentPointArray[2],
                currentPointArray[3]);
        if (mIsTouchStarted)
        {
            // 1 / oldScaleFactor - 1 / newScaleFactor is required to respect the relative translation,
            // when zooming (translation is always from the upper left corner,
            // but zooming should be performed centered to the fingers)
            float scaleFactorDifference = 1f / mScaleFactor;
            mScaleFactor = getBoundScaleFactor(mScaleFactor + (currentFingerDistance / mStartDistance - 1));
            scaleFactorDifference -= 1f / mScaleFactor;
            // Add the finger scroll since the last event to the current translation.
            PointF newTranslation = new PointF(mTranslation.x + (currentPoint.x - mStartTouchPoint.x) / mScaleFactor,
                    mTranslation.y + (currentPoint.y - mStartTouchPoint.y) / mScaleFactor);
            // Add the current point multiplied with the scale difference to make sure,
            // zooming is always done from the center of the fingers. Otherwise zooming would always be
            // applied from the upper left edge of the screen.
            newTranslation.x -= currentPoint.x * scaleFactorDifference;
            newTranslation.y -= currentPoint.y * scaleFactorDifference;
            mTranslation = getBoundTranslation(newTranslation);
        }
        mStartTouchPoint = currentPoint;
        mStartDistance = currentFingerDistance;
        mIsTouchStarted = true;
        requestLayout();
        return true;
    }

    protected float getBoundValue(float value, float min, float max)
    {
        return Math.min(Math.max(value, min), max);
    }

    protected PointF getBoundTranslation(PointF translation)
    {
        translation.x = getBoundValue(translation.x,
                -(getWidth() * (mScaleFactor - 1) + getWidth() * mTranslationBounds),
                getWidth() * mTranslationBounds);
        translation.y = getBoundValue(translation.y,
                -(getHeight() * (mScaleFactor - 1) + getHeight() * mTranslationBounds),
                getHeight() * mTranslationBounds);
        return translation;
    }

    protected float getBoundScaleFactor(float scaleFactor)
    {
        return getBoundValue(scaleFactor, mScaleFactorMin, mScaleFactorMax);
    }

    protected PointF getPoint(float x1, float y1, float x2, float y2)
    {
        return new PointF(getCenter(x1, x2), getCenter(y1, y2));
    }

    protected float getCenter(float position1, float position2)
    {
        return (position1 + position2) / 2f;
    }

    protected float getDistance(float x1, float y1, float x2, float y2)
    {
        float distanceX = Math.abs(x1 - x2);
        float distanceY = Math.abs(y1 - y2);
        return (float) Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b)
    {
        float width = (r - l);
        float height = (b - t);
        if (width <= 0 || height <= 0)
        {
            return;
        }
        initializeTranslation();
        final int childCount = getChildCount();
        l = (int) (mTranslation.x * mScaleFactor);
        r = (int) ((width + mTranslation.x) * mScaleFactor);
        t = (int) (mTranslation.y * mScaleFactor);
        b = (int) ((height + mTranslation.y) * mScaleFactor);

        for (int i = 0; i < childCount; i++)
        {
            View child = getChildAt(i);
            child.layout(l, t, r, b);
        }
    }
}

Old solution
Using dispatchTouchEvent and draw methods to apply scale factor and tranlation:
public class ZoomContainer extends ViewGroup
{
    /**
     * Limit the maximum/minimum scrolling to prevent scrolling the container,
     * so that no more children are visible.
     * The value is relative to the size of the container (so 0.1 means 10% of the size of this container)
     */
    protected float mTranslationBounds = 0.1f;
    /**
     * The translation to be applyed to the container
     */
    protected PointF mTranslation;
    /**
     * The the current zoom factor. You might initialze it to a value smaller than 1, if you want to add some padding in the beginning.
     */
    protected float mScaleFactor = 1f;
    /**
     * The minimum scale factor to prevent endless zooming
     */
    protected float mScaleFactorMin = 0.8f;
    /**
     * The maximum scale factor to prevent endless zooming.
     */
    protected float mScaleFactorMax = 4f;
    /**
     * Used to indicate, whether or not this is the first touch event, which has no differences yet.
     */
    protected boolean mIsTouchStarted = false;
    /**
    * Distance of the fingers from the last touch event
    */
    protected float mStartDistance = 0;
    /**
     * Center of the two fingers from the last touch event.
     */
    protected PointF mStartTouchPoint = new PointF(0, 0);

    public ZoomContainer(Context context)
    {
        super(context);
        setWillNotDraw(false);
    }

    public ZoomContainer(Context context, @Nullable AttributeSet attrs)
    {
        super(context, attrs);
        setWillNotDraw(false);
    }

    public ZoomContainer(Context context, @Nullable AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
        setWillNotDraw(false);
    }

    @Override
    public void draw(Canvas canvas)
    {
        canvas.save();
        canvas.concat(createDrawMatrix());
        super.draw(canvas);
        canvas.restore();
    }

    /**
    * Cancel all child touch events, if there is more than one finger down.
    */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev)
    {
        boolean intercept = ev.getPointerCount() > 1;
        if (intercept)
        {
            mIsTouchStarted = false;
        }
        return intercept;
    }

    /**
     * Creates the transformation matrix for drawing and converting touch coordinates
     */
    protected Matrix createDrawMatrix()
    {
        // Make sure children are centered, if initial scroll factor is not 1.
        if (mTranslation == null)
        {
            mTranslation = new PointF(getWidth() * (1 - mScaleFactor) / 2f,
                    getHeight() * (1 - mScaleFactor) / 2f);
        }
        // Matrix used for drawing the view
        Matrix matrix = new Matrix();
        matrix.setScale(mScaleFactor, mScaleFactor);
        matrix.postTranslate(mTranslation.x, mTranslation.y);
        return matrix;
    }

    /**
     * Transform the touch coordinates according to the current zoom and scroll,
     * for children to get the appropriate ones.
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev)
    {
        // Matrix for Touch events
        Matrix mappingMatrix = new Matrix();
        // Touch event matrix needs to be inverted
        createDrawMatrix().invert(mappingMatrix);

        // Copy the touch Event that is being mapped
        MotionEvent transformEvent = MotionEvent.obtain(ev);
        // Apply it's event mapping matrix
        transformEvent.transform(mappingMatrix);

        boolean handled = super.dispatchTouchEvent(transformEvent);
        transformEvent.recycle();
        return handled;
    }

    /**
     * Calculate the new zoom and scroll respecting the difference to the last touch event.
     */
    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        switch (event.getAction())
        {
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                mIsTouchStarted = false;
                return true;
        }
        //
        if (event.getPointerCount() <= 1)
        {
            mIsTouchStarted = false;
            return true;
        }
        float[] currentPointArray = new float[]{event.getX(0),
                event.getY(0),
                event.getX(1),
                event.getY(1)};
        float currentDistance = mScaleFactor * getDistance(currentPointArray[0],
                currentPointArray[1],
                currentPointArray[2],
                currentPointArray[3]);
        Matrix transformation = createDrawMatrix();
        transformation.mapPoints(currentPointArray);
        PointF currentPoint = getPoint(currentPointArray[0],
                currentPointArray[1],
                currentPointArray[2],
                currentPointArray[3]);
        if (mIsTouchStarted)
        {
            float scaleFactorDifference = mScaleFactor;
            mScaleFactor = getBoundScaleFactor(mScaleFactor + (currentDistance / mStartDistance - 1));
            scaleFactorDifference -= mScaleFactor;
            PointF newTranslation = new PointF(mTranslation.x + currentPoint.x - mStartTouchPoint.x,
                    mTranslation.y + currentPoint.y - mStartTouchPoint.y);
            newTranslation.x += currentPoint.x * scaleFactorDifference;
            newTranslation.y += currentPoint.y * scaleFactorDifference;
            mTranslation = getBoundTranslation(newTranslation);
        }
        mStartTouchPoint = currentPoint;
        mStartDistance = currentDistance;
        mIsTouchStarted = true;
        invalidate();
        return true;
    }

    protected float getBoundValue(float value, float min, float max)
    {
        return Math.min(Math.max(value, min), max);
    }

    protected PointF getBoundTranslation(PointF translation)
    {
        translation.x = getBoundValue(translation.x,
                -(getWidth() * (mScaleFactor - 1) + getWidth() * mTranslationBounds),
                getWidth() * mTranslationBounds);
        translation.y = getBoundValue(translation.y,
                -(getHeight() * (mScaleFactor - 1) + getHeight() * mTranslationBounds),
                getHeight() * mTranslationBounds);
        return translation;
    }

    protected float getBoundScaleFactor(float scaleFactor)
    {
        return getBoundValue(scaleFactor, mScaleFactorMin, mScaleFactorMax);
    }

    protected PointF getPoint(float x1, float y1, float x2, float y2)
    {
        return new PointF(getCenter(x1, x2), getCenter(y1, y2));
    }

    protected float getCenter(float position1, float position2)
    {
        return (position1 + position2) / 2f;
    }

    protected float getDistance(float x1, float y1, float x2, float y2)
    {
        float distanceX = Math.abs(x1 - x2);
        float distanceY = Math.abs(y1 - y2);
        return (float) Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b)
    {
        final int childCount = getChildCount();
        for (int i = 0; i < childCount; i++)
        {
            View child = getChildAt(i);
            child.layout(0, 0, r - l, b - t);
        }
    }
}


Get values from hash in hash

Question: I tried to implement this example in order to compare values:
error = system_errors[response_code]
    raise error[:error_class].constantize, error[:error_message]

@system_errors = {100 => { error_class: 'SystemError', error_message = 'A general system error occured.'},
                    101 => { error_class: 'MaintenanceError', error_message = 'System is undergoing maintenance, request could not behandled.'},
                    110 => { error_class: 'AuthenticationError', error_message = 'Login failed. Check your API credentials.'},
                    120 => { error_class: 'ConfigurationError', error_message = 'Configuration error occured, e.g. terminal not configured properly. Check terminal settings.'},
                    200 => { error_class: 'CommunicationError', error_message = 'Communication with issuer failed, please contact support.'},
                    210 => { error_class: 'ConnectionError', error_message = 'Connection to issuer could not be established, please contact support.'},
                    220 => { error_class: 'AccountError', error_message = 'Issuer account data invalid, please contact support.'},
                    220 => { error_class: 'AccountError', error_message = 'Descption: Issuer account data invalid, please contact support.'},
                    230 => { error_class: 'TimeoutError', error_message = 'Issuer does not respond within given timeframe - please reconcile'}}

But when I run the code I get this error:
syntax error, unexpected '}', expecting => (SyntaxError)
...general system error occured.'},
...                               ^
/Users/response.rb:34: syntax error, unexpected '}', expecting =>
... request could not behandled.'},
...                               ^
    /Users/response.rb:41: syntax error, unexpected '}', expecting =>
... timeframe - please reconcile'}}
...                               ^
/Users/response.rb:45: class definition in method body
    /response.rb:80: syntax error, unexpected end-of-input, expecting keyword_end
    from /Users/.rvm/rubies/ruby-2.2.2/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:55:in `require'

What is the proper way to implement this code?
Basically I want to compare values from hash into hash.
Comment: Hm, you literally would have spent significantly less time on figuring this out by actually reading the error message and taking a close look at a line which generated it, than you spent on composing this post. And it's the same with most of your questions (ruby ones, at leaat). Why you keep doing this, is a mystery to me. ¯\\_(ツ)_/¯
Comment: @SergioTulentsev: Typical for this poster. Then there are answer (or comments) and then... quiet... Check the number of downvotes on his questions (he is in the top 10 of most questions asked if I remember correctly)
Comment: @Kukeltje Hi dude, answering JSF question is not enough so you started Ruby also?
Comment: Learning JSF (or trying to) not enough? Ruby now also?
Comment: @Kukeltje yes sure
Answer: Replace every occurrence of = with : inside hash.
@system_errors = {100 => { error_class: 'SystemError', error_message: 'A general system error occured.'},
                101 => { error_class: 'MaintenanceError', error_message: 'System is undergoing maintenance, request could not behandled.'},
                110 => { error_class: 'AuthenticationError', error_message: 'Login failed. Check your API credentials.'},
                120 => { error_class: 'ConfigurationError', error_message: 'Configuration error occured, e.g. terminal not configured properly. Check terminal settings.'},
                200 => { error_class: 'CommunicationError', error_message: 'Communication with issuer failed, please contact support.'},
                210 => { error_class: 'ConnectionError', error_message: 'Connection to issuer could not be established, please contact support.'},
                220 => { error_class: 'AccountError', error_message: 'Issuer account data invalid, please contact support.'},
                220 => { error_class: 'AccountError', error_message: 'Descption: Issuer account data invalid, please contact support.'},
                230 => { error_class: 'TimeoutError', error_message: 'Issuer does not respond within given timeframe - please reconcile'}}

Answer: Error: error_message = '...'
Must be error_message: '...'
@system_errors = {100 => { error_class: 'SystemError', error_message: 'A general system error occured.'},
                101 => { error_class: 'MaintenanceError', error_message: 'System is undergoing maintenance, request could not behandled.'},
                110 => { error_class: 'AuthenticationError', error_message: 'Login failed. Check your API credentials.'},
                120 => { error_class: 'ConfigurationError', error_message: 'Configuration error occured, e.g. terminal not configured properly. Check terminal settings.'},
                200 => { error_class: 'CommunicationError', error_message: 'Communication with issuer failed, please contact support.'},
                210 => { error_class: 'ConnectionError', error_message : 'Connection to issuer could not be established, please contact support.'},
                220 => { error_class: 'AccountError', error_message: 'Issuer account data invalid, please contact support.'},
                220 => { error_class: 'AccountError', error_message: 'Descption: Issuer account data invalid, please contact support.'},
                230 => { error_class: 'TimeoutError', error_message: 'Issuer does not respond within given timeframe - please reconcile'}}

Get values from hash in hash


QTimer Slot not being fired from Library function

Question: I have a main Qt Application and I am developing a Qt Library that I link to from this Main Application. From the Main Application I wish to call a function in the library that will do something, and then at the end of the routine call a QTimer which will fire off a Slot in the library code after some delay. I cannot get the timer to fire and I am not sure why. If I place a timer in my Main App, then it fires as expected, just not in the library.
For now, my library is just one class. In my library header file I define the slot I wish to call as:
<code>private slots:

        void stop();
</code>
In the implementation file I have this:
<code>    void MyLib::start() {

        // Create a timer to user during audio operation
        m_GeneralTimer = new QTimer(this);

        // Fire off a oneshot to clear the buffer for fluke-media
        m_GeneralTimer->setInterval(3000);
        m_GeneralTimer->setSingleShot(true);
        connect(m_GeneralTimer, SIGNAL(timeout()), SLOT(stop()));
        m_GeneralTimer->start();
    }
    void MyLib::stop() {

        qDebug() << "Called stop()...";
        m_GeneralTimer->stop();
        delete m_GeneralTimer;
    }
</code>
What am I missing here for the timer to fire?
NOTE: Here is alot of my header file - everything after this in the real file is just function calls:
<code>/// Use shared memory
#include <QSharedMemory>

/// Normal Qt Includes
#include <QBuffer>
#include <QDebug>

/// QTimer is required for calling a method
/// to stop audio playback at a later time
#include <QTimer>

/// Put into a background thread
#include <QtConcurrentRun>

/// Check integrity of received data
#include <QCryptographicHash>

class MYAUDIOLIBSHARED_EXPORT MyLib: public QObject
{

    Q_OBJECT

    public:

            /// /// ///

    private slots:

            void stop();

            /// /// ///
}
</code>
Comment: Do you have a Q_OBJECT macro in your MyLib class?
Comment: Yes I do - in my header file
Comment: Could u add ur .h file here?
Answer: Well the following code works. I put 3 seconds in the start() function and now it fires off from the library call.
<code>    // Create a timer to fire a slot when the playback is done
    m_EndPlayBackTimer = new QTimer(this);
    m_EndPlayBackTimer->setInterval(3000);
    m_EndPlayBackTimer->setSingleShot(true);
    connect(m_EndPlayBackTimer, SIGNAL(timeout()), SLOT(playBackDone()));
    m_EndPlayBackTimer->start(3000);

    // Done
    return;

}

/**
 * @brief
 * Slot to be started by a timer after some time delay
 * to signify that the playback is complete.
 *
 */
void MyLib::playBackDone() {

    #if DEBUG
    qDebug() << "Playback is complete...";
    #endif

}
</code>


Update a PRIMARY ID field with auto increment

Question: MSQl question:
I have a web page the has a number of fields going against a msql database.
3 tables:
1. ID = primary key, INT. Auto Increment
2. Name = text field,
3. Address = text field
On that web page I'm showing all fields, but only fields 2,& 3 can update and not the PRIMARY KEY. basically, I see the issue that trying to overwrite a field that is auto generating is probably the problem. But I need the auto increment because on another web page I'm adding a record that the product web page gets the record and displays it online.
Question; Is there a way to (OVERWRITE) update a PRIMARY ID KEY field that is auto incremented?
Answer: You can easily update a record with a primary auto_increment key just like any other field, but the values must remain unique.
Comment: Thank you for your answer. However, that does not help me in this instant. Perhaps I was not very clear. If I can update 2 out three fields and the main primary key if the one not updating when displaying on the web page but the others do. I managed to make sure the data and the field i unique. But when I add a new data text in that field of the PRIMARY ID it does not update. Very puzzling...


What is this lightbulb and how do I change it?

Question: The lightbulb pictured below is in a ceiling lamp fixture in the United States and is probably original to the house, meaning approximately 1985 vintage.
There is no lettering or labeling I can see on the bulb, just the faint bossing on the lamp itself ("Nadair"?) to identify it.
The glass is fairly small, no more than a few inches long, much less than an inch wide.  There is no obvious direction to tug or twist it that releases it, although I've been reluctant to pull hard for fear of breaking it in my hand.  (On that note, this fixture is old and it took quite a bit of brute force to pry the one extendable claw out to release the cover.)
The white plastic pieces seem to be part of the fixture itself.
What is this thing, and what is the trick to removing it?
It has now been removed, and is the subject of the third image and the new question, "Did I break this thing?"  But I can get it to a hardware store, now, which is more than half the battle.
Comment: Totally off topic, but I keep thinking of *"how many X does it take to change a light bulb"* jokes :)
Comment: With a Kleenex otherwise the oils from your hands degrade the bulb.
Comment: Related question: https://diy.stackexchange.com/questions/63208/how-do-i-remove-a-double-ended-t3-r7s-bulb-that-isnt-spring-loaded
Comment: You would find one of those bulbs in any "dorm-room special" floor-standing torchiere lamp sold in the 1990s, and in fact the circular hole in the bracket located _above_ the bulb (along with the fact that it's clearly mounted off-center from the ceiling box, and was never meant to be used with one) makes me think this fixture was repurposed from one of those. (Edit: Maybe not off-center. That weird screw/protrusion at the very top of the first photo threw me off. ...Still ghetto-looking, tho. Replace the fixture!)
Answer: It's a double-ended halogen lamp. Looks a lot like a T3 size but I'm having trouble locating a picture of one so short in length as yours appears.
The ceramic blocks at the ends of the lamp conceal a spring loaded terminal. Push the lamp sideways (along its axis) toward one of the blocks, then lift the opposite end of the lamp out of the holder.
Sometimes the fixture terminal and the lamp terminal can stick together. You could try twisting the lamp just a little or inserting some tool into the end block to help separate them.
One might argue this is all a bit academic.. replace the entire fixture with a quality fluorescent or LED model!
Comment: do not touch the new one with bare hands ... skin oils will kill it
Comment: If you can spare half an hour I would still consider replacing it with a LED fixture, the electricity saved alone will already make it worthwhile.
Comment: @Reader If it's actually a standard size like the 78 mm R7S, you can just go buy a compatible LED bulb, no need to replace the whole fixture.
Comment: Yes, 100% go LED!  Incandescent fixtures, especially halogens, in addition to just being wasteful, make SO much heat.  I can't count the number of crufty old octo-boxes I've seen where the wires have been so heat-scorched by halogen or incandescent bulbs that the insulation just shatters like glass - it makes a real mess to sort out if you ever want to change the fixture.  Best to nip that problem in the bud and use a cool lamp like an LED instead.
Comment: Shopping is off topic here, but just to address the budget comment. I searched Amazon for ceiling light fixtures, and a UL listed LED fixture (or one for traditional screw in lamps, which can use LED "bulbs") aren't much more than I think you'd pay for that halogen bulb.
Comment: Halogen bulbs get really hot.  Make sure it is cool before following @Greg Hill's clear advice.
Comment: That worked, although I'm not sure if I broke it.  Hopefully I'll have it identified tomorrow, at a hardware store if need be.  And while I'm tempted to replace the fixture, that's not in my time budget right now.
Comment: @TimB I can pick up one of these halogens for AU$2.25. Pretty sure you'd be hard pressed to find a fixture and LED lamp for anything close to that price :)
Comment: @Corey - And I can't imagine that you would be able to find a CF or LED replacement that could come anywhere NEAR the brightness of a halogen bulb...
Comment: You can get fairly bright LED ceiling lights tbh. I have a pair of 12 watts in my living room that come in handy when in need of floodlights.
Answer: Just to add a bit of terminology info from the web to Greg's excellent answer:

T type halogen bulbs feature the letter "T" to indicate their tubular shape, followed by a number which specifies the tube's diameter.in eighths of an inch. For instance, a T3 bulb is a tubular halogen bulb which has a diameter measuring 3/8ths of an inch.

An R7S is a double ended, recessed single contact (RSC) linear halogen lamp measuring either 118 mm or 78 mm. Some less common lengths are 189 mm, 254 mm and 331 mm. These lamps have a T3 shape on an RSC/R7S base. These can also be known as J type and T type lamps. (From an Amazon QA comment)

Your bulb looks like it's probably 78mm long. BTW, yes, the photo shows a broken bulb.
Also, it's VERY important to make sure the wattage of the bulb is lower than the safe limit for the fixture -- otherwise a fire can result, as these bulbs get VERY hot.
Comment: If the ceramic ends broke off when removing the bulb, it's possible that the fixture was also damaged in the process.  I'd recommend a careful inspection of this before replacing the bulb.  If the fixture is at all damaged, that's another point in favor of replacing it with a fluorescent/LED fixture.
Comment: @TooTea Thanks for catching my mistake, I meant 78mm. OP's photo shows the ceramic ends broken off and it looks to me that with them in place it would be slightly over 3 inches. I could be wrong.
Comment: I also thought it's an R7S,but OP's photo shows it to be a little under 3 inches long. That's nowhere near 118 mm, actually not even 78 mm. If it was any of these common sizes,OP could easily buy a drop-in replacement LED bulb.
Answer: Last time I bought halogen bulbs like that, 1000bulbs dot com.
If that's a 100W bulb (1000bulbs carries 100W, 150W, 250W), it's $2 (for the bulb; considerably more for the power to run it, if it sees significant use; an enormous amount more if you have a fire):
Plusrite 3350 - 100 Watt - T3
Handle the new bulb only with a clean tissue or equivalent, to avoid skin oils damaging the bulb.
I would not worry excessively about the ceramic ends breaking off of the old bulb, though do inspect the fixture prongs for corrosion and wipe them clean.  The bulb obviously gets extremely hot during operation, but transfers a limited amount of heat to the socket.
Inspect the fixture prongs with the breaker off; no guarantee that mis-wiring doesn't have 120V on one end.
I second the "put in an LED fixture if you can" comments.  You will save money and it will be safer, unless you need the heat for some reason.
Comment: +1 for the heat point - sometimes it is useful.


Running Elasticsearch on Ubuntu on WSL: "System has not been booted with systemd as init system (PID 1). Can't operate."

Question: I'm using WSL on Windows 11 (with Ubuntu 22.04 LTS) and trying to use Elasticsearch on it. When I run
sudo systemctl start elasticsearch.service, I get the error:

System has not been booted with systemd as init system (PID 1). Can't operate.

I understand systemctl is not available on WSL. So, I tried its alternative, service elasticsearch start, but then I get the error: elasticsearch: unrecognized service.
I understand there's been similar phrased questions on this website but I have already tried the alternative command but it's not working. So, please help how I can resolve this issue.
Comment: Elastic's response to this issue: https://discuss.elastic.co/t/how-do-you-configure-elasticsearch-on-ubuntu-bash-for-windows-10/194888/3 . This is an Elastic issue, not an Ubuntu issue.
Comment: Sorry, retracted that last comment - I see that even the unit file points to a systemd dependency.  There's probably still a way to run it manually, but it isn't necessarily obvious from the unit file.
Comment: Well, I installed elasticsearch 7 and it's working now. It was giving the problem on version 8
Comment: Writing up an answer now for 8.4.1 if you're willing to use Docker.
Comment: Also would recommend you add a self-answer for the "use version 7" option.
Answer: While I'm sure it's possible to bring Elasticsearch up directly on Ubuntu on WSL, (a) I haven't done it, and (b) there's likely an easier way.
Elasticseach provides a Docker image with all dependencies.
To install and run it, I used a slightly modified form of the Elasticsearch doc for WSL:

Install Docker Desktop for Windows

Restart Ubuntu

Increase the mmap limits with:
sudo sysctl -w vm.max_map_count=262144

See this Stack Overflow question/answer for information on how to persist this.

Create a Docker network for Elasticsearch with:
docker network create elastic

Start Elasticsearch with:
docker run --name es01 --net elastic -p 9200:9200 -p 9300:9300 -it docker.elastic.co/elasticsearch/elasticsearch:8.4.1

The first time you run it, it will pull the images as well, so there will be a slight delay.  This won't occur on subsequent runs.

Make a note of (i.e. copy to Notepad or something else) the tokens that are displayed, as they will start to scroll off the page once other operations start to occur (e.g. you run Kibana).

Run Kibana in a separate Ubuntu on WSL session (e.g. new tab in Windows Terminal) via:
docker run --name kib-01 --net elastic -p 5601:5601 docker.elastic.co/kibana/kibana:8.4.1

When done, remember to clean up old containers with:
docker ps --all
docker remove <exited_container_name_or_id>


Leaking joint/pipe. What product to use?

Question:
Our "plumber" drilled hole in main down pipe (plastic) instead of in the ceramic main out pipe (Black). Probably good that he didn't touch that!
Anyway, the product he used to seal the "joint" has degraded over last two months, and is now leaking. Short term, I need to re-seal. Wondering if anyone can tell me what product to use?
The flexi pipe is the out from the washing machine.
Many thanks
Comment: Get him back to do it properly.
Comment: That is a TOTALLY inappropriate way to connect a washer drain line to a waste pipe!  Even if it wasn't leaking, that could allow waste to backflow into your washer and possibly overflow it.  Either FIX it or get it fixed by a real plumber.  Whoever did this was incompetent!
Comment: This gives hack jobs a bad name.  The best product to fix this is called "NEW PLUMBER".
Comment: Hello, and welcome to Home Improvement. I've given a somewhat vague answer; if you add more pictures/diagrams of your setup then someone can probably give you a better one. And, props for [taking our tour](//diy.stackexchange.com/tour) before posting; few newbies do.
Answer: As others have said, fixing this isn't a "get the right stuff to apply to the join" situation, but a "completely redo the join using the correct method" situation. Your plumber did a complete hack job; you risk sewage leaking into your home, as well as backflow into your (I'm guessing) washing machine. And, any sort of caulk you apply will only work temporarily. And, what happens when you want to move the washing machine for service?
If this was done by a "real" plumber, then you should definitely get them back to do it right.
(I don't have the chops to recommend a full fix; perhaps someone else will add an answer that does.)


What is the payout date for commercial applications?

Question: What date are commercial developers paid for their sales? I thought it was quarterly, but it's been about 4 months since my first sale and I haven't been paid.
NOTE: I sent canonical an email, I'll post an answer when I get a reply.
Answer: As noted in the Developer Agreement, payments happen within 30 days of the end of every calendar quarter. If it has been 2 calendar quarters since payment it is likely that we sent you an email requesting information to which you did not respond or the only charge was due to our end to end testing of your app.
You can send me an email at john dot pugh at canonical.com with the application name and I can ensure we have the proper information to process your payment.
Answer: As Zoopster noted, I needed to supply my last name, however, I don't think I got an email about it until my inquiry.
The issue has been resolved now that all required personal information is supplied.


How to repair broken grout in shower tile?

Question: Just moved into this house a few months ago, and noticed the stub wall in the shower that holds the controls has cracked grout.
I'm guessing that somehow water got in behind the tiles and started to swell the supporting studs, which blew out all of the grout in the area.
What should I do to fix this?

You can see the tile is separating perpendicular to its surface.

Here too.
Answer: It looks like the problem is not just the grout (which fills the gap between tiles) but also may be the tile adhesive is separating from the supporting structure (possibly plasterboard/drywall).
You can remove grout from between tiles using a variety of tools designed for this purpose. Then you can re-apply grout (and sealant if needed)
It seems likely that water has penetrated that structure, it might be best to open it up and assess what damage has been done and how the water got in.
In your case you may need to remove all the tiles, repair the supporting structure and re-tile. It's the only way to get the tiles to align neatly at the corners.


A^N - B^N = C, A,B,C are known, solve for N

Question: As title says:

$$A^N - B^N = C,$$
  $A,B,C$ are known, solve for $N$.
  This is substracted from a bigger formula where this N is one of the parameters to be calculated.

I have tried it with:
$$X = A^Y \Rightarrow Y=\frac{\log(X)}{\log(A)}.$$
But this doesnt work for this version. I have been stuck on in for 8 hours already and a solution would really help me out. By calculating it by myself I tried the following: $A = 5$, $B = 2$.
For $C = 3$, $N = 1$.
For $C = 21$, $N = 2$.
For $C = 117$, $N = 3$.
But that's with simply filling in $N$. Which is not allowed since I need to find it by a algorithm/formula for a vision project.
Sorry for duplicate.
Answer: You won't find a nice algebraic formula for general parameters.  It looks like you are restricting $A,B,C,N$ to natural numbers-are you?  You can do pretty well by ignoring the $B$ term to start, so take your first try to be $N=\left \lceil \frac {\log C}{\log A}\right \rceil$ then just count upward for $N$ until you find the one that is right.  If you don't restrict $N$ to naturals, you want a one dimensional root finder.  You have a good first guess (take off the ceilings).
Added:  for a very simple approach in the reals, not as fast as Newton-Raphson but easy to program, take $N_0=\frac{\log C}{\log A}$, then $N_{i+1}=\frac {\log C-B^{N_i}}{\log A}$ and iterate to convergence.  If $N$ is reasonably large $B^N$ will be well less than $A^N$ this should converge nicely.
Comment: For the first calculations I indeed only tried it with natural numbers, so i could calculate them easy myself. In the case where it will be used every number can be a real number. The problem with counting upward is the size of the count, which can in-/decrease but can take a while because of precision.
Comment: That is why you want a root finder in the real case.  Once you try a couple cases, it uses the error of those to evaluate the next step.  This problem should yield easily to [Newton-Raphson](http://en.wikipedia.org/wiki/Newton's_method_in_optimization)  You have a good starting value-use the equation above without the ceiling.


Consecutively Adding Sines

Question: One thing, I'm not a mathematician so please be patient. I am still in Algebra II Trig. Leading with that, why does
$$ x_0 = \sin 1,
\space
 x_1 = x_0 + \sin x_0,
\space x_2 = x_1 + \sin x_1 ... $$
and after a while,
$$ x = \pi $$
I know this to be true because I have evaluated this on my TI-84 and more deeply evaluated it with this program I made:
https://repl.it/@RobertoBean/Pi-Evaluator
To $100000$ Iterations (which I believe is enough)
So what's the math behind it? Why does adding $\sin 1$ in this manner produce $\pi$? Why doesn't doing the same thing using $100$ produce $\pi$?
For example,
$$\sin(1) = 0.841470...,\space \sin(1) + \sin(0.8414...), \sin(1) + \sin(0.841470...) + \sin(1.587095126...),\space ... $$ $$ = \pi$$
My question is different from the mentioned because my function is not taking the sin of a sin consecutively, but is this following function: $f(x) = x + \sin x$ and is not $f(x) = \sin x$ and therefore can exhibit different properties I need explained.
Comment: $x = x + \sin x \iff \sin x = 0$.
Comment: Does it? Where did you find this?
Comment: You are iteratively evaluating the map $x \mapsto x + \sin(x)$, and discovering that this map has a fixed point (i.e. there is some value of $x$ such that $x = x + \sin(x)$).  There are some thorny issues of convergence, but assuming that everything plays nice, you get
$$ x = x + \sin(x) \implies 0 = \sin(x) \implies x \in \{ \pi k : k\in\mathbb{Z} \}.$$
Comment: $\sin\left(1\right)+\sin\left(\sin1\right)+\sin\left(\sin\left(\sin1\right)\right)+\sin\left(\sin\left(\sin\left(\sin\left(1\right)\right)\right)\right)+\sin\left(\sin\left(\sin\left(\sin\left(\sin1\right)\right)\right)\right)>pi$
Comment: One drawback, @quasi, is that your edit masked the fact that the OP is unfamiliar with the notions of sequences and convergence (that would be an important information in answering this question IMO).
Comment: It is true for the recurrence $$
\left\{ \matrix{
  x_{\,0}  = \sin (1) \hfill \cr
  x_{\,n}  = x_{\,n - 1}  + \sin (x_{\,n - 1} ) \hfill \cr}  \right.
$$ so rewrite your post accordingly
Comment: You can have a look at [Fixed-point iteration](https://en.wikipedia.org/wiki/Fixed-point_iteration) and maybe try to draw corresponding [cobweb plot](https://en.wikipedia.org/wiki/Cobweb_plot). Here are [some examples for other functions](https://chat.stackexchange.com/rooms/14150/conversation/pictures-illustrating-iterations-for-x-n1fx-n).
Comment: The contraction mapping principle asserts that if there is some $c \in (0,1)$ such that $|f(x) - f(y)| < c |x-y|$ on some compact domain, then the mapping $x \mapsto f(x)$ has a unique fixed point.  We would like to apply this to the mapping $x \mapsto x + \sin(x)$.  Unfortunately, this is not a contraction mapping on all of $\mathbb{R}$.  Indeed, it has many fixed points, each corresponding to a different domain where it is a contraction mapping.  [This is somewhat illuminating](https://www.desmos.com/calculator/w7hduxr4i8).
Comment: @John Yes. I think it means that if I have a number that falls between $number * \pi$ and $(number + 2) * \pi$ the result will be $(number + 1) * \pi$ So 50 will be $15\pi$ I think the arrows mean there is an attractive force towards those places, hence the name attractor? Almost like the numbers start to change round those points to try and be closer to $n\pi$. Am I right?
Comment: @supersmarty visit the link
Comment: I never knew $\pi \approx 97.389372261283597254077903926372528076171875$, that is what it output.
Comment: @idk Sorry, I rewrote the question. Did not convey what I was trying to say. Remember, only in Trig
Comment: $$\sin(1) = 0.841470...,\space \sin(1) + \sin(0.8414...), \sin(1) + \sin(0.841470...) + \sin(1.587095126...),\space ... $$ $$ = \pi$$
Comment: @idk also it output that because I made the starting value 100 and forgot to change it.
Comment: @Xander what does that mean, or where can I go to figure out what that means?
Comment: @GCab yes that was exactly what I was trying to ask, as long as the subscript n means where we are in the sequence, or more better put, how much we have added
Comment: @GCab However, $c=1$ and only one. Attempt the problem with 100
Comment: @coderboy: If $x_1\ne 0$, then $(x_n)$ converges to either $\pi$ or $-\pi$.
Comment: @quasi I think if $(x_n) \to \pm \pi$ then for $X_1 := x_1 + 2\pi m$ then $(X_n) \to \pm \pi + 2\pi m$.
Comment: @Ben: Oops, you're right.
Comment: @Coderboy I guess you can get $x$ closed to $\pi$, but probably not $x = \pi$.
Comment: @John Maybe if the function were iterated an $\infty$ amount of times. Not sure.
Comment: @John Ma: At the algebra-2 level, the student is likely to have been introduced to sequences such as the Fibonacci sequence. As far as convergence, geometric series and the related notion of convergence is usually introduced informally at that level.
Comment: @Coderboy: I was trying to help, but the intention of your post is now clear anyway, so no big deal.
Comment: @Coderboy: The main area of math that deals with questions like yours is called "Dynamical Systems". Recommended prerequisites are Precalculus, Calculus, Linear Algebra, and Differential Equations.
Comment: @quasi Where can I go to learn enough to understand answers to my question?
Comment: @Coderboy: I recommend waiting a bit (see my prior comment).
Comment: @quasi That's not what I was hoping for. I will come back and look at the answers to this when I am older, however.
Comment: Do you understand the answer by G Cab (The horizontal and vertical arrows in particular)? In some sense that is already a very good intuition. @Coderboy
Comment: Just realized I can do the same thing with cos and multiply the final result by 2 and get $\pi$.
Comment: @supersmarty1234: You applied the wrong formula. `x1` is `sin(sin(1)) + sin(1)`, `x2` is `sin(sin(1)) + sin(1) + sin(sin(sin(1)) + sin(1))` and `x3` is `sin(sin(sin(1)) + sin(1) + sin(sin(sin(1)) + sin(1))) + sin(sin(1)) + sin(1) + sin(sin(sin(1)) + sin(1))`. Sadly, it isn't as easy as your proposal.
Comment: Why is this question so popular? I thought it was just a casual math question, is there something else I'm missing?
Comment: @Coderboy: It's a simple question (and therefore easy to understand, even for non-experts) with several interesting and nontrivial answers. Those often tend to get a lot of upvotes. Also, with several quick and popular answers, it may have ended up on [Hot Network Questions](https://stackexchange.com/questions?tab=hot) list for a while.
Answer: So the sequence is
$$
\begin{cases}
  x_{0}  = c & \\
  x_{n}  = x_{n - 1}  + \sin (x_{n - 1} ) &
\end{cases}
$$
and this is what is going to happen.

The sketch shows that for  $0< x_0 < 2\pi$ the recurrence will lead to $\pi$,
for $2\pi< x_0 < 4\pi$ it will lead to $3\pi$,   etc.
That means that, among all the solutions $x=n\pi$ to $x=x+\sin(x)$, the actual attractor points are those at $(2n+1)\pi$, while the  $2n\pi$ points are unstable.
Comment: @Coderboy The reason for the fast convergence to $x_\infty=31\pi$ that you observed, is that, when $x\to x_\infty$, $f(x)-x_\infty\sim\frac16(x-x_\infty)^3$. Hence, after a while, the number of correct decimals is (roughly) multiplied by $3$ at each iteration.
Comment: exactly, but shall be strictly greater or lower: if you start with precisely $30\pi$ you will remain there (theoretically, numerically the computation error might you drift around or out).
Comment: Is this why when I run the function with 100 it returns $\approx 97.3893722612$?
Comment: @Coderboy: yes $$
\eqalign{
  & x_{\,0}  = 100\quad  \Rightarrow \quad \left\lfloor {{{100} \over {2\pi }}} \right\rfloor  = 15,\quad 100\bmod \left( {2\pi } \right) \approx 0.9\quad  \Rightarrow   \cr
  &  \Rightarrow \quad x_{\,\infty }  = 31\;\pi  \approx 97.38 \cr}
$$
Comment: so that means 100 falls between $30\pi$ and $32\pi$? I'm very intrigued.
Comment: I know that that is true because when I call the `int.binary()` method from the integer class in python it doesn't equal what I intend it to when doing math things. Basically, computers suck at doing math with decimals
Comment: @Coderboy: yes computers are very powerful, but can be tremendously misleading if not "handled" with much care!
Comment: @Coderboy: considering previous comment, it would be interesting to know which is the minimum number of iterations required to get a given accuracy.
Comment: @G Cab to get 50 decimal places matching the given value of PI, you need 5 iterations
Comment: @Did: thanks , I was curious to know an estimate of convergence speed
Answer: It seems the OP has a hard time understanding the answers referring to fixed point iterations - I do too. Here follows a more intuitive and practical way to visualise what OP's formula is doing is by using the arc length of the arcs on the unit circle.
Your angle measured in radians is equal to the arc length of a segment of that angle - let's call it $ø$.
$sin(ø)$ gives you the y-coordinate (distance from the x-axis) of the end of that arc with it's centre at the origin.
In your next step you are creating a new arc by lengthening your arc by $sin(ø)$ and then you measure the distance from the x-axis for the end of your new arc and you keep repeating this procedure.
The measured distance from the x-axis will always be smaller than the length needed to lengthen your arc to $π$ but it keeps getting closer.
The illustration below explains it graphically and it's also easy to see from this why it converges so quickly:

Edit:
The arc length of the remainder of the half circle not covered by your arc is $π-ø$. By inspection, you can prove that $sin(ø)$ will always be smaller than that arc length (except when $ø=π$), thus, continuously adding $sin(ø)$ and adjusting ø to this new value will never exceed $π$.
Similarly you can see that for any value less than $π$, the result will increase, until you reach pi (which will happen at infinity).
Comment: Yes! We studied this in algebra, I understand this!
Comment: So the closer I get to $180^{\circ}$ around a circle (I know that this is $\pi$ Radians), the smaller the value I am adding? This is why it converges on $\pi$?
Comment: Yes. I'll amend my answer shortly to clarify
Answer: You are iterating the function $$f(x)= x+ \sin(x).$$
When you iterate a function and the function has a fixed point which happens to be an attractor, the sequence of iterates approaches that attractor.
In the case of $$f(x) = x+\sin(x)$$ the fixed point is found by $f(x)=x$ which is $$x+\sin(x)=x$$
Thus $\sin(x)=0$ which implies $x=\pi$ is the attractor.
Comment: This is not entirely correct.  What do you mean by "happens to be an attractor"?  How do you know that this map has an attractor?  Is the attractor unique?  And, most importantly to the original questioner (it seems), why does iterating with $x_0 = 1$ give you $\pi$, while $x_0 = 100$ gives something else?
Comment: so because $\sin \pi = 0$, that means that x is $\pi$?
Comment: @Xander Oh yeah that's right. $f(x) = x + \sin x$ converges differently if $x_0 \ne 1$. I'm already learning :)
Comment: The x_0=1 is in the basin of attraction of the fixed point $x=\pi$  $x_0=100$ is probably in the basin of attraction of another attractor. The attractors do not have to be unique. For example if you apply Newton's Method to f(x)= sin(x), depending on  your initial condition you get different attractors.

Consecutively Adding Sines


Javafx growing memory usage when drawing image

Question: I'm creating a quite simple Go board game in JavaFX. I stumbled on growing memory usage in my application and after reducing everything unnecessary, it appeared that even the minimal example causes huge memory growth overtime, its about 50 to 100MB/s.
Here's the code:
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.stage.Stage;

public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
    Group root = new Group();
    primaryStage.setTitle("Hello World");
    primaryStage.setScene(new Scene(root, 600, 600));
    Canvas canvas = new Canvas(600, 600);
    Image bg = new Image("resources/images/background2.jpg", 600, 600, false, false);
    root.getChildren().add(canvas);
    GraphicsContext gc = canvas.getGraphicsContext2D();
    new AnimationTimer() {
        @Override
        public void handle(long l) {
            gc.drawImage(bg, 0, 0, 600, 600, 0, 0, 600, 600);
        }
    }.start();
    primaryStage.show();
}

public static void main(String[] args) {
    launch(args);
}
}

The problem doesn't occur when I delete the gc.drawImage line but that's, obviously, not a solution.
Btw. I'm using Arch Linux 64-bit with OpenJDK 8
Comment: Well, if that is really the whole program, then you want to add the missing parts to complete your class. "Almost complete" is still not [mcve]
Comment: What I dont understand: you are sure that the JavaFx parts are to blame? Did you do any kind of memory profiling to figure where your memory is spent on?
Comment: What you see above is the whole program. There's nothing more than that, so I don't know if there can be anything else than JavaFx that's not working.
Comment: Now I inserted everything what's in there.
Comment: What is your memory setting ? -Xmx ?
Comment: I would try out to insert `gc.clearRect(0, 0, 600, 600);` right before `drawImage()`. If it's a buffering issue with the canvas, this could fix it.
Comment: -Xmx is 512m according to Intellij's idea.vmoptions file (not sure if it's the project heap size though). @Calculator clearRect didn't help.
Comment: Does it actually run out of memory?
Comment: Have a look at [this question](https://stackoverflow.com/questions/40228866/optimizing-memory-leakage-in-javafx) too - it may be solved with new versions of Mesa and X.org
Answer: There are numerous bug reports about memory leaks in JavaFX on Linux.
For example JDK-8156051 or JDK-8161997.
To verify if you are hit by this bug try to run your program with -Dprism.order=sw and see if the bug persists.
Comment: My code seems to be affected by this bug as well. I am simply drawing a star field and scrolling it. So about 10-20 ovals drawn per second. On Linux this increases memory to over 16GB in about a minute. On Windows this runs perfectly fine. Setting `-Dprism.order=sw` fixed this for me. Thanks. (I was getting paranoid ^^)


Compilation of latex file

Question: I am compiling a latex file on a server and download from there the generated dvi, ps and pdf files to view them.
The latex file by \includegraphics includes some figure files which are not on my local machine. I found that dvi file generated by latex command does not show the figures after dowloaded to my local, but ps file generated by dvips -Ppdf have the figures, and pdf file generated by either ps2pdf or pdflatex seem not have the figures again. Is it because the figures are not actually embeded as part of the dvi and pdf files by those compilation commands? How to actually embed figures so we can only export the document files to other machines?
Are the case for tables in separated tex files included into main tex file by /input and the case for style files included by \usepackage similar to the above case for figure files included by \includegraphics ?
Answer: you should look at the warnings. i am sure there some, because for ps you will need eps pictures and for pdflatex you'll need png or jpeg (try compiling at your local machine first, e.g. with kile or the gedit plugin)
I am using kile's compile commands for pdf generation which works always fine (pics incl.). they use pdflatex for that.
Answer: it depends a lot on the format of your picture files, and how those formats are handled by the various tools you use to convert dvi -> ps -> pdf
If you product ps, the best is to provide your figures in eps (encapsulated postscript) format, compile with latex and use dvips.
If you want to generate pdf, then provide your fgure in pdf or png format, and use pdflatex.
See
http://en.wikibooks.org/wiki/LaTeX/Importing_Graphics and
http://amath.colorado.edu/documentation/LaTeX/reference/figures.html
for good explanations of what happens.
The output of the latex command can be very informative about whant happens with your figures too.
Answer: Background
Embedded images, like eps files, are not supported in Knuth's original dvi specification — not surprising since dvi is an older format than Postscript; instead, they are encoded using an extension capability that is accessed in Tex through the \special command and in dvi by some reserved codes.
dvips set a standard for how to use specials, which gave a very flexible means for including Postscript facilties in Tex, but not all dvi utilities fully support these.
Answer, part one: where are the figures?
All figures imported using \includegraphics are encoded in the dvi as Postscript using the \special code, so to the first part of your questions - yes, the image content is all in the dvi file.  So you don't need to worry about where the files are that were used to generate the dvi.
However, different programs that process the dvi can do flaky things.  dvips is the standard, and it's based on ghostscript, which has seen various kinds of flakiness over the years.  Other dvi software has simply not supported specials, or supported them oddly.
Answer, part two: fixing things
Why do you think the figures are missing?  Have you looked at the files in an on-screen viewer, or have you printed them out?  It can often be that an on-screen viewer is flaky; that is rarely the case with the print-out.
Otherwise, look at the bug tracking systems for the various bits of software you are using.  I've found pdftex insulates me from a lot of these issues; I've found ghostscript bugs to be particularly annoying to deal with over the years.  Adobe Acrobat is clunky, but it is the standard and it's good for troubleshooting ps/pdf issues.  Try other software.

Compilation of latex file


Loading a page into a dialog with ASP .Net Buttons doesnt fire button click event

Question: I am loading a page into a jquery dialog.
    $(document).ready(function() {
        var $loading = $('');

        var $dialog = $('

').append($loading);
        var $link = $("#<%=lnkCustomise.ClientID %>").one('click', function() {
            $dialog.load($link.attr('href'))
                   .dialog({
                      title: $link.attr('title'),
                      width: 500,
                      height: 550
                    });

            $link.click(function() {
                $dialog.dialog('open');
                return false;
            });

            return false;
        });
    });

The aspx page has 4 buttons.when I click on the buttons it shows me error.
Server Error in '/projectname' Application.
The resource cannot be found.
I want to fire the server side click event of the buttons to perform some functionality.
Please suggest.
Comment: Please reformat your code so that it's readable!
Answer: This is what you are looking for i guess
__doPostBack('<%= UniqueIdOfBtn %>', '');

Comment: Inside  tags