How to Resize a Canvas in UWP

Question: I have a view that extends Canvas.
Such view is positioned inside another Canvas.
public class MyView : Canvas
{
  //this is my view
}

protected override void OnNavigatedTo(NavigationEventArgs e)
{
  PointerEventManager manager = new PointerEventManager(); // utility to manage the resizing event...
  MyView myView = new MyView();
  myView.PointerPressed += manager.OnPointerDown;
  myView.PointerMoved += manager.OnPointerMoved;
  myView.PointerReleased += manager.OnPointerUp;
  Canvas parent = new Canvas();
  parent.Children.Add(myView);
  // other stuff...
}

I want the user to be able to resize myView.
Note that such view should also be draggable by the user, and this is the main reason I want such view to be a Canvas.
The code for the method manager.OnPointerMoved looks like this:
protected void OnPointerMoved(object sender, PointerRoutedEventArgs e)
{
    myView.Width = myView.Width + 15; // enlarge by 15 pixel the width
    myView.Height = myView.Height + 50; // enlarge by 50 pixel the height
}

To change the Width and Height of myView is not working.
What can I do to properly resize myView?
Answer: You could simply use GridSplitter provided in Microsoft community toolkit sample.
I placed a canvas inside a Grid. The size of canvas can be modified by grid splitter and Yes the canvas is draggable. Nuget Package

<Page
    x:Class="App1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
    x:Name="YourPage"

    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid x:Name="RootGrid"
        Margin="48"
        BorderThickness="0,0,1,1"
        BorderBrush="{ThemeResource SystemControlHighlightChromeHighBrush}"
        Height="500"
        VerticalAlignment="Top">
        <Grid.RowDefinitions >
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
        </Grid.ColumnDefinitions>

        <Canvas Background="Red" CanDrag="True" ></Canvas>

        <controls:GridSplitter
            GripperCursor="Default"
            HorizontalAlignment="Right"
            Grid.Column="0"
            ResizeDirection="Auto"
            ResizeBehavior="BasedOnAlignment"
            CursorBehavior="ChangeOnSplitterHover"
            Width="16">
            <controls:GridSplitter.RenderTransform>
                <TranslateTransform X="-8" />
            </controls:GridSplitter.RenderTransform>

        </controls:GridSplitter>

        <controls:GridSplitter
        Grid.Row="0"
        Grid.ColumnSpan="1"
        VerticalAlignment="Bottom"
        Height="16">
            <controls:GridSplitter.RenderTransform>
                <TranslateTransform Y="-8" />
            </controls:GridSplitter.RenderTransform>
            <controls:GridSplitter.Element>
                <Grid>
                    <TextBlock HorizontalAlignment="Center"
                         IsHitTestVisible="False"
                         VerticalAlignment="Center"
                         Text=""
                         Foreground="White"
                         FontFamily="Segoe MDL2 Assets">
                    </TextBlock>
                </Grid>
            </controls:GridSplitter.Element>
        </controls:GridSplitter>
    </Grid>
</Page>

Answer: For the sake of who will bump into this question in the future, I managed it using a RelativePanel rather than a Canvas.
With that I can move&drag changing Margin property, and resizing using Width&Height properties.
Answer: I see several problems with your code.
Firstly, you didn't set the Background of MyView (you didn't mention). So, it's null, thus, it won't catch any PointerEvent. So, that's there.
Secondly, if you pass the first problem, yet,  you didn't set the Width and Height of MyView. If that's the case, both of them are NaN, which will prevent any of these two line from working:
myView.Width = myView.Width + 15; // what's NaN + 15 ?
myView.Height = myView.Height + 50; // huh ?

And at last, regarding

Note that such view should also be draggable by the user, and this is
  the main reason I want such view to be a Canvas.

Well, you can utilize the Margin property of any FrameworkElement to specify it's position in it's parent's layout.

How to Resize a Canvas in UWP


Render node fields in the views-view--[view_machine_name].html.twig

Question: I have a view called customfeedview showing contents of a content type viz. customfeeds.
View Setting are given in the picture below:

I created views-view--customfeedview.html.twig to customize the view. Code of the file is given here under.

{{ fields.title.content }}

{{ fields.body.content }}

But {{ fields.body.content }} & {{ fields.title.content }} does not render title and body of the contents of type customfeed.
Please help me in this issue as I am totally a beginner in drupal 8. Thank you...
N.B.: Here I am using show-type content instead of fields as only show-type content only give read-more option in the view page. Using show-type fields {{ fields.body.content }} is working fine but whenever I changed it to content {{ fields.body.content }} is not rendering the values.
Comment: Educated guess, when using `Show: Content`, try `{{ content.body }}`
Answer: You can call the node field in the view template
 node.field_(your-field).value

This will print the html tags as well, If the node field has the html structure.
node.field_(your-field).value | raw (or) node.field_(your-field).value |render|striptags

This will clean the html structure and useful to print the node value inside the view.template
NOTE: using node. instead of content. , because content. will be used only the node.html.twig


Meaning of ₵ symbol on guitar sheet music

Question: I have the following sheet music excerpt for Spanish guitar:

What is the meaning of the ₵2 and C3 on the 2nd and 4th measures?
Answer: I haven't seen those symbols in that context before, but they must mean that you use your first finger to barre the indicated fret (fret 2 in the second half of the first bar, and fret 3 in the third bar).
Comment: This makes a lot of sense. Barring the fret is the easiest way to hit the chords in the first chord. I suppose the crossed C indicates half barre (strings E,B,G) and the uncrossed C indicates a full barre.
Comment: The C with a slash through it is also noted as 1/2 C, e.g. 1/2 C5 is a partial barre in the 5th position.
Comment: @RenanGemignani: Yes, smart that you figured out the half vs the full barre; I'm sure that's the difference between those two symbols.
Answer: The symbols in question represent in fact barre chords. The numerals following the C indicates the position (i.e., fret) of the barre chord. As OP already has figured out, ₵ refers to a partial barre chord—it does, however, not indicate how many strings should be barred.
A nice overview of the many different styles to notate barre chords is given in the respective Wikipedia article.
Comment: This is the correct answer.
Comment: The notation rarely spoonfeeds yo by telling you how many strings to bar


How to show preview of entered values in previous steps in webform with multiple steps

Question: I am configuring a "Webform". In my webform field components, I am using "page break" in order to create Multiple step forms.
But I like to show the entered value in previous steps in current step.
for example, if user is in step 2, I want to print entered value of step 1 bellow the form.
or if user is in step 3, I like to print the entered value of step 2 and step 1 bellow the form.
is there any module to run this scenario? or I have to program a custom module?
Please guide me.
Thanks a lot
Answer: You can try Webform Bonus Pack module, it have the option to preview webform fields before submission.

which allows you to add a summary component directly to your form in
  the same way you would add a textfield or any other component type.
  Install that module and add a summary field to your form, selecting
  which fields you would like to include in the summary. If you would
  like it on its own page, make sure to add a pagebreak component first.

also take a look at this https://drupal.org/node/435232
Comment: Dear Bala, I have another question, IF I use your mentioned module, can I have this summary in every step of form (I mean every page) or I can have it only in end step (page)?
Comment: @Mehrdad201 not sure and I'm not using this module before, have a try and but I think you can show for each step.
Comment: Ok, I will try it asap
Comment: I tested it. It works fine. In every page I can have a summary from selected fields. Thanks a lot Bala.


Domain Still Points to Old Server After Deleting Account

Question: Yesterday, I set up an account with 000webhost.com along side with a free domain name from dot.tk. I found out that my WordPress site's Admin is only compatible with >= PHP 5.3 and the server doesn't allow you to change the default PHP version (5.2.14) to 5.3. So I switched to 1freehosting.com because they allow you to use up to PHP 5.4. Now the domain still points to a 404 page on the 000webhost server. I changed the DNS servers on my dot.tk domain to point to my 1freehosting account. How long will it take for the changes to happen?
Answer: It will take however long it takes for your cached record to expire on any resolver that has it cached. The TTL is a good estimate, but some DNS servers don't respect TTL.


Eigenvectors of a circulant matrix

Question:
Show that for the circulant matrix
$$C =
\begin{bmatrix}
c_0     & c_{n-1} & \dots  & c_{2} & c_{1}  \\
c_{1} & c_0    & c_{n-1} &         & c_{2}  \\
\vdots  & c_{1}& c_0    & \ddots  & \vdots   \\
c_{n-2}  &        & \ddots & \ddots  & c_{n-1}   \\
c_{n-1}  & c_{n-2} & \dots  & c_{1} & c_0 \\
\end{bmatrix}$$
the eigenvectors are
$$v_j = \left(1,w_j,w_j^2,...w_j^{n-1}\right), \qquad j=0,1,..,n-1,$$
where $$w_j = \exp\left(2\pi i j/n\right)$$ is the $n$-th root of unity. Show that the $\left(v_j\right)$ are linearly independent.

To show that the $v_j$ are eigenvector the only way I know is to solve the difference equation associated to the characteristic polynomial of $C$ to get a unique eigenvalue $\lambda$. Then find $\text{ker}\left(C-\lambda I\right)$. Is there an another way?
As for linear independence, I don't see how to reduce the matrix $\{v_j\}$ whose column are the eigenvector $v_j$.
Comment: Well, there is still the good old way: check that $Cv_j=w_jv_j$ directly.
Comment: My previous comment was irrelevant, sorry, I deleted it (the eigenvaluews are not necessarily pairwise distinct without further information on the $c_k$'s). To prove linear independence, you can use VanderMonde determinant, for instance: http://en.wikipedia.org/wiki/Vandermonde_matrix
Comment: The eigenvalue of $v_j$ is $c_0+c_{n-1}w_j+\ldots+c_1w_j^{n-1}$. To check that, all you have to do is compute $Cv_j$ and factor out $w_j$ on the second coordinate, $w_j^2$ on the third coordinate and so on... Using of course that $w_j^n=1$.
Comment: Note that the eigenvalues are given here, for instance: http://en.wikipedia.org/wiki/Circulant_matrix
Comment: @julien For linear independence, I didn't realized the eigenvalues were distinct, thanks. For the good old way, say the first row of $w_jv_j$, I don't see how to show: $c_0+\sum_{x=1}^{n-1}c_{n-x}w_j^x=w_j$.
Comment: @julien I had the wrong eigenvalue, with the right one I can show $Cv_j=w_jv_j$. I didn't know the VanderMonde determinant. Your comments are helpful, thank you.
Answer: I can give you a brief outline  of an alternative way to do it.
Consider the following matrix.
$$ \quad Q=
\begin{pmatrix}
 0 & 0 & \dots & 1 \\
 1 & 0 & \dots & 0  \\
 0 & 1 & \dots & 0 \\
 \vdots & \vdots & \vdots & \vdots \\
 0 & 0 & \dots & 0\\
\end{pmatrix}
$$
First show that $$ p(Q)= c_{0}Q^{0} + c_{1}Q^{1} + c_{2}Q^{2} + \dots + c_{n-1}Q^{n-1}= C$$
Then using the DFT matrix F, it can be shown that :
$$ FQ^{m}F^{-1}=
\begin{pmatrix}
 1 & 0 & \dots & 0 \\
 0 & \xi^{(m \bmod n)} & \dots & 0 \\
0 & \vdots & \xi^{2(m \bmod n)} & 0 \\
 \vdots & \vdots & \vdots & \vdots \\
 0 & \dots & \dots & \xi^{(n-1)(m \bmod n)}\\
\end{pmatrix} = D_{m} \\  \\
$$
The final step is:
$$  Fp(Q)F^{-1}
= \quad \quad
\begin{pmatrix}
 p(1) & 0 & \dots & 0 \\
 0 & p( \xi) & \dots & 0 \\
0 & \vdots & p( \xi^{2}) & 0 \\
 \vdots & \vdots & \vdots & \vdots \\
 0 & \dots & \dots & p( \xi^{(n-1)})\\ \end{pmatrix} =FCF^{-1}  $$
The circulant is diagonalized by the DFT matrix.
Answer: As a brief follow-up on Aspect's response (As this thread still appears to get quite a few views), if you don't want to use the language of Fourier analysis, you can also note that as Aspect pointed out $\displaystyle C = \sum_{i=0}^{n-1} c_iQ^{i}$. Therefore, it is sufficient to show that the $v_j$ vectors are eigenvectors of $Q$ (say with eigenvalues $\lambda_j$), as then we find that
$$Cv_j = \sum_{i=0}^{n-1} c_iQ^{i}v_j = \left(\sum_{i=0}^{n-1} c_i\lambda_j^{i}\right)v_j.$$
Note that this actually shows more, as we now have found an explicit formula for the eigenvalues in terms of the entries of the circulant matrices and the eigenvalues of the matrix $Q$. (It is a straight-forward exercise to show that the eigenvalues of $Q$ are the n$^{th}$ roots of unity.)

Eigenvectors of a circulant matrix


Where to start on basic derivation using $I$ inclusion

Question: I'm trying to get through the following problem (which uses a negation inclusive ($-I$)) what steps should I take to properly derive this?
$P\rightarrow Q, Q\rightarrow R, - R\vdash -(P\wedge S)$
I am using the following rule sets:
First 7:
https://books.google.com/books?id=qaIdAgAAQBAJ&pg=PA152&lpg=PA152&dq=nelson+p+lande+derivation+rules&source=bl&ots=dZSufOhmlc&sig=Ybw_RboRt2lze1CZqc8iXlyDUfQ&hl=en&sa=X&ved=0ahUKEwjr1aWXp-bTAhXqjFQKHTjJDA0Q6AEIJzAA#v=onepage&q&f=false
Last 4:
https://books.google.com/books?id=qaIdAgAAQBAJ&pg=PA192&lpg=PA192&dq=nelson+p+lande+derivation+rules&source=bl&ots=dZSufOhmlc&sig=Ybw_RboRt2lze1CZqc8iXlyDUfQ&hl=en&sa=X&ved=0ahUKEwjr1aWXp-bTAhXqjFQKHTjJDA0Q6AEIJzAA#v=onepage&q&f=false
Let me know if there is anything I can do to pose this question in a better way.
Answer: \begin{array}{llll}
1&1&P \land S&A\\
1&2&P&1 \land E\\
3&3&P\rightarrow Q&A\\
1,3&4&Q&\rightarrow E\\
5&5&Q\rightarrow R&A\\
1,3,5&6&R&4,5 \rightarrow E\\
7&7&\neg R&A\\
1,3,5,7&8&R\land \neg R&6,7 \land I\\
3,5,7&9&\neg(P\land S)&8 \neg I\\
\end{array}
Comment: Thanks! I started working backwards but I always get stuck when it comes to making the assumptions, need to touch up on those rules.
Comment: @Kellen You,ll pick up the use of $\neg I$ quick enough! But yes, you have to work 'backwards': if ever you need to prove $\neg \varphi$, 9 times out of 10 you need to throw in $\varphi$ as an assumption and derive some kind of contradiction.


Amazon EC2 instance : Cannot create temp file for here document. No space left on device

Question: I have an EC2 instance, which keeps on running Out Of Memory killing my mongod process in turn.
Doing df -h gives
udev            2.0G     0  2.0G   0% /dev
tmpfs           396M   41M  355M  11% /run
/dev/xvda1      7.8G  7.4G     0 100% /
tmpfs           2.0G     0  2.0G   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           2.0G     0  2.0G   0% /sys/fs/cgroup
tmpfs           396M     0  396M   0% /run/user/1000

so as my /dev/xvda1 is full. I go in my '/' or root directory and do a
ls -l --block-size=M
total 1M
drwxr-xr-x   2 root root 1M Nov 22 04:49 bin
drwxr-xr-x   3 root root 1M Dec 21 13:14 boot
drwxrw-rwx   3 root root 1M Oct 18 21:01 data
drwxr-xr-x  16 root root 1M Oct 18 20:30 dev
drwxr-xr-x  91 root root 1M Dec 14 01:29 etc
drwxr-xr-x   3 root root 1M Oct 18 20:30 home
lrwxrwxrwx   1 root root 1M Dec 21 13:14 initrd.img -> boot/initrd.img-4.4.0-57-generic
lrwxrwxrwx   1 root root 1M Dec  6 05:03 initrd.img.old -> boot/initrd.img-4.4.0-53-generic
drwxr-xr-x  21 root root 1M Sep  7 19:24 lib
drwxr-xr-x   2 root root 1M Sep  7 19:22 lib64
drwx------   2 root root 1M Sep  7 19:26 lost+found
drwxr-xr-x   2 root root 1M Sep  7 19:22 media
drwxr-xr-x   2 root root 1M Sep  7 19:22 mnt
drwxr-xr-x   2 root root 1M Sep  7 19:22 opt
dr-xr-xr-x 139 root root 0M Oct 18 20:29 proc
drwx------   4 root root 1M Oct 18 21:00 root
drwxr-xr-x  23 root root 1M Dec 25 13:55 run
drwxr-xr-x   2 root root 1M Oct 19 06:11 sbin
drwxr-xr-x   2 root root 1M Sep  1 17:37 snap
drwxr-xr-x   2 root root 1M Sep  7 19:22 srv
dr-xr-xr-x  13 root root 0M Dec 25 13:59 sys
drwxrwxrwt  11 root root 1M Dec 25 14:17 tmp
drwxr-xr-x  10 root root 1M Sep  7 19:22 usr
drwxr-xr-x  14 root root 1M Oct 18 20:52 var
lrwxrwxrwx   1 root root 1M Dec 21 13:14 vmlinuz -> boot/vmlinuz-4.4.0-57-generic
lrwxrwxrwx   1 root root 1M Dec  6 05:03 vmlinuz.old -> boot/vmlinuz-4.4.0-53-generic

If I add up all the file size it doesn't add up to be 7.4 GB. Then what is ? and how do I fix this? So that it doesn't overflow and kill my mongod process in return.
On some of the answer. It said restart your system. Post restarting this is the output.
udev            2.0G     0  2.0G   0% /dev
tmpfs           396M  5.6M  390M   2% /run
/dev/xvda1      7.8G  5.3G  2.2G  72% /
tmpfs           2.0G     0  2.0G   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           2.0G     0  2.0G   0% /sys/fs/cgroup
tmpfs           396M     0  396M   0% /run/user/1000

I still use 5.3G of space. what is causing 2 GB to be filled? How do I drill down the issue?
Answer: Okay, Now I have figured it out. I first do df -h. They tell me what all folders have how much space. We are only considered with /dev/xvda1. Now go to home directory and type du -h -d 1 which means disk usage and search by directory level 1 in human readable format. Which tells you how much space is being used by each directory.
I then go to that directory and remove the things which are taking space.In my case, it was the logs and wrote scripts to automatically gzip and secure copy them on my local machine and delete the logs. Hence solving the problem.
Answer: ls -l doesn't show the size of the files inside the folders. You should run du -hs. For example: du -hs /* | sort -h.
Comment: On an EC2 it mostly says can't read this file. How would I drill down to the nib of the issue
Comment: If it says `can't read` you can just filter out those lines with `du -hs /* | grep -v "Can't read" | sort -h`.


How do I display the latest post related to another?

Question: I'm on d7. I have 12 nodes that I use as groups with the entity relations module. When a user submits a post, they choose one of the groups to put it into. I want to make a views list of all 12 groups that displays the title of the latest post that has been submitted into each of them. Any suggestions? Thanks.
Answer: I ended up using the views field view to get the job done.


Arquivo .htaccess configurações

Question: Olá nobres amigos sou um iniciante aqui no Stack Overflow e iniciante em programação  Vôvo de 04 netos 54 anos.
Qual configuração fazer no .htaccess para proteção de diretórios, pastas, arquivos e DB de acessos via navegador. Grato.
Comment: Bem vindo ao StackOverflow, para começar faça um [tour] leia atentamente cada passo, e depois olhe [ask], veja como fazer uma pergunta corretamente, simples e objetiva.
Comment: Você também pode usar o .htpasswd para por senhas nos diretórios.
Answer: A opção que você procura é essa:
Options -Indexes

Pode por direto nos .htaccess (se estiver habilitado esse override no Apache).
Exemplo de configuração com Directory, em vez de .htaccess:
<Directory /caminho>
    Options -Indexes
</Directory>

Documentação (en):

https://httpd.apache.org/docs/2.2/sections.html#file-and-web

Link Útil:

20 dicas e truques extremamente úteis do .htaccess
Comment: Muito obrigado Sr. Darlei Fernando Zillmer...Consegui realizar as devidas alterações.

Arquivo .htaccess configurações


Using hex values for colors in LaTex/MathJax

Question: I have a couple variables in my javascript that hold color values, i.e.
var color = #ABCDEF

I'm trying to use these variables to color some text that I have, but it seems that MathJax doesn't support hex color values. Is there anyway to circumvent this in order to use the variable in the \color?
Answer: You can try \color[HTML]{ABCDEF}.
You need to add \usepackage{xcolor} to the preamble.
Answer:
it seems that MathJax doesn't support hex color values

Sure it does.  E.g., \color{#ABCDEF}{x+1} works fine in the standard configurations.  You can also load MathJax's color extension to make the \color command more compatible with LaTeX's syntax (thought it doesn't implement the HTML color model suggested by sergej, but does do rgb and several others).
You don't give enough of your code to tell how you intend to use you color variable, but one thing that is wrong is that you have left out the quotation marks:
var color = "#ABCDEF";

The issue now will be how you get this value into the \color command within you math expressions.  If you are trying to make all the math on your page be a different color, it would be best to use CSS for that.  E.g.,

would do it for MathJax's HTML-CSS output.
Comment: Well, here's a sample of my test code: https://jsfiddle.net/gamea12/u09or8aL/

What I'm trying to do right now is to color only the text within the brackets, and not the following code. If you could also give a reason as to why it's shifted so much to the right, I would also be thankful for that, please.


Strengthening the Consequent: From A implies B, infer A implies (B ^ C).

Question: Strengthening the Consequent:
From A implies B, infer A implies (B ^ C).
How do I construct a Fitch style proof to prove this?
Comment: You **cannot** : if with "A implies B, infer A implies (B ^ C)" you are meaning : $A \rightarrow B \vdash (A \rightarrow (B \land C))$ this is not true, because $(A \rightarrow B) \rightarrow (A \rightarrow (B \land C))$ is **not** a tautology.
Comment: This doesn't seem to work. What if A and B are true but C is false? Then the first statement is true but your desired inference is false. Did you mean the conclusion to be A implies B v C?
Comment: You cannot prove this because this is not the case. Aren't you confused with the conjunction and the weakening of the consequent (disjunction)?
Answer: Not true:
If $A$ true, $B$ true and $C$ false, then $A\Longrightarrow B$ true, $B\wedge C$ false, and hence $A\Longrightarrow (B\wedge C)$ false.
Answer: You are probably thinking of proving the following theorem:
$\vdash (A \rightarrow B) \rightarrow (A \rightarrow B \vee C)$
If this is the case, you can just
(1) assume $A \rightarrow B$;
(2) assume A;
(3) derive B by modus-ponens;
(4) derive $B \vee C$ by $\vee I$;
(5) derive $A \rightarrow (B \vee C$) by $\rightarrow I$ (assumption 2);
(6) derive $(A \rightarrow B) \rightarrow (A \rightarrow (B \vee C$)) by $\rightarrow I$ (assumption 1).
However, if you do really want to prove $(A \rightarrow B) \rightarrow (A \rightarrow (B \wedge C$)) it is no use, since $\nvdash (A \rightarrow B) \rightarrow (A \rightarrow (B \wedge C$)), i.e. it's not a theorem in the propositional calculus (if you want, you can confirm it by a truth table calculus).


Is it necessary include Google Play Servicies in apk?

Question: I am afraid with that. Is it necessary to include Google Play Services with our apk? If it were an external library the response is YES. But in this case, Android forces us to download latest Google Play Services version, so the code must be in the device...
The problem that I see is that every app with this library will use the same code that can have the device, thus saving space.
Practical case: I had an application with admob which is 800KB. Now, using Google Play Services is 2.8MB.
Could someone explain me that?
Thank you!
Answer: Because most users have the latest version installed on their devices, you do not need to include the entire Play Services lib in your build. If they don't have it installed, or if they do not have the latest version then your code might not work correctly.
If the user has Google Play then they will get a dialog letting them know that their Google Play Services is out of date and needs updating. If they don't have Google Play then you can choose what to do, for example you can alert the user that the app will have a limited functionality. If your app can't run without Google Play Services and the user doesn't want to install/update Google Play Services then your app will not work properly. Using an outdated libs in your project might work however you would be using them at your own risk as they won't be updated.
Comment: So, in case that the play servicies is not updated the user may see a FC and that is not good...
Comment: I just want play services to show ads. If I include the lib, GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) returns SUCCESS and the ad is shown. If I don't include the lib, GooglePlayServicesUtil return a NoClassDefFoundError.
Answer: Firstly you don't need to include it in your apk - you can pretty much assume it's on the phone and up to date. The increase in size means that you are including it in your apk. To exclude it from the apk delete it from your libs folder.
If you get errors then you need to add it as a library to your app. You can do that by going into your project's properties then clicking on Android on the left and then in the bottom section add Google Play Services from your workspace as a library (that is on Eclipse).
Comment: Add it only if fails in my devices? I think that is not a good idea. May it works on my devices but not in other people, generating a FC...


How to upload a bytes image on Google Cloud Storage from a Python script

Question: I want to upload an image on Google Cloud Storage from a python script. This is my code:
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient import discovery

scopes = ['https://www.googleapis.com/auth/devstorage.full_control']
credentials = ServiceAccountCredentials.from_json_keyfile_name('serviceAccount.json', scop
es)
service = discovery.build('storage','v1',credentials = credentials)

body = {'name':'my_image.jpg'}

req = service.objects().insert(
   bucket='my_bucket', body=body,
   media_body=googleapiclient.http.MediaIoBaseUpload(
      gcs_image, 'application/octet-stream'))

resp = req.execute()

if gcs_image = open('img.jpg', 'r') the code works and correctly save my image on Cloud Storage. How can I directly upload a bytes image? (for example from an OpenCV/Numpy array: gcs_image = cv2.imread('img.jpg'))
Comment: Is your issue on the python upload side or on the server side?
Comment: I know this is javascript, but: https://github.com/GoogleCloudPlatform/google-cloud-node/issues/2334
Comment: Also https://stackoverflow.com/a/37102815/1021819
Comment: https://www.quora.com/How-do-I-upload-a-file-to-Google-Cloud-Storage-using-Python; https://cloud.google.com/storage/docs/boto-plugin#setup-python; https://cloud.google.com/python/getting-started/using-cloud-storage#uploading_to_cloud_storage
Answer: In my case, I wanted to upload a PDF document to Cloud Storage from bytes.
When I tried the below, it created a text file with my byte string in it.
blob.upload_from_string(bytedata)

In order to create an actual PDF file using the byte string I had to do:
blob.upload_from_string(bytedata, content_type='application/pdf')

My byte data was b64encoded, so I also had b64decode it first.
Comment: OP - can you mark this accepted answer?
Answer: If you want to upload your image from file.
import os
from google.cloud import storage

def upload_file_to_gcs(bucket_name, local_path, local_file_name, target_key):
    try:
        client = storage.Client()
        bucket = client.bucket(bucket_name)
        full_file_path = os.path.join(local_path, local_file_name)
        bucket.blob(target_key).upload_from_filename(full_file_path)
        return bucket.blob(target_key).public_url

    except Exception as e:
        print(e)

    return None

but if you want to upload bytes directly:
import os
from google.cloud import storage

def upload_data_to_gcs(bucket_name, data, target_key):
    try:
        client = storage.Client()
        bucket = client.bucket(bucket_name)
        bucket.blob(target_key).upload_from_string(data)
        return bucket.blob(target_key).public_url

    except Exception as e:
        print(e)

    return None

note that target_key is prefix and the name of the uploaded file.
Answer: MediaIoBaseUpload expects an io.Base-like   object and raises following error:
  'numpy.ndarray' object has no attribute 'seek'

upon receiving a ndarray object. To solve it I am using TemporaryFile and numpy.ndarray().tofile()
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient import discovery
import googleapiclient
import numpy as np
import cv2
from tempfile import TemporaryFile

scopes = ['https://www.googleapis.com/auth/devstorage.full_control']
credentials = ServiceAccountCredentials.from_json_keyfile_name('serviceAccount.json', scopes)
service = discovery.build('storage','v1',credentials = credentials)

body = {'name':'my_image.jpg'}
with TemporaryFile() as gcs_image:
    cv2.imread('img.jpg').tofile(gcs_image)
    req = service.objects().insert(
       bucket='my_bucket', body=body,
       media_body=googleapiclient.http.MediaIoBaseUpload(
          gcs_image, 'application/octet-stream'))

    resp = req.execute()

Be aware that googleapiclient is non-idiomatic and maintenance only(it's not developed anymore). I would recommend using idiomatic one.
Comment:  I have asked so many question that SO has asked me only to answer. I can't ask anymore questions until I get more reputation
Comment: I have a similar situation. I am using `OpenCV` processing image which is in `ndarray`. I want to now store this processed image on cloud as an image `.jpg` file. Can you give any suggestions? To solve this Please
Comment: Can you help me? @A.Queue
Comment: Sorry for not answering. Could you create a new question to follow SO rules? Feel free to mention me there in the comments.
Comment: Can you guide me to a location online where I can find a solution for this at least? @A.Queue
Comment: https://stackoverflow.com/questions/49651351/upload-ndarrayimage-in-opencv-on-to-google-cloud-storage-as-a-jpg-or-png @A.Queue Posted question from a friends account
Comment: [link](https://stackoverflow.com/questions/49671827/upload-an-image-from-cloud-function-python-to-google-cloud-storage) @A.Queue
Answer: Here is how to directly upload a PIL Image from memory:
from google.cloud import storage
import io
from PIL import Image

# Define variables
bucket_name = XXXXX
destination_blob_filename = XXXXX

# Configure bucket and blob
client = storage.Client()
bucket = client.bucket(bucket_name)

im = Image.open("test.jpg")
bs = io.BytesIO()
im.save(bs, "jpeg")
blob.upload_from_string(bs.getvalue(), content_type="image/jpeg")

In addition to that, here is how to download blobfiles directly to memory as PIL Images:
blob = bucket.blob(destination_blob_filename)
downloaded_im_data = blob.download_as_bytes()
downloaded_im = Image.open(io.BytesIO(downloaded_im_data))


Gerar arquivo .txt com tres colunas

Question: Tenho um sistema onde faço algumas pesquisas no banco e armazeno tudo em um Array, porém tenho que montar um layout com esses dados paras que eles possam ser impressos como etiquetas em uma impressora matricial.
A parte das linhas eu já formatei, porém não sei como fazer para que o próximo registro da lista ao invés de ir pra próxima linha vire uma coluna.
Eu preciso deixar dessa forma:

O que eu consigo obter atualmente é isso:

Nesse caso minha consulta retornou apenas dois resultados, o certo seria colocar essa segunda linha em uma coluna como na primeira imagem.
Essa é minha classe que gera o txt:
public static void gerarTxt(List<Contrato> lista) {

        try {
            FileWriter arq = new FileWriter("C:\\etiqueta.txt");
            PrintWriter gravarArq = new PrintWriter(arq);
            for (Contrato item : lista) {
                gravarArq.print(item.getContrato());
                gravarArq.print("\r\n");
                gravarArq.print(item.getContratante());
                gravarArq.print("\r\n");
                gravarArq.print(item.getRua().trim()+", "+item.getNumero());
                gravarArq.print("\r\n");
                gravarArq.print(item.getBairro());
                gravarArq.print("\r\n");
                gravarArq.print(item.getCep() + " "+item.getCidade()+ " "+StringUtils.leftPad(item.getUf(), 22));
                gravarArq.print("\r\n");
                gravarArq.print(".");
                gravarArq.print("\r\n");
            }
            arq.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Como posso transformar essas linhas em colunas?

Update
Exemplo do projeto no GitHub: https://github.com/sinkz/EtiquetaTeste
Comment: Olha [essa pergunta](http://stackoverflow.com/questions/26229140/writing-data-to-text-file-in-table-format) ou [esta aqui](http://stackoverflow.com/questions/7465086/java-output-to-file-in-table-format) no SOEn.
Comment: Acho que isso resolveria, mas como passar o próximo item da lista na segunda coluna?
Answer: Se você conhece a largura da Coluna e ela é fixa (assumo que sim, pois é para uma impressora matricial), você pode usar o método StringUtils.rightPad.
De qualquer forma você vai ter que trabalhar com mais de um registro da lista ao mesmo tempo. Por exemplo:
for (int i = 0; i < lista.size(); i + 2) {
    Contato c1 = lista.get(i);
    Contato c2 = lista.get(i + 1);

    metodoQueVaiEscreverOText(c1, c2);

}
Ainda assim, você precisa controlar o tamanho do array e o index, para evitar o outofboud.
Qualquer coisa cola seu código e exemplos de dados para enriquecermos o exemplo.
Boa sorte
Comment: Qualquer compartilha o código no editor de sua preferência e damos uma olhada.
Comment: Sim, a coluna é fixa. Vou tentar dessa maneira e ver se da certo
Comment: Uma dúvida, sabe como eu poderia padronizar esse layout com StirngUtils?
Comment: Eu quero deixar sempre na mesma posição, tenho que medir o tamanho da String anterior antes de fazer a proxima?
Comment: Eu imagino algo assim:
StringUtils.rightPad(c1.getNome(), 15);
StringUtils.rightPad(c2.getNome(), 15);
//quebra uma linha
StringUtils.rightPad(c1.getContrato(), 15);
StringUtils.rightPad(c2.getContrato(), 15);
//quebra uma linha

Ele vai truncar ou fazer pad para o tamanho informado.
O que vc quer dizer com Layout?
Comment: Entendi, vou tentar dessa forma.
Comment: Por exemplo, posso ter String's com tamanhos diferentes, tenho que fazer que independente do tamanho da String o layout nunca mude, estou utilizando o leftPad e está ficando fora de ordem conforme o tamanho, acho que ele não considera o espaço em branco.
Comment: vou sair pra viajar :/. Segunda continuo tentando, as colunas já estão funcionando só falta alinhar. Obrigado pela ajuda, feliz ano novo.
Comment: De acordo com sua imagem vc deve usar o rightPad e 3 elementos (Contatos) simultaneamente.
Verifiquei na api, se o tamanho for maior que o esperado, ele nao vai truncar, então usa o substring para quebrar no tamanho.  Conversamos na segunda.
Comment: fiz um projeto de exemplo e coloquei no github se quiser dar uma olhada: https://github.com/sinkz/EtiquetaTeste
Comment: lá tem um arquivo `.txt`  o primeiro layout é gerado pelo sistema, e a parte de baixo é como estou tentando deixar. De começo estou tentando fazer com duas colunas.
Comment: Acho que consegui resolver, mas agora estou tendo problemas com o índice :p kk
Comment: Problema resolvido, utilizei o rightPad mesmo ao invés do left
Comment: Legal. Desculpa a demora, só consegui acesso à internet agora. Valeu
Comment: Tranquilo, dei uma fuçada e consegui. kkk

Gerar arquivo .txt com tres colunas


'""C:\Program' is not recognized as an internal or external command, operable program or batch file - spark shell

Question: I'm getting an error while running spark-shell
'""C:\Program' is not recognized as an internal or external command,
operable program or batch file.
Answer: I suspect that you installed Java to a directory with a space so JAVA_HOME breaks spark-shell script on Windows.
Make sure you install Java to a directory with no space in the path.

The other option would be to set JAVA_HOME to the same value but wrapped with double quotes, e.g.
set JAVA_HOME="C:\Program Files\Java\jdk1.8.0_131"

That will likely lead to the other issue on Windows that was answered in Why does spark-shell fail with "was unexpected at this time"? that's simply to re-install Java to a directory with no space in the path.

The thing I could not check out yet would be to wrapped JAVA_HOME using single quotes (not double quotes). That in theory would help pass the line with comparison to "x".

p.s. Yes, that's a copy of my answer to Why does spark-shell fail with "is not recognized as an internal or external command" on Windows?, but given the mentioned question has no answers approved it's not possible to mark this one as a duplicate.
Answer: You may need quotes around "C:\ Program Files..." because of the space in the string.
Comment: thanks that was a big help.... this answer [here](https://stackoverflow.com/questions/44066854/why-does-spark-shell-fail-with-c-program-is-not-recognized-as-an-internal) helped as well -


Directive Scope is not coming through controller

Question: We are having an issue in getting the scope into the controller and downgrading the angular version to 1.5.3 is actually fixing it up.
Can someone help us with what is wrong with angular 1.6.3 or if this needs to be done any differently?
Please ignore any syntax errors as the actual code has none
<code>// Simple Directive

var directive = {
    restrict: 'EA',
    templateURL: 'sometemplate.html',
    scope: {
        text: '@'
    },
    bindToController: true,
    controllerAs: 'someCtrl',
    controller: 'someController'
}

// someController.js

var self = this;

self.text //this comes back as undefined which is the issue

sometemplate.html

{{someCtrl.text}} // this works
</code>
so in short the scope is working for the template but is not avaialble in controller.
For the same if we rollback the version from 1.6.3 to 1.5.3 it starts to work..
Also tried changing the bind to controller to a object with same fields as scope but it doesnt work with 1.6.3.
are we missing something??
Answer: It is because you are binding to controller. When bindToController is set to true, all the scope values being inherited are bound to the variable provided under controllerAs.  Look for the value on the injected $scope on the provided name of someCtrl.
Comment: hey - i have tried that. someCtrl in the scope is also coming back as empty. I am trying to see if there is a different way to do it. and why it works in with 1.5.3 and 1.6.3
Comment: make a plunkr and I'll mess with it.


How to obtain extension properties by Kotlin reflection?

Question: I have used the memberExtensionProperties() method, but result collection of the extension properties is empty. The test code is attached. What is the right procedure?
class ExtensionPropertyTest {
    class DummyClass{}
    val DummyClass.id get() = 99
    val DummyClass.name get() = "Joe"

    @Test
    fun testExtensionProperties() {
        val dummyClass = DummyClass()
        expect(dummyClass.id).toEqual(99) // OK

        val properties = DummyClass::class.memberExtensionProperties
            .stream()
            .toList()
        expect(properties).toHaveSize(2) // Fails due a zero size
    }
}

Comment: I don't believe it's possible to do that, as the extension properties can live anywhere.  I would expect the class with `memberExtensionProperties` to be `ExtensionPropertyTest`.
Answer: memberExtensionProperties does not return extensions over a class, but its members that are at the same time extensions:
fun main() {
    println(DummyClass::class.memberExtensionProperties)
}

class DummyClass {
    val String.foo: Int
        get() = toInt()
}

It is not that easy if at all possible to find all extensions over a class, because extensions are detached from their receivers and they can be located anywhere in the classpath.


Where is the documentation of System.Web.Razor? (v2)

Question: I've got the v2 version of the Razor engine from NuGet. I'd like to compile Razor views on-the-fly using its API. However, it seems to be fully non-documented.
Every single type and member has the following documentation:

This type/member supports the .NET Framework infrastructure and is
  not intended to be used directly from your code.

This is very irritating, since these are all public types and public members.
I've seen some 3rd party stuff which does compile Razor views using this library, so I know that the task should be doable too.
So, is there any actual usable documentation on how to use this API anywhere?
Comment: +1 This has got to be one of the most irresponsible decisions I've ever seen. I've always hoped that responsible framework developers would consider *useful* API documentation a critical requirement, something necessary before deployment. To see page after page of the MSDN polluted with "*herp derp **not intended to be used directly** herp derp*" is just insulting.
Comment: @Bracketworks Yep, I completely agree!!!
Answer: I left this question open for almost a year without an answer, so I decided to post what I came up with eventually.
It is pretty clear that Razor is still undocumented, see http://msdn.microsoft.com/en-us/library/system.web.razor%28v=vs.111%29.aspx and I think it is very likely to remain undocumented.
However, how to use it can be easily determined by looking at the code of how ASP.NET MVC uses it in its Razor view engine. You can then write code based on that.
It seems that Razor also ties into the ASP.NET BuildManager infrastructure, so you can easily get an instance of a Razor view through that. Then, you are looking for calling the ExecutePageHierarchy method.
Here is the code:
public void ProcessRequestCore(HttpContextBase context)
{
    try
    {
        // Create Razor page instance
        var instance = BuildManager.CreateInstanceFromVirtualPath(_razorFilePath, typeof(WebPage)) as WebPage;

        if (instance == null)
            throw new NullReferenceException("BuildManager.CreateInstanceFromVirtualPath returned null.");

        // Set up things
        instance.VirtualPath = _virtualPath;

        // Render the Razor page
        instance.ExecutePageHierarchy(new WebPageContext(context, instance, _model), context.Response.Output);
    }
    catch (Exception exc)
    {
        Logger.WriteException(exc);
        context.Response.StatusCode = 500;
    }
}


Can a symphony be in many keys?

Question: First of all, please excuse me for my bad musical vocabulary usages.
I'm working on an information-system for music, and I'm trying to understand some basic concepts in order to move on in my project.
One of the features that I've got is key. this key could have value of the following list:

Well, my question is:
If a symphony has the key "CMinor", can it also have another key?
According to Wikipedia , the famous 5th Symphony for Beethoven is from CMinor key. so can I say for sure that it doesn't have anyother key value?
Comment: You need to have some music theory background. Because even the composer doesn't change the key signature he could run around. I heard a comment from professor R. Greenberg that changing the key makes the music more interesting.
Comment: Usually the key a symphony is "in" is just the first and last key used. In the middle it could change between any number of keys. That is also true of other musical works besides symphonies. Usually rock songs are in just one key, but classical, jazz, show tunes, and sound track music often changes keys.
Comment: If you took a short symphony - Mozart or Haydn perhaps, and studied it, you would find many changes of key - often just modulations. But you'd need to be able to recognise what clues are there to be able to do this. Changes of notes via accidentals, new key sigs etc. In itself the skill to do this will take at least a couple of years to hone. Compiling a list of keys is really only of academic interest, and not particularly helpful to many. Musicians will play in whatever key the piece is at that moment, and change when it tells them to, maybe not even thinking  what the current key is.
Comment: A couple of other points - 1) sometimes it's not really clear what key a passage of music is in - there are situations where you could view it from one perspective or another. 2) The set of tonalities that can be described by the key system is wide, but not every piece can be well-described as being in any minor or major key (even including some pieces that are not atonal).
Comment: @WilliamKinaan - there have been several studies, etc. on key structure and what chords/notes tend to occur in keys.  Such as https://en.wikipedia.org/wiki/Markov_chain#Music . These approaches might be of use to you.  Just a thought!
Comment: @ToddWilcox so each musical work has at least one key, but it could have many as well. right?
Comment: @ToddWilcox moreover, how can I know all the keys for a specific symphony, say 5th or 9th symphony for Beethoven please?
Comment: Did you try a web search for a list of keys or an analysis? Even just the Wikipedia page for Beethoven's fifth seems to list all the keys used: https://en.wikipedia.org/wiki/Symphony_No._5_(Beethoven) Note that this one ends in C **major**, which was an unusual choice at the time but in line with Beethoven's style and outlook.
Comment: Not a symphony, but 'Phantom of the Opera' actually changes key on every verse.
Comment: Could you give us more information about what exactly your goals are with the project, and where you expect the information to come from that will be going into the database?
Comment: @WilliamKinaan The answers provide a good survery of the music-related issues here, but from a knowledge-engineering standpoint, I'd also suggest that you make your representation a bit more flexible. E.g., you might relate Pieces to Keys by a hasKey property where a Key has attributes such as tone and scale. Thus you could say something like "X hasKey [ hasTone [ hasPrimary G ; hasAccidental Flat ] ; hasScale Major ]". (That's N3 notation of RDF; since it looks like you're developing an ontology in Protege.)  By separating some of those concerns, you'd be able to query for some features...
Comment: ...like "pieces that involve the parallel major and minor (e.g., C minor *and* C major, or Ab minor and Ab major)" which would be difficult to do if you have each key as a distinct, opaque individual.
Comment: @Andy I have a real problem with the Markov chain applied to music as there are many problems with using it. The biggest being if you actually get a good sample a music you'll most likely end up with something that doesn't make any sense since it's missing the context which is needed when composing  similar how you wouldn't want to use it to write a book.
Comment: @Dom thanks for the comment - I wasn't actually telling the questioner to use such things for composition, just gently suggesting he read up on previous work to see what's been done in the field before. I agree he shouldn't drift off into attempting composition based on state machines or something...
Answer: It's not clear what your goals and requirements are for this information system -- and that has a huge bearing on the answer.
If, for example, your software is trying to analyze the harmony inside of a single piece, then yes, symphonies definitely will modulate (change keys) all over the place, as Wheat Williams describes in his excellent answer. And this will be extremely important to understand.
If, on the other hand, you are trying to classify music by the key that it is written in, it is probably sufficient to pick the main key that the piece is in (which could possibly be none, as others have mentioned). While the symphony will visit other keys -- sometimes closely related keys, and sometimes more distantly related -- it will (usually) keep returning to the main home key as a sort of touchstone, or a "global constant" (to use a programming term). Tonality, like many aspects of music, tends to be rather hierarchical in nature.
So before we can give you a useful answer, we need to know what you are trying to do with your system.
EDIT: Another way of stating my answer, triggered by Kyle's comment below about schema: From a DB perspective, you're modeling the relationship between a piece of music and its key as a "has-a" relationship, and you are asking about the cardinality of this relationship. But semantically, a musician will think about music, not as having a key, so much as being in a key, or visiting another key. So you will need to determine the desired semantics of the "has a key" relationship that is of interest to your application, before its cardinality can be determined. IOW, what is the "key" value actually supposed to represent? For what is it meant to be used?
Comment: We also need to know who is going to be generating the database entries. If it's the OP, they'll clearly need to learn more about classical harmony; otherwise, it's probably possible to generate a schema by asking questions like this one.
Answer: Every symphony ever written has more than one key -- usually several different keys.
A symphony may have the name of a certain key in its title, but this only refers to the main key that occurs throughout its structure. Each symphony will have many changes to different keys. Each symphony will tend to be unique in how it uses multiple keys. Different symphonies throughout history have had different structures altogether.
You can easily construct a database that categorizes the titles of symphonies based on the main key in the name of each symphony. That may be sufficient for your purposes. But if you truly want to understand and categorize all the keys involved in each symphony, that is a more complex subject.
Encyclopedia Britannica opens its lengthy article on the symphony by saying:

Symphony, a lengthy form of musical composition for orchestra,
  normally consisting of several large sections, or movements, at least
  one of which usually employs sonata form.

To gain a better understanding of the complexities involved, you may look to studying about what a key is, what a symphony is, and how it is constructed; this depends in part on what we call the sonata form. If you want to understand these matters, they come under the category of musical form and analysis. Form and analysis is a university course that is taught at the end of about two years of study in the music theory curriculum. It goes without saying that to understand all the keys in a symphony you need to be able to read music and to analyze and study the sheet music for the symphony.
On this site we frequently receive questions from young people who are learning computer programming, database development or the like who are doing school projects and want to create computer software to express musical ideas. These young people do not understand what a complex subject music is. To understand these concepts, you must be a student of music.
If your goal is to study database development, and you need to find a suitable subject for building a database for a school project, then perhaps you should choose a different subject area than music around which to build a database.
If your primary aim is to study music and become a musician, that is the purpose of this site, Music Practice & Theory. We are happy to help you with that.
Comment: There's some valid advice there, but 2 paragraphs of answer and 5 paragraphs of advice not specific to the question seems a bit too much. It almost comes across as a rant.
Comment: @KyleStrand, *sonata form* defines the usual structure for using multiple different keys in different sections of one movement of a symphony.
Comment: @WheatWilliams thanks for answering. Developing a *simple prototype* for a project in order to get funded by someone, *after than* consulting musical experts, is also an option :) , don't you think?
Comment: I wouldn't necessarily say EVERY symphony.  The vast, overwhelming majority of them, for sure.  But I wouldn't discount the possibility that a work of music titled a "symphony" exists which does not change keys.  (Off the top of my head, The Verve's "Bittersweet Symphony" is pretty tonally consistent.  Is that really technically a symphony?  Well, they call it one in the title, so what official rule exists to deny that claim?)  Not disagreeing with you per se, just pointing that all generalizations are false and all.
Comment: @DarrelHoffman, I disagree strenuously. The questioner wants to learn about actual symphonies, not other kinds of music that the public might misunderstand to be a symphony. To be sure, categorizing things in databases is about adhering to clearly defined and proper nomenclature and definitions of terms. Furthermore Richard Ashcroft, Mick Jagger and Keith Richards are perfectly clear on the concept that their song "Bitter Sweet Symphony" is, in fact, a song. https://en.wikipedia.org/wiki/Bitter_Sweet_Symphony
Comment: @JBentley I suspect Mr. Williams has done a cursory check of the asker's network profile and made the very understandable conclusion that the asker is coming from the world of development with a focus on databases. I do agree that saying one "must be a musician" to understand musical concepts is stronger wording than I would use. I just think everyone should be a musician because it's so much fun. Wheat: Rep does not make the man. We don't know who Mr. Bentley is but that doesn't mean we should discount his thoughts outright.
Comment: @WheatWilliams My point is not specific to music; it would apply to any Stack Exchange site (and for what it's worth, I've been a member of Stack Exchange for 4 years and have provided plenty of answers elsewhere; I only mention that because you seem to think quantity of answers and/or years membership matters in some way).
Comment: The "information-system" could simply index symphonies by key. There isn't much reason to guess what the software is about. A concise answer - like the one from @Shevliaskovic - is all that is needed.
Comment: What does sonata form have to do with the question? Why is music so complicated that building a simple database to store information about musical pieces is out of the question for someone who isn't a student of music? Why does your entire answer amount to "your question isn't good, your goals are improper, and your knowledge is insufficient"?
Comment: @DarrelHoffman, "Bittersweet Symphony" is the title of a *song*. It is certainly not a *symphony* in any sense. A *symphony* is a long-form multi-movement musical composition with specific sections that move through different key relationships and musical structures in a certain defined structure (although the specifics of this structure have evolved over the centuries). I've provided a link to one article on the structure of the *symphony* in my answer. A *song* is something altogether different.
Comment: @KyleStrand, if you ask the question "Can a symphony have more than one key", the answer is, "Yes, and this structure of more than one key is explained in the concept of *sonata form*". Understanding *sonata form* is useful to understanding the answer to the question.
Comment: That is the classical definition of a symphony, yes.  That doesn't mean an artist is not allowed to call something that doesn't fit the classical definition a "symphony" if they want to.  There are undoubtedly other isolated examples of non-traditional works called symphonies which would not meet that definition.  Doesn't necessarily make them "not symphonies".  Art is subjective, rules are fluid.  And generally speaking, in art as in life, there are no absolutes.
Comment: @WheatWilliams Yes, sonata form is an extremely common form in classical music, especially for the first movements of traditionally-structured symphonies. But "you do not understand what sonata form is" is not a useful response to the original question, which is pretty obviously about whether or not a symphony can be considered to be "in" multiple keys in the same sense that Beethoven's 5th is "in" C Minor. In this sense, short-lived modulations are irrelevant. In short, it's not clear that understanding sonata form is a prerequisite for categorizing pieces by their primary key(s).
Comment: It's also not clear that understanding sonata form would be sufficient or even helpful for understanding the primary keys of more modern works that don't follow it. Your edited answer is better, but from the perspective of someone looking to write the code for a database, it's not even clear that the OP will be responsible for generating the database entries; this question is basically just asking about the schema!
Answer: A composition like "Symphony in C minor" refers to a key in the piece, with which key the composition starts and with which it ends. There is a certain number of notes and chords in that key, so if a whole composition was built only on that key, it would sound repetitive. That's why during the composition changes keys. Usually it's more than one, but it really depends on the length of the composition.
Concerning your comment:

so each musical work has at least one key, but it could have many as well. right?

The answer is yes, but there is something more to it. There are also compositions without any key. These kind of compositions belong to atonal music

Atonal music is a generalizing term used to define music that seems to lack a clear tonal center.
how can I know all the keys for a specific symphony, say 5th or 9th symphony for Beethoven

One way would be to harmonically analyze the symphony and see what is going on. But this would require harmony knowledge and quite some time. Other than this, there might be some online guide to those symphonies, since they are so well known
Comment: @WilliamKinaan Note that "Dies Irae" does not refer to one specific piece of music. A few different types of church music, including a requiem, may have a section called "Dies Irae". There are also some pieces that are just called "Dies Irae" all on their own. That's the same problem with searching for "symphony number 9". There are many ninth symphonies by different composers. Include a composer name if you have it for classical music searches.
Comment: You need to look for an analysis of that symphony. There are some famous symphony that was analyzed the go step by step through the whole symphony. You need to search on the internet.
Answer: This is actually not a simple question, but neither do the answers give an accurate picture of historical practice during the common practice period.
The Beethoven Fifth is a good example: we regard it as a "C-minor symphony" because its first movement is in C minor. Within that movement, C minor is, as we often say, the tonal center: it's the key to which we ultimately relate all the other harmonic events within the movement. The second theme (as it's frequently but imprecisely called) appears first in E-flat major, the "relative major" of C minor; that is, the major key counterpart to C minor whose scale contains the same notes (or "pitch classes") as the natural minor form of the C minor scale. When, toward the end of the movement, the second theme reappears, it does so in C major, the "parallel major" of C minor. Nevertheless, despite visits to other keys, some of which Beethoven establishes quite convincing, the movement begins and ends in C minor: it's the gravitational field that pulls everything towards it.
At the multi-movement level, the symphony's key is also important. According to the convention in multi-movement works like symphonies, string quartets, and the like, the minuet or scherzo--the 3/4-time dance(-like) movement that normally appears in the second or third position--also is in the tonic key; and, in the case of a minor key symphony, the middle section of them movement (called the "Trio") will appear in the parallel major key. This is what happens in the Beethoven Fifth. (Another good example of this is the Menuetto of Mozart's 40th.)
As a C-minor symphony, of course, we should expect that the symphony to end in that key. Yet that's not how Beethoven ends this one: rather, he ends in a famously triumphant C-major (emphasized at the end by an obsessive affirmation of the key). Without our expectation of the C-major ending, we'd have a very different piece on our hands, wouldn't we?
The bottom line is that the tonic key of a large-scale piece like a symphony is of vital importance for how we understand what it's about. While Beethoven Fifth is relatively straightforward, there are other pieces (like Beethoven's Seventh) where the composer does some wild, unexpected, clever things with the key relationships. But in all cases, at least until the early twentieth century, the stated key of a symphony is almost always a vital reference point.
Answer:
If a symphony has the key "C Minor", can it also have another key?

I think the misconception you are having is that certain instruments are transposing by their nature. The Bb clarinet for instance when it plays a C what you are actually hearing is a Bb.
So if the strings play in C major, the Bb clarinet would have its score written in D Major. This is not a different key per se it is just a way to get the concert pitch of all instruments in the same key.
So when the clarinet plays the tonic note of its scale- the D- and the instruments that play their music at concert pitch play the tonic of C major you are in fact hearing the same note.
I think this may the root of your problem.
There is also the issue of modulations. Music rarely consists of one key. It modulates often to the Relative Keys, Dominant and Sub Dominant. You are under no obligations as composer to stay in the same key and it often makes sense to modulate to other keys.
Answer: If you know the basics of reading music, you could probably get a score of any piece written before 1900 from the IMSLP and quickly page through it looking for key changes.  For example, if you scan the score for Beethoven's Fifth, the first movement is in C minor, the second movement is in A-flat major, the third movement has sections in both C major and C minor, and the finale is in C major.
However, a quick scan like the one I just did will only account for the "official" changes of key signatures, i.e., the ones that the composer wrote into the score.  In the case of Beethoven's Fifth Symphony, for example, there's an extended section during the finale where one of the themes in C minor from the third movement is re-stated.  But the score never changes keys;  it's all done with accidentals.  It's also not always easy to tell whether a piece is in a major key or the corresponding relative minor unless you're already familiar with it (or are willing to do a close reading.)  Basically, this method is quick, but it would not necessarily give you a complete list of the keys used in a given piece.
Answer: Good luck with your software. Your list is rather incomplete, as it only lists majors and minors. (I'm not sure how much this matters but you should definitely be aware of this limitation.)
On the other hand you seem to be aware that B# major for example is essentially never used as it needs five double sharps. Most "black note" keys use whichever of flat/sharp that will give the smallest number of non-natural notes in the key signature. An exception is that Db major (five flats) is sometimes written as C# major (7 sharps) because certain instruments prefer an all-sharp key signature.
Each possible key signature has a fixed number of sharps or flats. But then there are 7 modes for each key signature. For example, if we take the natural notes (no sharps or flats), we have the Ionian mode C major CDEFGABC, the Aeolian mode A minor ABCDEFGA and five other possible (but less common) modes, depending on which note is the tonal centre (which note of the scale feels like "home" for the piece) https://en.wikipedia.org/wiki/Mode_(music)
A computer might be able to pick out the correct key signature (number of sharps and flats) if all 7 notes are present and their are no additional notes (absent notes and accidental notes will confuse it.) But it's going to have difficulty picking out which of the 7 notes is the tonal centre.
As an example, according to https://en.wikipedia.org/wiki/Symphony_No.5(Beethoven) the main key is C minor. This has a key signature with 3 flats. Its relative major (i.e the major key with 3 flats) would be Eb. Relative keys have the same key signature (i.e. they contain the same notes)
Additionally, the second movement is in Ab major, which has four flats (one more than C minor) so is a completely different key signature.
There is also a trio section in C major. C major is the parallel major of C minor (parallel keys are ones with the same tonal centre.) C major has no flats or sharps.
So you can see, there are quite a variety of keys in this long piece. A simple pop song might have only one key (but there are many that have several, especially those that use the trick of a key change on the last chorus.)

Can a symphony be in many keys?


MemoryError exception thrown for numpy.asarray()

Question: I have a system with 32 GB of memory, with most of it available to the work I'm trying to do:
$ more /proc/meminfo
MemFree:        29535136 kB
MemAvailable:   30789956 kB
...

I have some code that encodes letters in a string to vectors:
#!/usr/bin/env python

import os
import sys
import numpy as np
from Bio import SeqIO
import errno
import gzip
import shutil

seq_encoding = {'A' : [1, 0, 0, 0],
                'C' : [0, 1, 0, 0],
                'G' : [0, 0, 1, 0],
                'T' : [0, 0, 0, 1],
                'N' : [0, 0, 0, 0]}

sequence_chunk_length = 200

def sequence_split_by_length(seq, n):
    """
    A generator to divide a sequence into chunks of n characters and return
    the base array.
    """
    while seq:
        yield [seq_encoding[base] for base in seq[:n].upper()]
        seq = seq[n:]

def encode_chromosome(name, length):
    enc_records = []
    fasta_fn = os.path.join(fasta_directory, name + '.fa')
    fasta_fh = open(fasta_fn, "rU")
    for record in SeqIO.parse(fasta_fh, "fasta"):
        for chunk in sequence_split_by_length(str(record.seq), sequence_chunk_length):
            enc_records.extend(np.asarray(chunk))
    fasta_fh.close()
    enc_arr = np.asarray(enc_records)

# ... some more code not relevant to exception ...

Encoding fails at the line:
enc_arr = np.asarray(enc_records)

Here is the relevant part of the thrown exception:
Traceback (most recent call last):
  File "./encode_sequences.py", line 95, in <module>
    res = encode_chromosome(chromosome_name, sequence_chunk_length)
  File "./encode_sequences.py", line 78, in encode_chromosome
    enc_arr = np.asarray(enc_records)
  ...
MemoryError

The data structure that would be encoded is about 1 GB in size, which would seem to fit within the free memory available on this system.
Is there an alternative method or procedure for converting a Python list to a Numpy array, which helps to get around MemoryError exceptions with Numpy methods like asarray()?
Comment: You should check how much memory is actually used by python process: [Python script knows how much memory it's using](http://stackoverflow.com/questions/1240581/python-script-knows-how-much-memory-its-using)
Comment: `np.asarray` is not your only object here, before it gets to that line you have a lot of other objects like `SeqIO.parse` or  `chunk` the the `enc_records` itself.
Comment: Also when you use `np.asarray` it will consider a default data type for your array which is usually more than what you need. You can specify a proper type manually in order to consume less memory. For example `int8` instead of `int64` and etc.
Comment: Tell us about `enc_records`. Length, length of a sublist. The result of applying `np.array` to a subset of the list.  Do you expect a sparse array, mostly 0s?
Answer: This should be a quick fix:
enc_records = []
for record in SeqIO.parse(fasta_fh, "fasta"):
    for chunk in sequence_split_by_length(str(record.seq), sequence_chunk_length):
        enc_records.append(np.asarray(chunk, dtype=np.int8))
enc_arr = np.vstack(enc_record)

I changed 2 things:

Use dtype int8 instead of the default integer dtype. The default numpy integer is 32 or 64 bits depending on platform, while int8 is only 8 bits.
Collect 2D arrays (200x4) in a list instead of (1x4) vectors, since numpy arrays have significant memory overhead for small arrays.


How can I modify the core field "link" widget?

Question: I need to alter the "Embed Link" form provided by Drupal 8 in the node AddForm. Namely I need to add a select list form item to specify the "type" of the
For this I am trying to implement a hook_form_alter()
  if(isset($form['field_link_embed'])){
   $form['field_link_embed']['widget']['format'] = [
    '#type' => 'select',
    '#required' => TRUE,
    '#title' =>t("Link format"),
    '#options' => [
        'open' => t("option1"),
        'html' => t("option2"),
    ]
  ];

But I guess this is not the right chain how to access the form  $form['field_link_embed']['widget']['format'], could you please help me?
Comment: Are you trying to specify format for the `Link Text` or are you trying to make the `Link Text` a select box ?
Comment: I am trying to extend it with select box. So to say to add one more field
Answer: Here is quick and dirty hook_form_alter implementation that does this
Add this to your THEMENAME.theme or your MODULENAME.module
function THEMENAME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == "node_article_edit_form" || $form_id == "node_article_form") {
    $link_count = intval($form["field_link_embed"]["widget"]["#max_delta"]);
    for ($i = 0; $i <= $link_count; $i++) {
      if (isset($form["field_link"]["widget"][$i]["format"])) {
        continue;
      }
      $form["field_link"]["widget"][$i]["format"] = [
        '#type' => 'select',
        '#required' => TRUE,
        '#title' => t("Link format"),
        '#options' => [
          'open' => t("option1"),
          'html' => t("option2"),
        ],
      ];
    }
  }
}

NOTE: you have to modify node_article_form and node_article_edit_form and perhaps field_link_embed to match your setup.
Perhaps for more involved implementation you should create a dedicated field_formatter using web/core/modules/link/src/Plugin/Field/FieldFormatter/LinkFormatter.php as a starting point.
Comment: Will it create a column in database?
Comment: Nope that is why I said its a quick and dirty solution, the use case of the above solution is ruther limited, and you actually never mentioned in your description that this is a requirement.
Comment: Sure, it is. I am sorry. Do I need to open a new question for it?
Comment: yeah I suppose this is the best way, as this is probably a complete question/answer already


Is there any module for Restful API in drupal 7 with commerce

Question: I am working in a ecommerce website in drupal 7 by using commerce module, also developing for mobile (android/ios) application for the same project.
So that I want to send data's for mobile application, for that I am searching API integration module.
Anybody found any module or have any relevant idea?
Answer: Both Drupal and Drupal Commerce support API integrations with mobile apps.
Look into the following:

Start with Services for basic web service support in Drupal.
Throw Commerce Services on top of it to expose Drupal Commerce entities.

There are a couple of good articles by Tyler Frankenstein:

Drupal Services Example
Build a Mobile App to Sell Products with Drupal
Sell products with a custom mobile app a Presentation with Scott Hooker (then Commerce Guy) at DrupalCon Austin


How to render childcomponents inside content with ngx-markdown in Angular 14

Question: I've been banging my head against a wall for a while now trying to solve this problem. We have content coming in from an epi-server, the content is in HTML and needs to rendered dynamically in a component.
We are using ngx-markdown to do this quite succesfully when it's only "standard" html elements.
But sometimes we get component elements to render, but it seems like ngx-markdown just ignores these elements, I can see them while inspecting the page but they don't really load like components.
This is how it is set up:
dynamic-markdown.component.html
`<markdown [data]="html"></markdown>`

dynamic-markdown.component.ts
import { Component, Input, OnInit } from "@angular/core";

@Component({
  selector: 'dynamic',
  templateUrl: './dynamic-markdown.component.html'
})
export class DynamicMarkdownComponent implements OnInit {

  constructor() { }

    @Input() html: any;

    ngOnInit() {
    }
}

And this is how the dynamic component is loaded inside other components:
<dynamic [html]="mainBody.toString()" ></dynamic>

This is the content we get from the server inside the "mainBody.toString()" that we are trying to display in the dynamic component:

<download-file url="/api/document/51ecd42259554e88b93b5dd60de22105/Sortimentskiftesrapport 2017-12-01 (1)" [displaytext]="'Hämta bilagan med ändringsmarkeringar (xlsx)'"></download-file>.

"download-file" is our own component that we are trying to load.
As of now the "p" tags and the "." at the end is all that shows. When inspecting the page I can see that there is an  element in between the "p" tags but it doesnt show anything.
I can confirm that the  component should display content because if I just hardcode it into the page it shows up fine.
This is in Angular 14, and ngx-markdown@^14.0.1
Does anyone know why this happens or how I can make the markdown component load components succesfully?
I have tried going through all the documentation I could find on: https://jfcere.github.io/ngx-markdown to see if anything was specified there on loading components inside the content. I also have searched everywhere online but can't seem to find anyone else with the same issue.
Answer: In my case a part of the solution is to disable the sanitizer on the markdown component using [disableSanitizer]="true"
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


An inequality about sequences in a $\sigma$-algebra

Question: Let $(X,\mathbb X,\mu)$ be a measure space and let $(E_n)$ be a sequence in $\mathbb X$. Show that $$\mu(\lim\inf E_n)\leq\lim\inf\mu(E_n).$$
I am quite sure I need to use the following lemma.
Lemma. Let $\mu$ be a measure defined on a $\sigma$-algebra $\mathbb X$.

If $(E_n)$ is an increasing sequence in $\mathbb X$, then
$$\mu\left(\bigcup_{n=1}^\infty E_n\right)=\lim\mu(E_n).$$
If $(F_n)$ is a decreasing sequence in $\mathbb X$ and if $\mu(F_1)<+\infty$, then
$$\mu\left(\bigcap_{n=1}^\infty F_n\right)=\lim\mu(F_n).$$

I know that
$$\mu(\liminf_n E_n)=\mu\left(\bigcup_{i=1}^\infty\bigcap_{n=i}^\infty E_n\right)=
\lim_i\mu\left(\bigcap_{n=i}^\infty E_n\right).$$
The first equality follows from the definition of $\lim\inf$ and the second from point 1 of the lemma above. Here is where I am stuck.
Answer: Note that $\mu\left(\bigcap_{n=i}^\infty E_n\right)\leq\inf_{n\geq i}\mu(E_n)$
and by this definition you get
$$
  \lim_i\mu\left(\bigcap_{n=i}^\infty E_n\right)\leq\lim_i\inf_{n\geq i}\mu(E_n) = \liminf_n\mu(E_n)
$$
Answer: For every $i\geq 1$ we have that
$$
\bigcap_{n=i}^\infty E_n\subseteq E_i
$$
and so for all $i\geq 1$
$$
\mu\left(\bigcap_{n=i}^\infty E_n\right)\leq \mu(E_i).
$$
Then
$$
\mu(\liminf_n E_n)=\lim_{i\to\infty}\mu\left(\bigcap_{n=i}^\infty E_n\right)\leq \liminf \mu(E_i),
$$
using the fact that if $(x_n)_{n\geq 1}$ and $(y_n)_{n\geq 1}$ are sequences with $x_n\leq y_n$ for all $n$, then $\liminf x_n\leq \liminf y_n$.


Cisco ASA: How to free memory without reboot?

Question: How can I free up some memory in our Cisco ASA 5510 without rebooting it?
We urgently need to free memory otherwise it will crash, but we can't reboot it in the next 2 days.
Answer: First figure out what is eating up your memory
sh mem detail
sh proc detail

Something like this could bring the memory down but might not be what you desire.  Also remember logging takes memory I belive.
clear conf threat-detection

Comment: Thanks! We deactivated some options and seems that the memory is decreasing very slowly (aprox 1% every 3 hours). We are hitting now 95% memory usage.


Does Qt platform for Linux support X5800?

Question: 4 months ago, after many installations of sdk, qt, libraries, mameo etc. I realized that Qt simulator for touch devices only supports windows. We linux users could only use button based old phone sim.
I'm in the forum.nokia site searching for and improvement for 20 mins. Couldnt find any related information.
Answer: X5800 is symbian based phone, You can download Qt for symbian SDK from here,
http://qt.nokia.com/products/platform/symbian/
Here are some tutorial videos for your help,
http://labs.qt.nokia.com/2009/12/03/tutorial-videos-qt-development-for-symbian/
Here is a good book for Qt for Symbian.
http://www.amazon.com/Qt-Symbian-Frank-H-Fitzek/dp/0470750103
Happy Hacking!


Angular 6 routing issue with deployment to Apache (URL not found 404)

Question: I have a small Angular 6 app that works as expected when using 'ng serve' and localhost:4200. If I refresh a page or manually type a URL I get the expected results and the page loads.
However, when I build a distribution using 'ng build --base-href=/quickorder/' the app runs fine until I do a refresh or type the url in a tab wheen I get URL not found 404 with the URL being shown as the part after the servername.
The dist is placed in Apache's htdocs in a folder named quickorder and the URL is .
The Apache conf file for the dist is basically standard apart from changing the SRVROOT to reflect Apache's location.
app.modules.ts
 const appRoutes:Routes = [
  {
    path: '',
    component: LoginComponent
  },
  {
    path: 'order-input/:ref/:name',
    canActivate: [AuthguardGuard],
    component: OrderInputComponent
  },
  {
    path: 'order-input',
    canActivate: [AuthguardGuard],
    component: OrderInputComponent
  },
  {
    path: 'trad-verify',
    canActivate: [AuthguardGuard],
    component: TradVerifyComponent
  },
  {
    path: '**',
    component: LoginComponent
  }
 ]

Thanks for any help you can provide me,
Mark.
P.S. Looking at the Apache docs for 2.4 they recommend not using an .htaccess if you have access to httpd.conf and all .htaccess commands can go into the httpd.conf

<Directory />
   RewriteEngine On
   RewriteBase /quickorder
   # If an existing asset or directory is requested go to it as it is
   RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
   RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
   RewriteRule ^ - [L]

   # If the requested resource doesn't exist, use index.html
   RewriteRule ^ /index.html
   Options FollowSymLinks
   AllowOverride All
   #AllowOverride none
   #Require all denied
</Directory>

However, this gives me an error rresponse from the server;
You don't have permission to access /cgi-bin/dugquickorder.cgi/wh
on this server.
Comment: Your `.htaccess` should redirect every incoming request to `index.html`.
Comment: I'm sorry I can't, I know the answers but don't know how to apply them (mostyle because I have never used Apache). A quick google search will explain it to you : https://www.alvinpoh.com/how-to-create-and-use-htaccess-files-for-apache-web-server-in-microsoft-windows/
Comment: Hi, Thanks. I'm on Windows and can't see an .htaccess file in the Apache folders. could you provide an example of how do do this please?
Comment: No problem. I'm Googling now...
Comment: (I gave you a website)
Answer: Solved. In Apache 2.4 an .htaccess file is not required (if you have access to httpd.conf). The changes can go inside a 'directory'
#
# Deny access to the entirety of your server's filesystem. You must
# explicitly permit access to web content directories in other
# <Directory> blocks below.
#
<Directory />
    AllowOverride none
    Require all denied
</Directory>

<Directory C:\Apache\Apache24\htdocs\quickorder\>

RewriteEngine On
    # If an existing asset or directory is requested go to it as it is
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
    RewriteRule ^ - [L]

    # If the requested resource doesn't exist, use index.html
    RewriteRule ^ \index.html
    AllowOverride All
</Directory>

Answer: Refer the following link:
https://blog.neoprime.it/ng-in-httpd/
It helped to resolve the problem. I have not used any .htaccess file but have overridden httpd.conf.


? Is there a known issue with Internet Explorer and Jquery's $("document").ready(function()?

Question: This is a generic question so not really any code to show in this question.
I am having a problem getting a particular jquery script to run in IE9 (indeed any version of IE)
Most annoyingly it appears to be slightly hit or miss which is making debugging this very difficult.
In FF and Chrome it runs completely without issue.
But in IE the script will only run if you press F5 to refresh.
Obviously I am using
$("document").ready(function() {

    alert("start control script");
    // lots more code here
};

By observation it appears that once I have run the script once if I subsequently logout and log back in all is well. But If I close the browser completely I am back to needing to press F5 to get the script started. This is only happening in IE.
I imagine that it works once I have refreshed and logged out due to some kind of caching which is lost when I close the browser completely.
Any thoughts welcomed.
Comment: I believe the correct syntax is

`$(document).ready(...)`

is that the problem?
Comment: and the missing parenthesis. basic syntax errors.
Answer: You have written it incorrectly, document is a global object & does not need quotes around it.
$(document).ready(function() {

    alert("start control script");
    // lots more code here
});

Notice the lack of quotes around the word document & the missing parenthesis at the end.
Comment: Also it lacks a closing `)` on last line.
Comment: Yes the ending ) just a typo in SO. It was the "". Couldn't see this for life of me. Don't know how I missed that.
Answer: You don't need document in quotes also you are missing parenthesis ) at the end.
$(document).ready(function() {

    alert("start control script");
    // lots more code here
});

Answer: From jQuery documentation:
All three of the following syntaxes are equivalent:
$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)

There is also $(document).bind("ready", handler), deprecated as of jQuery 1.8. This behaves similarly to the ready method but if the ready event has already fired and you try to .bind("ready") the bound handler will not be executed. Ready handlers bound this way are executed after any bound by the other three methods above.
The .ready() method can only be called on a jQuery object matching the current document, so the selector can be omitted.
The .ready() method is typically used with an anonymous function:
$(document).ready(function() {
  // Handler for .ready() called.
});

Which is equivalent to calling:
$(function() {
 // Handler for .ready() called.
});

If .ready() is called after the DOM has been initialized, the new handler passed in will be executed immediately.


sendmail (or postfix) is always failing with Helo command rejected

Question: On digitalOcean this tutorial points to installing postfix.  I've attempted this and also uninstalling postfix then installing sendmail
When a test mail is sent, invariably there is an error in identifying the sender
 451 4.7.1 <m-dev>:  Helo command rejected: HELO string 'm-dev' does not match last HELO string 'theactual.ws' from this IP *(when testing with sendmail)*

[with postfix it complains about it being sent by no-reply@m-dev...]
The tutorial suggests The System mail name must be the same as the name you assigned to your server.  But that is simplistic, and has a high probability of not being respected.
Well, the domain name was not assigned to the server.
hostname does return the assigned m-dev name.
How can Ubuntu 20.04 be set-up to use a FQDN that actually points to this server (+ has SPF and DKIM configurations set) ?
When attempting with postfix the  postfix -n returns
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
append_dot_mydomain = no
biff = no
compatibility_level = 2
inet_interfaces = all
inet_protocols = loopback-only
mailbox_command = procmail -a "$EXTENSION"
mailbox_size_limit = 0
mydestination = localhost.$mydomain, localhost, $myhostname
myhostname = m-dev
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
myorigin = /etc/mailname
readme_directory = no
recipient_delimiter = +
relayhost =
smtp_tls_CApath = /etc/ssl/certs
smtp_tls_security_level = may
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
smtpd_tls_cert_file = /etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file = /etc/ssl/private/ssl-cert-snakeoil.key
smtpd_tls_security_level = may

Comment: edit completed.  ` $ hostname     market-dev`  is still being returned at the console prompt  while `echo "This is the body of the email" | mail -s "This is the subject line" some@addresscom` now hits
`mail: cannot send message: Process exited with a non-zero status`
Answer: Other mail servers on the Internet generally expect your server to identify itself using its fully qualified domain name, and for the relevant forward and reverse DNS records to match. This does not require any special Postfix configuration on Linux systems which already have their hostname set to the FQDN, but Debian chose to use only an unqualified hostname (which causes a lot of other issues that have to be worked around, this being one of them).
First, you will need to decide what the fully qualified domain name is for this machine. It must not be a naked domain name. Once you have done that, you need to set the DNS address records for that name to the IPv6 and IPv4 addresses of your system, set the PTR records for those addresses to that FQDN, and finally in Postfix, set myhostname to the FQDN.
Finally, if that mail server has remembered something else as your FQDN, (which itself is quite unusual) you will probably have to wait for it to forget before you are able to send mail to it again.
Comment: This is exactly what I understood in terms of dynamics.  However, what do you mean by 'naked domain name'.  I set `myhostname = theactual.ws`.  New evolution: `echo "body" | mail -s "subject" email@example.com` logs, has a message-id with the FQDN and delivers.  But an app on the VPS (rails) `ActionMailer::Base.mail([...]).deliver_now` feedsback `Delivered mail 61[...]firstname.lastname@example.com (4028.0ms)` setting up the message-id similarly. It is not logged, queue is empty and message undelivered.


Is a subalgebra of a normed algebra again a normed algebra?

Question: Suppose that $(A,\parallel\cdot\parallel)$ is a normed algebra (with or without an identity) and $B\subseteq A$ is a subalgebra of $A$. It is said in my textbook that $B$, together with the induced norm, is also a normed algebra.
However, it is assumed that the norm of the identity in a unital normed algebra is $1$. If $B$ happens to contain an identity $\mathbf{1}_B$, then in order for $B$ to become a normed algebra, we need to show that $\parallel\mathbf{1}_B\parallel=1$. Since $\mathbf{1}_B$ is not necessarily the identity in $A$, it is not guaranteed that $\parallel\mathbf{1}_B\parallel=1$. So I think $B$ may not also be a normed algebra.
Any comments on this issue?
Comment: @MarianoSuárez-Álvarez Let $M_2$ be the algebra of all 2×2 matrices over the reals, and let $\parallel\cdot\parallel$ be the norm on it defined by $\parallel A\parallel=\frac{1}{\sqrt{2}}\parallel A\parallel_F$, where $\parallel\cdot\parallel_F$ is the Frobenius norm. The norm $\parallel\cdot\parallel$ makes $M_2$ a unital normed algebra with identity $I$. The 2×2 matrices for which all entries are zero, except for the first one on the diagonal, form a subalgebra. This subalgebra is not a normed algebra since the norm of its identity (1,0,/0,0) is $\frac{1}{\sqrt{2}}$, not $1$. Am I correct?
Comment: @MarianoSuárez-Álvarez If this example makes sense, then the statement "a subalgebra of a normed algebra is a normed algebra" is not correct in general. Am I right?
Comment: Two questions about definitions:  Does your textbook's definition of a normed algebra require that $\|ab\|\le\|a\|\,\|b\|$ for all $a,b\in A$? Does your textbook define a subalgebra to contain the unit of the larger algebra?
Comment: @Aweygan 1)Yes, the norm is submultiplicative; 2)No. A subalgebra is a subspace closed under multiplication.
Comment: Could you please share the author/title of the textbook?
Comment: @Aweygan Oh, it's actually not a textbook but a set of lecture notes on C* algebra. See this link (the statement is right after definition 1.5): https://math.dartmouth.edu/~dana/bookspapers/cstar.pdf
Comment: I see, thanks for sharing!  I have updated my answer to hopefully clarify the issue
Answer: This is a subtle point, one that the author barely mentions, but a unital normed algebra is more than just a normed algebra with a unit.
A unital normed algebra is a normed algebra $(A,\|\cdot\|)$ with a unit $1_A\in A$ such that $\|1_A\|=1$.
While a subalgebra of a normed algebra is itself a normed algebra, it is not true that a unital subalgebra of a unital normed algebra is itself a unital normed algebra
Indeed, suppose $(A,\|\cdot\|)$ is a unital normed algebra containing an idempotent $e$ with $\|e\|>1$, and let $B=eAe$.  Then $B$ is a subalgebra of $A$, with unit $e$, but it is not a normed algebra with the norm induced by $A$, as the unit of $B$ does not have norm one.


mongo-rust-driver v2.1.0 compilation failure

Question: rustc 1.60.0-nightly (17d29dcdc 2022-01-21) running on x86_64-pc-windows-msvc
I don't know how to solve, I deleted main to such an extent that it still reports an error
main.rs:
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    println!("Hello, world!");
    Ok(())
}

error:
Compiling mongodb v2.1.0
error: internal compiler error: compiler\rustc_mir_transform\src\generator.rs:755:13: Broken MIR: generator contains type ClientOptionsParser in MIR, but typeck only knows about {ResumeTy, impl AsRef<str>, std::option::Option<resolver_config::ResolverConfig>, bool, client::options::ClientOptions, [closure@C:\Users\BORBER\.cargo\registry\src\mirrors.tuna.tsinghua.edu.cn-df7c3c540f42cdbd\mongodb-2.1.0\src\client\options\mod.rs:1100:69: 1100:90], impl futures_util::Future<Output = std::result::Result<SrvResolver, error::Error>>, (), SrvResolver, &Vec<client::options::ServerAddress>, Vec<client::options::ServerAddress>, usize, &client::options::ServerAddress, client::options::ServerAddress, &str, impl futures_util::Future<Output = std::result::Result<ResolvedConfig, error::Error>>} and [impl AsRef<str>, std::option::Option<client::options::resolver_config::ResolverConfig>]
    --> C:\Users\BORBER\.cargo\registry\src\mirrors.tuna.tsinghua.edu.cn-df7c3c540f42cdbd\mongodb-2.1.0\src\client\options\mod.rs:1092:23
     |
1092 |       ) -> Result<Self> {
     |  _______________________^
1093 | |         let parser = ClientOptionsParser::parse(uri.as_ref())?;
1094 | |         let srv = parser.srv;
1095 | |         let auth_source_present = parser.auth_source.is_some();
...    |
1145 | |         Ok(options)
1146 | |     }
     | |_____^

thread 'rustc' panicked at 'Box<dyn Any>', /rustc/17d29dcdce9b9e838635eb0adefd9b8b1588410b\compiler\rustc_errors\src\lib.rs:1115:9
stack backtrace:
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
note: the compiler unexpectedly panicked. this is a bug.
note: we would appreciate a bug report: https://github.com/rust-lang/rust/issues/new?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md
note: rustc 1.60.0-nightly (17d29dcdc 2022-01-21) running on x86_64-pc-windows-msvc
note: compiler flags: -C embed-bitcode=no -C debuginfo=2 --crate-type lib
note: some of the compiler flags provided by cargo are hidden
query stack during panic:
#0 [optimized_mir] optimizing MIR for `client::options::<impl at C:\Users\BORBER\.cargo\registry\src\mirrors.tuna.tsinghua.edu.cn-df7c3c540f42cdbd\mongodb-2.1.0\src\client\options\mod.rs:973:1: 1261:2>::parse_uri::{closure#0}`
#1 [layout_of] computing layout of `[static generator@C:\Users\BORBER\.cargo\registry\src\mirrors.tuna.tsinghua.edu.cn-df7c3c540f42cdbd\mongodb-2.1.0\src\client\options\mod.rs:1092:23: 1146:6]`
#2 [layout_of] computing layout of `core::future::from_generator::GenFuture<[static generator@C:\Users\BORBER\.cargo\registry\src\mirrors.tuna.tsinghua.edu.cn-df7c3c540f42cdbd\mongodb-2.1.0\src\client\options\mod.rs:1092:23: 1146:6]>`
#3 [layout_of] computing layout of `impl core::future::future::Future<Output = [async output]>`
#4 [optimized_mir] optimizing MIR for `client::options::<impl at C:\Users\BORBER\.cargo\registry\src\mirrors.tuna.tsinghua.edu.cn-df7c3c540f42cdbd\mongodb-2.1.0\src\client\options\mod.rs:973:1: 1261:2>::parse_uri`
end of query stack
error: aborting due to previous error

error: could not compile `mongodb` due to previous error

Comment: sometime a cargo clean help, this is a ICE, a bug inside rustc, there is not much you can do
Comment: Does this error have anything to do with my use of nightly?
Comment: I think [this issue](https://github.com/rust-lang/rust/issues/93254) is the same ICE as yours.
Answer: just use stable!
    Finished dev [unoptimized + debuginfo] target(s) in 0.61s
     Running `target\debug\my-mongodb.exe`
Hello, world!