flutter_callkit_incoming notification isn't received in terminated or background state in iOS using Flutter

Question: Flutter Incoming Callkit notifications are working fine on my iOS app in all states (foreground/background/terminated).
On iOS device, issue is when my app is in background or terminated state and if I open any other app after closing or minimizing my application , I stop getting callKit notification in both background/terminated state.
I don't know that which part can cause this issue i.e if its from my code or its the problem in iOS device itself. Because besides opening another app after closing/minimizing my app, I am getting call notifications in all states of my app.
[Note: Everything is working fine in the Android app]
This is the silent notification being received to the receiver from cloud function.
  await admin.messaging().send({
    token: token_o,
    notification: {
    },
    data: {
      imageUrl: requesterImageUrl,
      chatRoomId: chatRoomId,
      screenName: 'voiceScreen',
      voiceCall: 'voiceCall',
      callerName: requesterName,
      callsDocId: callsDocId,
      senderId: requesterId,
    },
    android: {
        notification: {
            click_action: "android.intent.action.MAIN"
        },
    },
     apns: {
              headers: {
                apns_priority: "10",
              },
              payload: {
                aps: {
                  badge: 1
                },
                notification: {
                title: "iOVoiceCallNotification",
                body: {},
                                  },
                mutable_content: true,
                content_available : true,

              }
            }
  }).then(value => {
    functions.logger.log("Notification for AudioCall is sent to the Receiver");
  }).catch((e) => {
    functions.logger.log(e.toString());
  });

I can provide anyother code or log if required.
Comment: is enable to background modes at voice over ip?
Comment: @JunsuCho yes it is
Comment: @BilalSaeed-FlutterDeveloper hi do you find a solution for that. I am in the same situation. It works fine for android but for ios the incoming call shows only when the app is in foreground. Do you manage to fix this??
Comment: Hi, Can someone provide me full sourcecode? because it is not working even on android in terminated state. I checked the example source code of "flutter_callkit_incoming" but didn't find anything there
Answer: I simply had to configure pushKit to awake iOS from background & terminated state.
Note: Even for pushKit, I had to create a token for iOS device from the getVoipToken() function that is present in flutter_call_kit incoming package.
Comment: can you please tell how you configured pushkit ??
Comment: Check this [pacakge](https://pub.dev/packages/flutter_ios_voip_kit)
Answer: Inorder to recieve callKit notifications perfectly in background/terminated states in IOS you have to do following necessary things:

Implement APNs (Apple push notifications) for IOS. Because IOS devices will not wake the phone and show call when you send firebase notifications in background/terminated states. IOS devices require APNs to achieve this.
Follow the instructions written in PUSHKIT.md if you are using flutter_callkit_incoming package for flutter app.
Configure your backend (from where you want to recieve notifications) to send both firebase and APN notifications depends upon the device user is using. (I recommend you to send the platform e.g "android" or "ios" along with the device token to your backend when you register the firebase token in flutter app. You can also ask for IOS deviceToken from firebase.

I know its very lengthy process but it is. I was also very disappointed when I was required to integrate call notifications in my app and I have to do all this on my frontend app and backend.


Is there a way to program I OpenCL without 3rd party plugins? C#

Question: I realise the question of how to run C# on the GPU is a common question but my question is a bit different. Is there a way to do it without 3rd party frameworks (such as Cudafy). I don't  want to use plugins because I'm making a program which I intend to be 100% my own code (personal ambition) and in feel I won't learn as much if I do.
Would I simply need to create a kernel and compile it and call it from c# (process.start()) or is there a better way of doing it.
How do I go about making a kernel? I am beginner with GPGPU so sorry for my ignorance. However, I am a very advanced c# programmer.
Comment: You can't use opencl in C# without C# bindings or without using C++ dll. You need somehow bind opencl.lib and some header files but you can't do  that in C#. Khronos' site gives C++ headers only. Start with C++ then. You'll need it later anyway. Why? For example, to map a memory area to GPU copy engines, you need the source buffer to be aligned on say 4096-bytes-multiple. C# doesn't have this but easily done inside C++. Another example could be C# moving all buffers unless you pin them. If you don't create them from C++, gpu-cpu communication performance suffers.
Comment: I think you can use hlsl to do it that isnt opengl.
Answer: After a long time, I have finally come up with a solution to my issue. I created bindings to the (unmanaged) OpenCL.dll. It then uses some tricks to be able to run the code on the GPU by using an attribute. The best way I can describe it is like Cudafy, but it is quite different.
Thanks to those who replied to my question.


Pra que serve o "self "?

Question: Estou estudando Python para complementar meus programas em Nodejs.
Porém por que em Python, uma linguagem que preza a velocidade no desenvolvimento e facilidade no código, é utilizado o self?
Exemplo bem simples do uso do self
class ButtonPerson(Button, Person):
    def __init__(self, name):
        Person.__init__(self)
        Button.__init__(self, "Pessoa: " + name)
        self.set_name(name)

Não é redundante?
Comment: [*Explicit is better than implicit*](https://www.python.org/dev/peps/pep-0020/#the-zen-of-python)
Comment: @bfavaretto achei legal essa filosofia, mas ainda não vejo o pq do self...rs
Comment: Pra eu entender melhor a pergunta: como você escreveria algo com essa mesma estrutura em JS, já que você disse que usa node?
Answer: Embora em outro idioma, esta pergunta foi respondida no próprio STO. Então fiz apenas uma adptação:
A razão pela qual você precisa usar o self é porque o Python não usa a sintaxe @ para se referir aos atributos de instâncias.
O time do Python decidiu fazer métodos de uma maneira que faz com que a instância a qual o método pertence seja passada automaticamente, mas não recebida automaticamente: O primeiro parâmetro de um método é a instância em que o método é chamado.
Isso faz com que os métodos sejam inteiramente iguais às funções, e deixa o nome real para ser usado, a cargo do usuário/desenvolvedor (embora a palavra self seja a convenção e a maioria das pessoas torcerão o nariz se voce usar uma outra palavra qualquer).

Editada
  Exemplo evitando o self (não torçam o nariz!) :-)
  Obs. Rodei em um terminal (local) python 3, no repl.it não foi aceito, exige o self

class Foo():
    def __init__(this, msg):
        this.msg = msg

    @property
    def bar(this):
        return 'Hello '+this.msg

foo = Foo('bar')
foo.bar
'Hello bar'

self Não tem nada de especial para o código, é apenas mais um objeto.
O desenvolvedores do Python poderiam ter optado por outra estrategia para distiguir "nomes normais" de atributos -- Sintaxe especial como o Ruby, ou requerer declarações como o C++ e Java ou, talvez, qualquer outra coisa diferente-- SQN.
Python tem como um dos pilares de sua filosofia a determinação de fazer as coisas da forma mais explícitas possível, embora, obviamente esse objetivo nem sempre possa ser atingindo.
Em consequencia desse objetivo é que voce precisa do self, para fazer uma atribuição a um atributo de instancia, é necessário explicitar a que instancia atribuir, self informa que a atribuição é a si mesmo.
Answer: Uma comparação que talvez te ajude a entender, é pensar no self como se fosse o this do java/C#. Que não fica explicito na implementação mas também aponta para o próprio objeto.
No caso do python, quando você chama um método de uma classe ele automaticamente passa esse parâmetro na primeira posição.
O primeiro parâmetro de uma classe, recebe uma instância desse mesmo objeto e serve para acessar atributos e métodos do mesmo objeto.

Gostaria de deixar claro que não há nenhuma obrigatoriedade de se fazer assim podemos usar qualquer outro nome para o parâmetro.

Costuma-se chamar o primeiro parâmetro de self porque a maioria dos
  programadores Python já reconhece esse nome como o nome do objeto a
  ser invocado no método; ademais, esse é o padrão especificado pela
  PEP-8. Por isso mesmo, via de regra é melhor utilizar self como o nome
  do primeiro parâmetro dos métodos.

Pra que serve o "self "?


Como posso usar o Gesture com o GridView?

Question: Preciso de ajuda para quando o usuário clicar na imagem, abrir a página correspondente.
<code>import 'package:flutter/material.dart';
import 'package:health/page-health/doador.dart';
import 'package:health/page-health/imc.dart';

class GridDasboard extends StatelessWidget {
   Items item1=  new Items( title: "IMC - Peso e Altura", img: "assets/images/balanca.png" );
  Items item2 = new Items(title: "Doador ", img: "assets/images/doador.png");

   var links = [
     IMCPage(),
     DOAPage(),

   ];

  @override
  Widget build(BuildContext context) {
    List<Items> myList = [item1, item2];
    var color = 0xffD3D3D3;

    return Flexible(
      child: GridView.count(
          childAspectRatio: 1.0,
          padding: EdgeInsets.only(left: 8, right: 8),
          crossAxisCount: 2,
          crossAxisSpacing: 18,
          mainAxisSpacing: 18,
          children: myList.map((data) {
            return Container(
              decoration: BoxDecoration(
                  color: Color(color), borderRadius: BorderRadius.circular(10)),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset(
                    data.img,
                    width: 42,
                  ),
                  SizedBox(
                    height: 14,
                  ),
                  Text(
                    data.title,
                    style: Theme.of(context).textTheme.headline6,
                  ),

                  GestureDetector(
                    onTap: () async {
                      await Items();
                    },
                  ),
                ],

              ),
            );

          }).toList()),

    );

  }
}

class Items {
  String title;
  String img;
  Items({this.title, this.img});
}
</code>
Comment: De uma olhada nesses dois links, devem lhe atender: [Navegando entre telas no Flutter](https://www.youtube.com/watch?v=UKkAUkrhwH4); [Navegação entre telas (Rotas Nomeadas)](https://www.youtube.com/watch?v=9olJ-lTSM8E).
Comment: obrigada, mas meu objetivo é a partir de uma imagem no gridview ir para a page
Comment: Certo... Então EDITE sua pergunta e explique seu problema, de mais detalhes. Pois vi que você está utilizando ali o `GestureDetector` que deixa o _Widget_ clicável, sendo assim, basta apenas aplicar o que foi ensinado nos vídeos que indiquei.
Comment: Se lhe ajudar, a estrutura do item deve ser `return GestureDetector > Container > Column`, ou seja, você precisa deixar o `GestureDetector` por primeiro, assim cada item da grid será clicável.
Answer: Vc pode cobrir o Container, dps do retorno com o Widget Gesture Detector. Q ai o container todo vai virar uma espécie de objeto clicavel. E vc acrescenta o onTap e nele coloca um navigator para a pagina q vc quer exibir


How to pass a variable with in jquery

Question: I just started using jQuery in the past few days. I love how it makes functions simple. However because I am very new to using Javascript, I keep hitting a road block with one function.
I am trying to bind a couple functions together, but I'm not sure if I am doing it in the right order. What I want it to do is get a variable from a selector href='#from=xxxxx&to=xxxxx', with the xxxxx being a value printed out from a DB using PHP.
Then create a DOM window to display a form and insert those values into the hidden input fields. I have been stuck trying to figure out a way to pass those variables from the link to the form.
Here is my script:

<?php   $from="0";  $to="0";
for ($x=1; $x<=4; $x++){ $from++; $to++;    ?>
<a href="#from=<?php echo $from;?>&to=<?php echo $to;?>" class="foo">user<?php echo $x;?>

<?php } ?>

Answer: In the handler for the click event on each link you can get a reference to the target link and extract the values from the href attribute and then set the values of the hidden fields in the form.
$('.foo').click(function() {

var href = $(this).attr('href'); // will contain the string "#from=0&to=0"

var from,to = ... // extarct from string by splitting by & or using url parse library

$('#msgBox').find("input[name='from']").val(from);
$('#msgBox').find("input[name='to']").val(to);

// rest of code...

});

Comment: Hi, thanks for the response, How can I pass the values into the form tho. I somewhat was able to separate the values before. Also the rest of the code might show you what I am trying to do.

How to pass a variable with in jquery


Set path of Header files to avoid using relative paths (VS2015/c++)

Question: H, i'm trying to set my project up so that i can avoid using relative paths for my header files in my project. The reason is that the project is multi-platform and I would like to avoid restructuring each use dependent on which system it's compiled on.
Currently, the header files do not use the correct path way and the only way i can use the includes is if i set relative paths to the files.
E.G.
for my file render.h i want to use:
#include "math/matrix.h" <--- this doesn't work

but
#include "../math/matrix.h" <--this works

What would i be doing incorrectly here for setting up the project?
in the Properties page, i have set up the following
VC++ Directories -> Include Directories -> C:\Game\math
C++ -> General -> Additional Include Directories -> C:\Game\math
If i right click on the .cpp files and go to properties, i have the C\C++ options but the Headers do not.
Answer: If your file resides in C:\Game\math\matrix.h, then an Include Directory of C:\Game\math and #include directive of "math/matrix.h", would produce a concatenated result of C:\Game\math\math/matrix.h. You simply need to change your Include Directory to be C:\Game (or your #include to be only "matrix.h").
Also, generally you set include directories per-project, not per source (.cpp) file. The reason that the header files do not have C++ compilation options is that they are not compiled - only the sources are compiled.


Basic Help Needed in Coding Data Using Stata

Question: id  Year  Lat  Long
 1  1990   10    11
 3  1994    2     8
 .  1998    2     8
 1  1993    .     .
 1  1991   10     .
 3  1996    .     8

I recently started working with Stata and I am having some difficulty coding my data. Attached above is a sample of what the data looks like. The idea is that I have a time series of objects with known latitudes and longitudes. The data, however, has some missing values. For example, in the 3rd row the id should be 3 because the latitude and longitude are the same as row 2. Also, in row 4, the latitude and longitude should be 10 and 11 respectively because the id is the same as in row 1. How will I go about coding this? Is there a simple command in Stata that can solve this issue? My understanding of Stata is fairly basic because I have just started using it.
Edit: It should look like this in finalized form:
id  Year  Lat  Long
 1  1990   10    11
 3  1994    2     8
 3  1998    2     8
 1  1993   10    11
 1  1991   10    11
 3  1996    2     8

Comment: Even if just starting with new software, you should be prepared to answer: [what have you tried?](http://mattgemmell.com/what-have-you-tried/) A more informative title is also recommended.
Comment: It will help to add what you have tried. But this is probably enough to be migrated now.
Comment: So how do I transfer it? thanks for the help
Answer: Try this: http://www.sealedenvelope.com/stata/xfill/
Other ways here: http://www.stata.com/support/faqs/data-management/replacing-missing-values/
Or carryforward from SSC.


Organic Groups and Workbench or Revisioning together. Will this work?

Question: I'm building a D7 site using Organic Groups and would like some revisioning control.
Is it likely that something like Workbench or Revisioning will work nicely with Organic Groups?
I'm interested in hearing of any good or bad experiences or advice.
I've done some initial tests and Workbench appeared to work okay. Of course the number of configurable options tends to explode with two node access modules. It gets quite complicated. The Revisioning module wasn't quite so smooth. I seemed to get into a situation where an item wasn't visible to a normal group member when it should be but it could be fixed if the author / moderator simply edited the item and saved without doing anything. Maybe I need to have another play with that.
These modules actually do a lot more than we need. We don't really need multiple roles for author, moderator etc. Mostly "all" we'd like is the ability for a user to edit and save an existing node but see what it looks like before making it public. The "Preview" button does that (sort of) but it would be nice to be able to save changes, take a break, and come back later. Also, the public view maybe in a panel so "Preview" doesn't really show the final result.
Thanks
Answer: We've built a D7 site with Organic Groups and Revisioning and have found that installing Organic Groups causes a pretty major problem with Revisioning in that the Author and Moderator roles cannot see unpublished content.  We've confirmed on a clean Drupal installation that Organic Groups Access Control is the cause of the issue.
The only workaround that we found was to check the Bypass Access Control checkbox for those roles.  That means those roles bypass all security checks on content on the site so they can edit/delete/publish any content.  That is an okay work around for our site but did present a problem when we wanted a separate moderator role for just one content type.
See this post for full details -> http://drupal.org/node/1494232
We are planning on looking at Workbench for a different D7 site because Revisioning and Rules isn't going to be sufficient for the workflows.
Answer: I think you'd want to go with one of these options:

OG Workflow
Workbench OG

...depending on whether you prefer Workflow or Workbench Moderation.  To help with that decision, What is the difference between the Workbench and Workflow modules? may be useful.
At the time of this writing, Workbench OG is more popular by a factor of 6.
There doesn't seem to be a good Revisioning solution because of Revisioning and Organic Groups Access Control - requires rebuild perms all the time.


Malicious program changing my DNSs

Question: Some weeks ago I started having problems with my internet connection, it was extremely slow and suddently some websites (specifically gmail, facebook, youtube and twitter) started failing to connect, while the rest connect normally. Some days after, those same websites started showing me a message in portuguese: "Nova atualização disponível" whenever I tried to connect and a .exe file started downloading ("internet_update.exe" or something like that).
That's when I freaked out! It was definitely a virus or something like that, but it was really weird because I never had a problem like that (I run Linux). So I turned on my old PC (running Windows XP) and it turned out it had the same problem! the same message was showed whenever I tried to connect one of those specific websites, while the rest loaded without problems. Even in my Android smarthphone the same message was showed.
So it was obvious that the problem was not in a particular machine but in the router itself. So I started googling and I found some information, unfortunately I only found some in spanish, so I will make you a short summary:
It is a new banking trojan developed specifically to infect and collect information from Brasilian banks. Apparently now it has expanded to Argentina and Peru.
So how does it work? It spreads through social networks (videos, links, ...) and then it "takes control" of your internet connection by changing the values of your DNSs. More specifically, it changes the Primary DNS to one of this IPs: 18.104.22.168, 220.127.116.11 or  220.127.116.11 and the Secondary DNS to 188.8.131.52, this secondary DNS is actually the Google Public DNS, and it is configured this way so that your internet connection continue working properly and the user does not notice anything.
The important part here is that because no download or install has been made in your machine, no antivirus will notice any change. After your DNSs have been changed, the trojan controls every single website you connect to and this way they steal your bank information.
So after reading about this I accesed to my router and I restored my Primary and Secondary DNSs to their proper values, but one day after I had the same problem again.
This is actually a 50% warning post - 50% help me! post.
So, here comes the question: Is there any possible way to prevent my DNSs of being changed?
Answer: It definitely sounds like your router has been compromised. Your best best would be to nuke / replace it as once this happens your internal network is vulnerable.
As a workaround don't use DHCP to set your DNS servers but enter them directly onto your workstation.
Comment: I reset the router the first time I corrected the DNSs values, but the problem came back. Sorry, but what do you mean with "enter them directly onto your workstation"?
Comment: You can enter static IP and DNS (or just DNS) entries on your computer. I would be more concerned about stopping your router from being tampered with.
Comment: I'm really concerned about stopping my router from being tampered with, but I don't seem to find anyway of doing it.

Malicious program changing my DNSs


How to allow users to change my Accurev stream

Question: I'm going to be on vacations for a month, the stream needs to be supported. How to allow other users to change my Accurev stream (change time label, backed stream, etc.)?
Answer: By default anyone can change the time basis, rename a stream, apply locks, etc..to streams.  The only way to prevent these operations from occurring is thorough the server_admin_trig.  If you have enabled this trigger to block users from performing these acts, then I suggest you create a group, add whoever needs to admin this stream for you and update the script to allow this group to perform those operations.


Morph a view into another

Question: I have a view in my app that is replaced by another view by swapping their visibilities (gone <-> visible).
Those views are similar by content but no one is contained in the other.
Curenntly one view disappears and the other appears. I have another option of animating the visible out and animating the other one in. But I was wondering, is there a way to morph the first view to the other? It seems possible that it can be done by animating the size and regarding the content - split the content animation to three parts: blurring, replace content, un-blurring. Is there something similar?
Also any other solutions to replacing the views would be much appreciated.
Answer: Take a look at ViewSwitcher
https://developer.android.com/reference/android/widget/ViewSwitcher
You can customize the in/out animation, it holds 2 views, where only 1 can ever be visible at a time

Morph a view into another


How to choose between airsoft mechanisms?

Question: I've been playing airsoft for a little while now, and so, I am looking to purchase my own gear. I understand there are 3 main firing mechanisms; gas, electric and mechanical(spring). What I want to know is, what are the differences between the 3? I.e pros and cons.
Also, as I understand, the size of the gun affects the suitability of each specific mechanism, so I should mention, I am looking to get a pistol as I have been told smaller is better for close quaters(I play indoors only).
Comment: There are good explanations and pros/cons [here](https://www.redwolfairsoft.com/blog/how-do-airsoft-guns-work) (I'm not related to them, just to say...)
Answer: Mechanical

Pro: The spring is a very powerful mechanism for shooting BBs.
Con: The spring has to be manually loaded each time. Ie, not a semi-automatic weapon.

Gas

Pro: Fires faster and more accurately as a semi-automatic weapon.
Con: Gas can cause malfunctions in cold conditions.

Electric

Pro: A lighter footprint while being more consistent in firing than gas.
Con: Performance drops in wet/damp conditions.

Recurring Costs
Another rule-of-thumb is the recurring cost after buying the weapon.
Mechanical guns have the least amount of recurring cost as it does not require gas/electric to power while going through BBs at a much slower rate.
Gas guns require CO2 cartridges while many electric guns use rechargeable batteries. CO2 cartridges are generally one-time use and disposable while rechargeable batteries can be reused. A second rechargeable battery is recommended for less downtime when the first battery needs recharged or dies.
Also, the gas/electric in both situations to power the weapon are a recurring cost to consider.


Covariance of product of two functions of two binomial distributions

Question: Allow a multinomial distribution as per [1] with event probabilities  $p_{1},\ldots ,p_{k}$ and $\Sigma_{i=1}^{k}{ p_{i}}=1 $ and support $X_i \in \{0,\dots,n\}$ such that $   \Sigma X_{i}=n $.
Clearly, $\textstyle {\mathrm{Cov}}(X_i,X_j) = - n \, p_i \, p_j$ when$~~(i\neq j)$
Given real-valued constants $a$ and $b$ where $ 0 \leq a, b \leq 1$, what is $\textstyle {\mathrm{Cov}}(a^{X_i}, b^{X_j})$
$\textstyle {\mathrm{Cov}}(a^{X_i}, b^{X_j}) = ?$
[1] https://en.wikipedia.org/wiki/Multinomial_distribution
Answer: Each $X_i$ has a marginal distribution of $\text{Binomial}(n, p_i)$. Therefore,
$$ \begin{align} E[a^{X_i}]
&= \sum_{x=0}^n a^x \binom {n} {x} p_i^{x} (1 - p_i)^{n-x} \\
&= \sum_{x=0}^n \binom {n} {x} (ap_i)^{x} (1 - p_i)^{n-x} \\
&= (1 - p_i + ap_i)^n\end{align}$$
and similarly $E[b^{X_j}] = (1 - p_j + bp_j)^n$
The cross moments actually is similar too:
$$ \begin{align} E[a^{X_i}b^{X_j}]
&= \sum_{\substack x_i, x_j = 0 \\ x_i + x_j \leq n}^n
a^{x_i}b^{x_j}\frac {n!} {x_i!x_j!(n-x_i-x_j)!}p_i^{x_i}p_j^{x_j}
(1 - p_i - p_j)^{n - x_i - x_j} \\
&= \sum_{\substack x_i, x_j = 0 \\ x_i + x_j \leq n}^n
\frac {n!} {x_i!x_j!(n-x_i-x_j)!}(ap_i)^{x_i}(bp_j)^{x_j}
(1 - p_i - p_j)^{n - x_i - x_j} \\
& = (1 - p_i - p_j + ap_i + bp_j)^n
\end{align}$$
where we just applied the multinomial theorem. (binomial theorem being the special case). We assune $i \neq j$ here; If $i = j$ then just use the result of the first part and have $E[(ab)^{X_i}] = (1 - p_i + abp_i)^n$.
Finally, with all things ready, you just need to use $Cov[X, Y] = E[XY] - E[X]E[Y]$ to arrive the desired result.


Connections in non-Riemannian geometry

Question: In case of Riemannian geometry the connection $\Gamma^i_{jk}$ as is derived from the derivatives of the metric tensor $g_{ij}$ is ought to be symmetric wrt to its lower two indices. But in the case of Non-Riemannian Geometry that need not be the case, so the question is how do you actually construct such connections? Do you again use the metric tensor?
Comment: You don't need a metric to construct a connection. See [this](http://math.stackexchange.com/q/807256/2002) related question for further insights.
Answer: Here's one way to construct a connection on the tangent bundle (a similar construction works on more general vector bundles). Let $\{\rho_\alpha \}$ be a partition of unity subordinate to a locally finite coordinate cover $\{U_\alpha \}$. On each $U_\alpha$, choose coordinates $x_1^\alpha, \dots, x_n^\alpha$, giving a frame $X_1^\alpha = \frac{\partial}{\partial x_1^\alpha}, \dots , X_n^\alpha = \frac{\partial}{\partial x_n^\alpha}$ for the tangent bundle. Then choose a connection $\nabla^\alpha$ on each $U_\alpha$; any valid connection will do! To specify $\nabla^\alpha$, it suffices to specify the Christoffel symbols. One easy choice would be to make all the Christoffel symbols zero (meaning $\nabla^\alpha_{X_i^\alpha} X_j^\alpha = 0$ for all $i$, $j$).
We now have a connection on each $U_\alpha$, but we don't have a well-defined connection on the whole manifold because in general, $\nabla^\alpha$ and $\nabla^\beta$ will not agree on $U_\alpha \cap U_\beta$. But one way to construct a global connection is to use the partition of unity: define $\nabla$ by
$$ \nabla := \sum_\alpha \rho_\alpha \nabla^\alpha.$$
Then $\nabla$ is a well-defined global connection. This shows that connections exist!
Of course, depending on the context, this construction may not be too useful since we chose the $\nabla^\alpha$'s arbitrarily. For example, on a Riemannian manifold, one usually wants to work with the unique Levi-Civita connection. On more general vector bundles, there is not a canonical connection analogous to the Levi-Civita connection, but one often wants to work with metric-compatible connections (the torsion-free condition does not make sense in general).
Comment: You could have used partitions of unity to construct a Riemannian metric, and thereby reduce the problem to one the OP knows how to solve :)
Comment: @MarianoSuárez-Alvarez: That wouldn't really answer the OP's question, which as far as I can tell is specifically about connections with torsion.
Answer: A connection is an abstract non-unique $\mathbb{R}$-linear map on a smooth manifold $M$ with tangent bundle $TM$ and smooth vector fields $\Gamma(TM)$ given by
$$\nabla:\begin{cases}\Gamma(TM)\times \Gamma(TM)\to \Gamma(TM)\\
(X,Y)\mapsto \nabla_XY\end{cases}$$
satisfying the following properties

$\nabla_{fX}Y=f\nabla_XY$ for all $f\in C^\infty(M)$
$\nabla_X(fY)=X(f)Y+f\nabla_XY$
$\nabla_XY-\nabla_YX=[X,Y]$

It is a fact that the zero map doesn't satify above properties, but that if one has two connections $\nabla^1,\nabla^2$ one can create another by $g\nabla^1+(1-g)\nabla^2$. When looking at Riemannian manifolds $(M,g)$ we get a unique connection called Levi-Civita Connection which in addition satisfies what one calles metric compatibility
$$Xg(Y,Z)=g(\nabla_XY,Z)+g(Y,\nabla_XZ)$$
The proof mainly consists in looking at all cyclic permutations of above equations and than using a smart way in combining them to get an explicit formula which shows existance and uniqueness and satisfies the above properties. This formula is
$$2g(\nabla_XY,Z)=Xg(Y,Z)+Yg(Z,X)-Zg(X,Y)+g([X,Y],Z)-g([X,Z],Y)-g([Y,Z],X)$$
What you denoted as connection is in fact not a connection but the so called Christoffel Symbols obtained from the Levi-Civita connection via $$\nabla_{\partial_j}\partial_k=\sum\limits_{j,k}\Gamma^i_{jk}\partial_i$$
where $\partial_i,\partial_j,\partial_k$ are defined by taking a chart $(U,,\varphi)$ at a point $p\in M$ and setting $$\partial_i(p)(f)=\frac{\partial (f\circ\varphi^{-1})}{\partial x_i}(\varphi(p))$$ This is used to express a vector field in local coordinates $X(p)=\sum\limits_iX_i(p)\partial_i(p)$ and gives an expression of the Levi-Civita connection in local coordinates
$$\nabla_XY=\sum\limits_{i=1}^m\left(\sum_jX_j\partial_jY_i+\sum\limits_{j,k}\Gamma_{jk}^iX_jY_k\right)\partial_i$$
Like this we realize, that the Christoffel Symbol can be interpret as a measure of how strong the derivative of a vector field along another vector field on a Riemannian manifold deviates from the standart partial derivative on $\mathbb{R}^n$.

Connections in non-Riemannian geometry


Displaying users who click the button

Question: I have 2 user roles in my Drupal 7 site 'A' and 'B' respectively:

users of role 'A' can create and publish content.
users of role 'A' can see content they created on their profile page. (For this purpose I created a block to display content and put it on user's page.)
users of role 'B' can not create content but they can view all published content.

Content in my case is an invitation to some event (ie "Who wants to play football on Friday?")
Each content has 'Participate' button which users of role 'B' can submit.

How can I display in 'A' users pages the names of 'B' users who want to participate in their event?
How can an 'A' user confirm participation of some 'B' users and dismiss the rest?
Answer: This is quite a complex task your planning – and it's hard to answer in just a few lines of text. I can basically just recommend you have a closer look at the mighty Rules module in combination with the Flag and the Entity reference module.
Here's just a vague suggestion / outline of how this could probably be done by combining the above modules:

Put a flag 'participate' on content type event users of role 'B' can use
Define a new content type 'participation' with checkbox/flag 'confirmed / dismissed' and reference the event and the user to it, editable by 'A' users
Make a rule that generates a new node of content type 'participation' and alerts users of role 'A' of a new request
Extend your profile pages' view with the referenced items of content type 'participation'

There is probably different ways to do this – most likely also easier ways than the one described above. And then there is also a more specific module 'Rules link event' that might fit your demands.

Displaying users who click the button


Ship Logs from application server to ELK server with beats

Question: I am building log analyzer for production environment. My scenario is, i need to setupelasticsearch,Logstash and kibana on one centos7 server which is going to use ELK server another one is apache server(remote server).
I have configured following like
(i).ELK server - elasticsearch,kibana ,logstash with nginx proxy
(ii).Application server(apache server)-  installed beats on apache server
(i).ELK server configuration
Elasticsearch Configuration
vi /etc/elasticsearch/elasticsearch.yml
network.host: localhost
http.port: 9200
Kibana Dashboard Configuration
vi /etc/kibana/kibana.yml
server.port: 5601
server.host: "localhost"
elasticsearch.hosts: ["http://localhost:9200"]

Nginx Configuration:
server {
listen 80;
server_name 172.xx.xx.xx;
location / {
    proxy_pass http://localhost:5601;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
  }
}

Logstash Configuration
cat /etc/logstash/conf.d/02-beats-input.conf
input {
  beats {
  port => 5044
 }
}

I have configured filter section too..
cat /etc/logstash/conf.d/30-elasticsearch-output.conf
output {
 elasticsearch {
  hosts => ["localhost:9200"]
  sniffing => true
  manage_template => false
  index => "%{[@metadata][beat]}-%{[@metadata][version]}-%{+YYYY.MM.dd}"
 }
}

ii) Application server Beats configuration
I have installed beats in application server and ships logs with logstash.
Filebeat configuration:
cat /etc/filebeat/filebeat.yml
output.logstash:
   #the logstash hosts
hosts: ["172.xx.xx.xx:5044"]

here, i am not sure how to load filebeat index template, index and Dashboard in kibana. When i try to run
"filebeat setup" command from apache server, i got following error.
[root@webserver ~]# filebeat setup
Exiting: Index management requested but the Elasticsearch output is not configured/enabled.

I know if i configure filebeat with elasticsearch output, i can load indexes directly to kibana. But i don't want apache server directly contact with elasticsearch.
Can someone suggest how can i load "index, index template and dashboards" directly from apache server to kibana while configured beats output to logstash.
I have searched lot of sites, but haven't get any answers. Is there any other alternative method(like import method) to load apache server filebeat indexe in kibana  and elk server.
I am eager to wait someone give solution for this.
Thanks
Kumar
Answer: First, take a look at how events get from the source server into ElasticSearch.
[App-Server --> Log-file --> Beats] --> [Logstash --> ElasticSearch].

The Apache server, the app server, has no way to talk to ElasticSearch in this configuration. Therefore, the beats commands to set up the index, template, and dashboards won't work from there. However, your architecture is not set up to assume Beats! It assumes Logstash is the one sending events into ElasticSearch. Kibana can handle that just fine.
If you go into Kibana's management and then index patterns, it will bring up a list of your current indices. With your beats to logstash configuration, you should have some. Set up a wildcard for the indices you want to search.
Comment: Thanks for your reply..I have done configurations as per your guide and It's working fine.But i have faced another issues.

when i configure filebeat and metricbeat in apache server, it bring up new indices on ELK server. In same case, auditbeat doesn't bring any indices to ELK server. Is there any other method to load auditbeat indices from client machine with logstash configuration.
Comment: Also I would like to setup custom index pattern on kibana. Like i have done filebeat configuration through logstash in Apacheserver(Development),Apacheserver(QA testing) and Apacheserver(Production server). But those server logs are getting same filebeat index pattern.

Any way to separate both logs from three servers ?
Answer: Try running: filebeat -e
instead of: filebeat setup
Comment: This is an old question that already has an accepted answer. Has something changed in the system that your answer may be more valid today than the answer that was already accepted? If so, please give some more information to show how and why.


Confused - which shell do I really have?

Question: The commands which I ran and their outputs are given below -
$ echo $SHELL
/bin/bash

$ whence bash
sh: whence: command not found

$ which bash
/usr/bin/bash

I am not sure which shell I really have. First one says bash and the second says sh.
So, which shell is it ? bash or sh ?
Comment: May I know why I got a -1 ? Please tell me how I can fix the question. This question did not get a -1 for so long, so it seems that its ok.
Comment: Please move this question to superuser (and also give me a +1 if you can :) )
Answer: This should clarify what you are using:
echo $BASH_VERSION

Comment: yes, that gives me the version. lets try that with echo $CSH_VERSION
...no result
Comment: Meaning you are running BASH.
Comment: can you give me a +1 if thats ok ?
Comment: That's not the way it works. You'd rather ask a moderator to move your question to Superuser where it belongs. It is off topic as you are not  asking in the context of a shell script.
Answer: Check to make sure that /usr/bin isn't a link to /bin or vice-versa and that /usr/bin/bash isn't a link to /bin/bash or vice versa.  It is possible that you are running one binary, /bin/bash, but that your path lists /usr/bin before /bin, in which case, which bash would list /usr/bin/bash - but that only means that /usr/bin/bash is the one you will run if you type bash on the command line.  It doesn't mean it is the one you're running.


Solve the following recurrence relation: $a_{n}=10a_{n-2}$

Question: I'm trying to solve the following recurrence equation $a_{n}=10a_{n-2}$.
Initial conditions: $a_0=1$, $a_1=10$
I have tried to use characteristic polynomial and generating functions but both methods lead to contradiction.
I think I should observe $\mathbb{N}_{even}$ and $\mathbb{N}_{odd}$ as different cases but I don't know how to do it formally.
Any help would be appreciated.
Comment: Can you explain how the characteristic polynomial leads to a contradiction?
Comment: The solutions are $10^{0.5}$ and $-10^{0.5}$ and then I get a contradiction while calculating the coefficients.
Comment: Well, since you don't give any initial conditions...how do you even try to compute the coefficients?
Comment: You need two initial values, $a_0$ and $a_1$ say.
Comment: @lulu You are right, fixed that.
Comment: I mean, you could just write $a_{2n}=10^na_0$, and $a_{2n+1}=10^na_1$ if you want...but there is nothing wrong with the characteristic polynomial method.
Comment: @GADI The odd and even series are independent of each other.
Comment: I see the edit, so writing $a_n=A\left( \sqrt {10} \right)^n+B \left( -\sqrt {10} \right)^n$ we get $1=a_0=A+B, 10=a_1=(A-B)(\sqrt {10})$.
Comment: @lulu Yes. That's a contradiction, doesn't it? you get $0=10^{0.5}$
Comment: Where is there a contradiction?
Comment: You get $0=\sqrt {10}$
Comment: Really?  I get $A=\frac {\sqrt {10}+10}{2\sqrt {10}}, B=\frac {\sqrt {10}-10}{2\sqrt {10}}$.  I don't see any problem at all.
Comment: I mean, the linear forms $A+B$ and $(A-B)(\sqrt {10})$ are linearly independent, so how could there possibly be a contradiction?
Comment: Yes. I made an algebraic mistake. Thank you for that
Answer: We need initial values for $ a_0 $ and for $a_1$ to start with.
Notice that, $$ a_2 = 10a_0$$,$$a_4 = 10a_2 =10^2a_0$$  $$ a_6=10a_4 =10^3 a_0$$
With the given initial values we get  $$a_{2k}=10^ka_0 = 10^k $$
Similarly you get $$a_{2k+1}=10^{k+1}  $$
Comment: With the specific initial conditions, this can be condensed in a single formula: $$a_n=10^{\bigl\lceil \tfrac n2\bigr\rceil}.$$
Comment: @Bernard very true and smart.


Can someone please explain the below and if it means that if x=m/2^n and if m is odd then x can be represented in binary in two ways?

Question: Reference image containing the statement
Can someone please explain the below text and what it means in simple words? From what I understood it means that if x=m/2^n and if m is odd then x can be represented in binary in two ways? But how is that possible. I tried with 1/2 but how can 0.5 be represented as 0.1 and 0.0111?
Answer: Note that the $1$s go on forever. They don't stop after the first three. This is the binary version of the infamous fact that
$$
0.999\cdots = 1
$$
in decimal. (This equation has its own Wikipedia page.)
I cannot see what equation $(2)$ is in your book, but here's a definition of binary representations which is likely equivalent:

A binary number $(.a_1a_2a_3\cdots)_2$ represents the real number $x$ if
$$
\sum_{n = 1}^\infty \frac{a_n}{2^n} = x.
$$

For your example, $x = \frac12$, the $0.1$ representation is short for $0.1000\cdots$. The infinite sum is then
$$
\sum_{n = 1}^\infty \frac{a_n}{2^n} = \frac12 + 0 + 0 + 0 +\cdots = \frac12.
$$
But for the other representation, $0.0111\cdots$, the sum is
$$
\sum_{n = 1}^\infty \frac{a_n}{2^n} = 0 + \frac14 + \frac18 + \frac1{16} + \cdots.
$$
This is a geometric series which evaluates to = $1/2$, as desired.
Comment: It's every number which "terminates" (ends with infinitely many $0$s) that has two representations. To get the other representation, replace the last $1$ with a $0$, and replace all the following $0$s with $1$s. For example, $5/8 = (0.101)_2$ = $(0.101000\cdots)_2$. The other representation is $(0.100111\cdots)_2$. This is actually what your book describes in a different way.
Comment: Would this hold for other values like 3/8 or 5/4? I mean the cases where m (numerator) is odd and denominator is 2 raised to the power n? Then also, would there be two ways of representing the decimal fraction in binary as per the given condition?
Comment: Yes, this holds for every number of the form $m/2^n$. This is what the book is claiming. (And for decimal, you'll get two representations for numbers of the form $m/10^n$.)
Comment: I am mostly clear about it but I still can't figure out how would someone find out the alternative representation of binary for a given m/2^n. Let's say 3/4 or 5/8. I could find the normal binary representations for these but how do I get the alternative representation to prove that this holds? Any help? Apologies if I'm asking something irrelevant.
Answer: by definition, $x = (.a_1a_2\dots a_n\dots)_2$ iff
$$x=\sum_{i=1}^{\infty}a_i2^{-i}$$
if $x = \frac{m}{2^n}$, for $m$ odd, i.e., $m=2k+1$, then $x=\frac{2k+1}{2^n}=\frac{k}{2^{n-1}}+\frac{1}{2^n}=(.a_1a_2\dots a_{n-1}1000\dots)_2$. But, note that $x$ is also equal to $(.a_1a_2\dots a_{n-1}0111\dots)$ by definition, since
\begin{align*}
\sum_{i=1}^{\infty}a_i2^{-i} & = a_12^{-1}+\dots+a_{n-1}2^{n-1}+\sum_{i=n+1}^\infty2^{-i}\\
& = \frac{k}{2^{n-1}}+\frac{2^{-n-1}}{1-\frac12}\\
& = \frac{k}{2^{n-1}}+\frac{1}{2^n}\\
& = x
\end{align*}
so the real reason why every real in binary has two decimal expansions is precisely because $\frac12 = 0.1 = 0.0111\dots$, both series converge to the same number. And in fact this occurs on any numerical basis $b$, since
$$(0.1)_b=b^{-1}=\sum_{i=2}^\infty (b-1)b^{-i}=\frac{(b-1)b^{-2}}{1-\frac1b}=(0.0(b-1)(b-1)\dots)_b$$
this is why, for example, $1 = 0.999\dots$ in decimal base.


How to replace all the whitepaces with '-' in redshift?

Question: The data I have, as below
Client ID:16402600010001                          Merchant ID:372048655883                          Terminal ID:7582626                               07/08/16                                  20:51:12                       SALE                                         Invoice:106393                  Account:DEBIT ************8747                    Cardholder:ZAMOA/ KAANDRA                      Card Entry Mode:Swiped                            Result:CAPTURED                                   Authorization Code:971125                         CTroutd:11118                                     Approved Amount:2.64                              Subtotal:                                     2.64Total:                                        2.64
There is 4-5 tabs and whites spaces between each string. Now, I want to replace all the white spaces with - (dash). What will be regular expression for that?
Comment: Are these separate columns or is this data all in one column? Some formatting and a table structure might help, as it's not very clear what your "data" represents.
Comment: This entire data is in one single row. Yes, there is whites spaces or tabs or new lines in between of like ClientID, Merchant ID, TerminalID, date and so on
Comment: Can you just use a simple REPLACE, e.g. SELECT REPLACE(, ' ', '-') FROM ; ?
Answer: Is this what you are looking for?
SELECT trim(regexp_replace(column_name, '\\s+', ' ')) as mystring FROM Table_name;

If I've made a bad assumption please comment and I'll refocus my answer.


Acentuação no diretório

Question: Estou com problema de localização de diretório quando envolve um arquivo ou pasta com acentuação. Segue o trecho abaixo onde tento capturar o tamanho do arquivo:
$filepath = "$novocaminho".utf8_encode($arquivo);
$tamanho = filesize("$filepath");

Neste caso ele está retornando o seguinte erro:  Warning: filesize(): stat failed for
Em outro caso, onde verifico se é um diretório, quando o diretório está sem acentuação, o if retorna true caso seja um diretório com acentuação ele retorna false.
if(is_dir(utf8_encode($novocaminho_implode)) == TRUE){
Os diretórios passados são do tipo string.
Já tentei utilizar o utf8_encode().
Comment: utf8_encode() talvez não seja a melhor opção
Answer: Uma sugestão é converter tudo que entra no banco de dados (até mesmo renomear o nome do arquivo) em entidades html, como segue o código php:
$email = addslashes(htmlentities($_POST['email'], ENT_QUOTES,'UTF-8'));

Dessa forma, todos os caracteres especiais são convertidos, e na hora de exibi-los, o próprio navegador o interpretará.

Será convertido segundo a tabela disponível em http://erikasarti.net/html/acentuacao-caracteres-especiais/
á = á (&aacute)
ã = ã (&atilde)
e assim por diante
Comment: Eu tentei e não funcionou. Quando faço a verificação se é um diretório, ele retorna como false mesmo a string já estar em utf-8.
Comment: Alterou o nome do arquivo para os caracteres correspondentes?
Comment: Sim, ainda sim não foi.
Comment: @JonathandeToni E o $novocaminho? Como ele está?
Comment: É uma string também, no caso eu armazeno navegação utilizando array, assim consigo armazenar,construir e destruir o caminho que o usuário está percorrendo. O $novocaminho é atribuído uma string retornada da função implode().
Answer: Verifiquei que o problema pode estar em outro ponto do código:
if(isset($novocaminho)){
    if(is_dir($novocaminho) == TRUE){

         $diretorio = dir(utf8_encode($novocaminho_implode));

         while (($arquivo = $diretorio->read()) !== false){

Quando a minha string, já alterada com o UTF-8, é verificada por if(is_dir()) ela retorna false, mas apenas retorna false quando a string vem com assentos, caso contrário, ela continua e percorre todo o diretório normalmente.
Seria o caso de alterar todo o meu diretório para ficar sem assentos?, mas tenho que mostrar para o usuário os assentos. Como eu faria se estou mostrando "imprimindo" na tela exatamente o nome dos arquivos e pastas que estão no meu diretório.
Existe outras formas de mostrar o diretório?
Eu passo a pasta por um string $pastaraiz = "public/data/downloads";. Pois se eu utilizar o $_SERVER['DOCUMENT_ROOT']; irá passar a minha pasta atual.

Acentuação no diretório


Points on an elliptic curve over $\mathbb F_p$

Question: Let $E$ be an elliptic curve over $\mathbb F_p$ (the finite field of $p$ elements) defined by $y^2=x(x-n)(x-m)$ where $p\nmid nm(n-m)$. Let $N$ be the number of $\mathbb F_p$-valued points of $E$.  Let $a=p+1-N$.
Then $a=A-B$ where $A$ is the number of elements $x\not=0,n,m$ in $\mathbb F_p$ such that $x(x-n)(x-m)$ is a non-square in $\mathbb F_p$ and $B$ is the number of elements $x\not=0,n,m$ in $\mathbb F_p$ such that $x(x-n)(x-m)$ is a square in $\mathbb F_p$.
I can't see why this is true but I feel like it should be obvious.  Can anybody offer any insight into how to show this?  Thank you!
Answer: Let's count the points on $E$. There's that point at infinity. Then we have exactly $p$ choices for $x$. If to each $x$ there were exactly one $y$ such that $(x,y)\in E$, then the number of ($\Bbb{F}_p$-rational) points on $E$ would be $p+1$.
But let's take the form of the equation into account:
$$y^2=x(x-m)(x-n).$$
We see that $y$ only appears squared. Meaning that if $(x,y)\in E$ then so is $(x,-y)$ - two points on $E$ for those choices $x$. If furthermore $y\neq0$ these two points are distinct. But also it is easy to imagine that to some $x$ the r.h.s. has no square root. To such $x$ there is no matching $y$ - no points on $E$ for those choices $x$.
The variable $A$ counts those choices of $x$, where we get one point less than "expected". The variable $B$ counts those choices, where we get one more. Therefore
$$
|E|=p+1-A+B.
$$
Comment: Making this CW because I have given essentially the same answer before. Couldn't locate it right away.
Comment: Thank you, very clear.  I tried to think it through exactly like you explained it but for some reason I got hung up - looks like it was straightforward.


Find the indicated term of the geometric sequence algebraically.

Question: a1=18, r=4/3, 8th term
1.Find the indicated term of the geometric sequence algebraically.
Comment: Welcome to MSE! What do you know about geometric series that might be useful in solving this problem?
Comment: Let's start with something a little simpler. How would you find the second term?
Comment: I know first term is 18, and difference is 4/3. We need to find 8th term so we?
Comment: multiple 18 with 4/3
Comment: second term is 24
Comment: Exactly! If you had to multiply by $4/3$ once to find the second term and twice to find the third term, how many times would you need to multiply by $4/3$ to find the eighth term?
Comment: 8? So do I multiply 24 times 4/3 for third term etc?
Comment: Is the answer is 60?
Comment: If you have a G.P. then $a_1=18,a_2=18\cdot\dfrac 43, a_3=18\cdot(\dfrac 43)^2,\cdots,a_8=18\cdot(\dfrac 43)^7$
Comment: You were close with your guess of $8$. Notice that
$$a_\color{red}1=18\times\left(\frac43\right)^\color{red}0=18\times1=18$$
$$a_\color{red}2=18\times\left(\frac43\right)^\color{red}1=18\times\frac43=24$$
I was about to ask if you could continue that pattern on your own to see why you would need to multiply by $4/3$ only $7$ times to find the eighth term, but it looks like someone else beat me to it.
Comment: 294912/2187?, so like 134.99?
Comment: Yep, that's it. I got $134.85$, but it's pretty close.
Answer: Just to summarize what transpired in the comments:
Notice that
$$a_\color{red}1=18\times\left(\frac43\right)^\color{red}0=18\times1=18$$
$$a_\color{red}2=18\times\left(\frac43\right)^\color{red}1=18\times\frac43=24$$
$$a_\color{red}3=18\times\left(\frac43\right)^\color{red}2=18\times\frac{16}9=32$$
$$\dots$$
Continuing the pattern a few more times, you'll find that
$$a_\color{red}8=18\times\left(\frac43\right)^\color{red}7=18\times\frac{16384}{2187}\approx134.85$$
Problems like this become much simpler if you can find a pattern!


How to hide a views result item based on role?

Question: I have a View based on taxonomy vocabularies and terms. The view only contains 2 fields, taxonomy vocabulary and taxonomy term and the output is HTML list.
How can I hide one of the terms in one of the vocabs in the view result based on the role of the logged in user?
UPDATE:
With the help from No Sssweat below, this is how the final snippet looks like:
function mytheme_preprocess_views_view_fields($vars){
  global $user;
  if ($vars['view']->name == "view name" && strip_tags($vars['fields']{rendered_entity}->raw) == tid && in_array('user role', array_values($user->roles))){
    $vars['fields']{rendered_entity}->content = NULL;
  }
}

... in case anyone else need something like this snippet.
Answer: Assuming you added Taxonomy term: Name as the field, which you want to hide.
Add this to your theme's template.php file.
function mytheme_preprocess_views_view_fields($vars){

  $global user;

  if ($vars['view']->name == "name_of_view" && strip_tags($vars['fields']['name']->content) == "Term Name" && in_array('role name', array_values($user->roles))){
    $vars['fields']['name']->content = NULL;
  }

}

change mytheme to your actual  theme name.
change name_of_view to your view name.
change Term Name to the name of the term.
change Role Name to the specific role name.
Comment: Thanks a lot! Just one thing... I am using Taxonomy term: Rendered taxonomy term... I am trying to figure out how to change your snippet but Devel refuse to show me the variables when I use dsm()... Could you enlighten me?
Comment: Never mind my comment, I just figured it out. Se my updated question. Thanks again!
Answer: You can achieve this using Views PHP module as well.

This module allows the admin account (user 1) to add fields, filters
  and sorts to views which use PHP code. It also supports additional
  accounts when the core PHP Filter module is enabled.

While this module allows you to directly use PHP inside views which may be useful for quick and easy solutions, it is highly advisable to use regular handlers and plugins when available (or even to create one yourself). Take note that filtering and sorting a view using PHP always has a considerable perfomance impact.
Steps:
Add Global PHP filter in view.
Load global user.
Get User role.
Get the term id
After getting both values, Put in condition.
If condition satisfy return False else return TRUE.


C# combobox like dropdown list in web application

Question: I have comboBox component and i am adding items like comboBox1.Items.Add("Item1"). But i alo need to know some other info about this Item. So if i click "Item1" i need to get "102454".
Can i somehow save 102454 to "Item1" on combobox.
At web aplication there is dropdown list which look like
<select>
  <option value="102454">Item1</option>
</select>

and when i click "Item1" i get 102454.
Can i do this in windows desktop applicatin with combobox?
Answer: Edit better solution:
Use a KeyValuePair and ValueMember \ DisplayValue:
comboBox1.ValueMember = "Key";
comboBox1.DisplayMember = "Value";

comboBox1.Items.Add(new KeyValuePair<int, string>(102454, "Item1"));

As Kristian points out this can be extended to be even more flexible - you can put whatever object you like into the list of items, and set the value and display members on the combobox to be whatever property path you want.

To get the key back later you can do this:
var item = combobox1.SelectedItem;

int key = ((KeyValuePair<int, string>)item).Key;

Comment: This is the most flexible solution. As the "KeyValuePair" can be changed with any object. If you use e.g. "Person" as the object, you can set:
comboBox1.ValueMember = "SSN";
comboBox1.DisplayMember = "Name";
Comment: thx will try. but right code is KeyValuePair(102454, "Item1")
Comment: hmm how can i get now Key back. I can not read 102454 or can i?
Comment: @senzacionale Updated my answer to show how to get the `Key` back out
Answer: You may take a look at the SelectedItem property.
Answer: A have created a similar class like Mark Pim suggested; however, mine uses generics.
I certainly would not choose to make the Value property a string type.
    public class ListItem<TKey> : IComparable<ListItem<TKey>>
    {
        ///
        /// Gets or sets the data that is associated with this ListItem instance.
        ///
        public TKey Key
        {
            get;
            set;
        }

        ///
        /// Gets or sets the description that must be shown for this ListItem.
        ///
        public string Description
        {
            get;
            set;
        }

        ///
        /// Initializes a new instance of the ListItem class
        ///
        /// <param name="key"></param>
        /// <param name="description"></param>
        public ListItem( TKey key, string description )
        {
            this.Key = key;
            this.Description = description;
        }

        public int CompareTo( ListItem<TKey> other )
        {
            return Comparer<String>.Default.Compare (Description, other.Description);
        }

        public override string ToString()
        {
            return this.Description;
        }
    }

It is also easy to create a non-generic variant of it:
    public class ListItem : ListItem<object>
    {
        ///
        /// Initializes a new instance of the <see cref="ListItem"/> class.
        ///
        /// <param name="key"></param>
        /// <param name="description"></param>
        public ListItem( object key, string description )
            : base (key, description)
        {
        }
    }


How can I calculate a hover state change based on the original state values?

Question: This may not be possible using just CSS alone buuuut let's give her a whirl.
For example: I have an image with certain margins. let's say something like this:
img {
margin-left: 1em;
}

What I want to do, (I'll write it in pseudo code) is something like this:
img:hover {
margin-left: [take original non-hover state margin, then -1 from that to make 0]
}

Hopefully I'm making sense here if it's even possible - I've really tried to simplify that example down.
Comment: **take** *original non-hover state margin*, is not possible,wish for *css 4* to provide those features.
Answer: img {
margin-left: 1em;
}
img:hover {
margin-right: 1em;// for minus 1
}

you can use margin-right to subract

P.S remember what you learnt in childhood about net force


Interact with .OBJ?

Question: Is it possible to interact with .OBJ models? I'm trying to animate the rotation of my imported .obj model, and incorporate the cursor for "clicking" on the model triggering an animation. I would appreciate some information on how to do this.
I would also like to know if it is possible to use the mouse on the destop to rotate the .OBJ model instead of moving the camera.
Here is my code so far:

Answer: To animate a property of an object, you can use the a-animation elements:

For using the mouse to rotate, aframe-orbit-controls is a wrapper around THREE.OrbitControls. That's definitely the place to start. It may be a little tricky to switch between animated rotation and mouse rotation on the same object.

Interact with .OBJ?


jade.Boot class not found ubuntu10.10

Question: I know this is an old question, but I have spend any hours on this and now in desperation turn to ask for help.
The problem: I cant run > java jade.Boot -gui
Terminal:
xxxx:~/Documents/Active/Studies/MscEngProject/Work/Java$ java -cp home/xxxx/bucket/jade/lib/jade: jade.Boot -gui

Exception in thread "main" java.lang.NoClassDefFoundError: jade/Boot
Caused by: java.lang.ClassNotFoundException: jade.Boot
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: jade.Boot.  Program will exit.

I'm running: java version "1.6.0_26", Ubuntu10.10
I have being working with jade since last year, but only in Eclipse. Now I must run the program in the command line. I have tried moving jade.Boot around, changed my classpath in the command and also created a CLASSPATH env variable. I even tried to extract Boot.class and run that. Im not the best programmer but do understand somethings, but this problem is above my knowledge. Help will be really appreciated!
Answer: java jade.Boot -gui will work only if jade.Boot is in the classpath of jre. Add it to your classpath and be happy.
You can try to do this(if jade is distributed in jars): java -cp "jar1.jar;jar2.jar" jade.Boot -gui
Other way is to download sun jdk, extract it (for example, in /opt/jdk) and put jade libs in /opt/jdk/lib or smth like that

jade.Boot class not found ubuntu10.10


How would I allow access to a VPS based MySQL database only from AWS East based IPs?

Question: I have a MySQL database on my VPS that I only want to be accessible by my local IP (no problem in doing that) and an IroneWorker Ruby app, which may use any of these AWS East IPs.
So far, the only way I can think of doing this is by adding a rule, to the VPS firewall/iptables, that will only allow connections by all AWS East IPs on the MySQL port, and refuse all other connections.
Given the large number of IPs, is there a better way to do this.
NOTE: The VPS is not on AWS, so using their security rules is not an option.
Also, access will only be granted for a user created specifically for IronIO access.
UPDATE: As suggested by tadman, I've come to the conclusion that establishing a remote SSH connection is the safest route. I tracked down the Net::SSH and Net:SSH::Gateway gems that would make this possible, however I am still unsure how to do this using key authentication, so created a new question here.
Comment: Sounds like a job for a VPN, really. Opening up all of AWS East is not exactly secure.
Comment: Yep, not ideal or secure, but the guys at Iron.IO couldn't narrow down the IP that would be accessing it. Oh, and, of course, it would only be one user specifically created for IronIO access (maybe I should of added that in description...)
Comment: Leaving your MySQL port open to AWS is nearly as bad as leaving it open to everyone. Are you sure you can't use an SSH tunnel or some kind of simple VPN to connect to your remote database?
Comment: Barring that, you could try [port knocking](http://www.portknocking.org/) to manipulate your firewall rules automatically.
Comment: @tadman how would I make the IronWorker connect using an SSH tunnel or VPN? I understand using SSH or VPN to connect locally, but this is a running task (some times scheduled) that I want to grant access. Maybe I'm not using IronWorker for what it is designed to do, it seems (to me anyway) that ensuring secure access by a "worker" to a db would be a standard function of the API.
Comment: Looks like I can do the ssh method using the net-ssh-gateway or net-ssh gems. I'll try it when I find some examples to work from :)
Answer: If you're able to use AWS security groups:
http://dev.iron.io/worker/reference/environment/#security_groups_and_ip_ranges
If not (permissions to wide though):
https://forums.aws.amazon.com/ann.jspa?annID=1701 (aws-east region)
Sadly, there are no good solution for that. Amazon can assign almost any ip within the range
Comment: As noted the VPS is not on AWS, so AWS Security Groups are not an option.
Answer: Using SSH you can set up a tunnel from each machine requiring access to the database to the remote machine. For example:
ssh -L 3306:localhost:3306 -f remote_database.host

The -L option specifies the local port to listen on and the remote address and port to connect to. In this case, local 3306 is connected to the remote 3306 on the machine you're connecting with SSH to.
You'll probably want to ensure that you're using SSH public/private key authentication, and that you've got a way of keeping this tunnel up if something goes wrong with it.


FlatList render too many times

Question: I just got this issue when using FlatList in React native, I am using PureComponent, my data just has only 20 items but it renders like 30 times.
Here is my code:
export default class App extends React.PureComponent {
  state={
    data: [{key: '1'}, {key: '2'}, {key: '3'}, {key: '4'},
    {key: '5'}, {key: '6'}, {key: '7'}, {key: '8'},
    {key: '9'}, {key: '10'}, {key: '11'}, {key: '12'},
    {key: '13'}, {key: '14'}, {key: '15'}, {key: '16'},
    {key: '17'}, {key: '18'}, {key: '19'}, {key: '20'}]
  }
  render() {
    console.log(this.state.data);
    return (
      <View>
        <FlatList
          data={this.state.data}
          renderItem={({item}) => {
            console.log(item.key)
            return (
              <MyItem>{item.key}</MyItem>
            );
          }}
        />
      </View>
    );
  }
}

export default class MyItem extends React.PureComponent {
    render(){
      return(
        <View>
          <Text>{this.props.children}</Text>
        </View>
      );
    }
  }

and this was what I got when running
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Comment: This is still present in react native v0.55.4, I guess it is a bug. If you have large lists it can significantly cause stuttter.
Answer: Your code looks fine. There should not be any issues while running this code.
How are you know how many times your screen renders? Here since your state is static it should render only once, until and unless you are doing setState somewhere in your code.
Otherwise this piece of code is fine.
Comment: Hi Yash, i use console.log() in renderItem function to see how this function works, first it renders 10 items, then it render the first 10 items again.

FlatList render too many times


How do I set the ItemsSource of a DataGrid in XAML?

Question: I'm trying to set the ItemsSource property of a DataGrid named dgIssueSummary to be an ObservableCollection named IssueSummaryList.  Currently, everything is working when I set the ItemsSource property in my code-behind:
public partial class MainPage : UserControl
{
    private ObservableCollection<IssueSummary> IssueSummaryList = new ObservableCollection<IssueSummary>

    public MainPage()
    {
        InitializeComponent();
        dgIssueSummary.ItemsSource = IssueSummaryList
    }
}

However, I'd rather set the ItemsSource property in XAML, but I can't get it to work.  Here's the XAML code I have:
<sdk:DataGrid x:Name="dgIssueSummary" AutoGenerateColumns="False"
                ItemsSource="{Binding IssueSummaryList}" >
    <sdk:DataGrid.Columns>
        <sdk:DataGridTextColumn Binding="{Binding ProblemType}" Header="Problem Type"/>
        <sdk:DataGridTextColumn Binding="{Binding Count}" Header="Count"/>
    </sdk:DataGrid.Columns>
</sdk:DataGrid>

What do I need to do to set the ItemsSource property to be the IssueSummaryList in XAML rather than C#?
Answer: You need to make "IssueSummaryList" a property.  If you do this, you can bind to it directly.  You can't bind via Xaml to a private field.
You'll also need to set the DataContext to "this" (or use another method to get it to find the appropriate instance).
Comment: Isn't the DataContext thing only needed if you use the M-V-VM Pattern for binding ?

He seems to use just code behind files
Comment: @KroaX: No.  The binding works via a DataContext.  The MVVM pattern takes advantage of this, but Data Binding in WPF (and Silverlight) is always binding to a property on the DataContext being used by the UIElement.
Answer: Your IssueSummaryList is private. You need to make it a Property with get and set
public ObservableCollection<IssueSummary> IssueSummaryList
{
     get
     {
        // ...
     }
}

Answer: The XAML is correct, so the problem must be in the Binding.

Is the ObservableCollection exposed as a property?
How have you set the Binding? In the most simple case you use code like:
this.DataContext=this;

in the Window_Load eventhandler


Como faço para ordenar string no metodo Insertion sort?

Question: Estou com o seguinte método, porém na linha do WHILE ele da erro. O netbeans diz

"bad operand types for binary operator "&&", first type: boolean, second type: int".

public boolean insertionSort(String a []) {
        if (a == null) return false;
        int i,j;  String x;
        for ( i=0; i 0  && x.compareTo(a[j-1])) {
                a[j] = a[j-1];
                j--;
            }
            a[j] = x;
            visualizarEtapa(a,i);
        }
        return true;
}

Answer: O método .compareTo retorna um int (-1 para menor, 0 para igual e 1 para maior).
Deste modo, para vc comparar você pode usar:
while (j>0  && 0 == x.compareTo(a[j-1]))

ou
while (j>0  && x.equals(a[j-1]))

ou ainda utilizando o
commons lang3 da apache
while (j>0  && StringUtils.equals(x.compareTo(a[j-1]))

Existem diversas formas para se comparar strings, nos dois primeiros exemplos vc precisa tomar muito cuidado para evitar NullPointException quando x for nulo, fazendo sempre validações antes de trabalhar com o .compareTo ou com o .equals
Codigo editado
public boolean insertionSort(String a []) {
        if (a == null) return false;
        int i,j;  String x;
        for (j = 1; j = 0) {
                if (x.compareTo(a[i]) > 0) {
                    break;
                }
                a[i + 1] = a[i];
                i--;
            }
            a[i + 1] = x;
            System.out.println(Arrays.toString(a));
        }
        System.out.println(Arrays.toString(a));
        return true;
}

Comment: Funcionou! Porém o método ainda não estava ordenando os valores do vetor alfabeticamente.
Troquei o comparativo "==" para ">". Ficou assim:
while (j>0  && 0 > x.compareTo(a[j-1]))
Comment: peguei seu codigo fiz algumas alteracoes, veja se funciona


How to calculate the mean from bin endpoints and frequencies?

Question: Sometimes data extracted from reports do not have individual values, like 4, 23, 43, but grouped together like this:

income level
people in this group

10k to 20k
44

20k to 40k
240

40k to 80k
400

80k to 100k
130

What is the best way to describe this situation in statistics, and how to calculate the mean value?
At first, I thought about multiplying the mid value of the first row by the number of people, i.e.:
mean = ((15k x 44) + (30k x 240) + (60k x 400) + (90k * 130))/(44 + 240 + 400 + 130)
However, I feel since the distribution is skewed, the mid point doesn't represent the mean value in each group, and thus the calculation above is wrong.
I also thought about using weighted arithmetic mean, but I am not sure.
What is the statistic tool to deal with this sort of problem?
Comment: To a good first approximation, income distribution will be closer to symmetric on logarithmic scale than on the original scales. So an alternative would be to work with the geometric mean and similarly the geometric means of the interval end-points. You don't spell it out here but it's common that the uppermost income interval is reported as open-ended, which compounds the problem.
Comment: Your table is basically a histogram. You could plot it to further verify if the data is skewed.
Comment: See our posts on [Sheppard's corrections](https://stats.stackexchange.com/search?tab=votes&q=sheppard%20correction).  Although the duplicate is explicitly about estimating the SD, it also shows how to estimate the mean (and any other moment).  The question and its answers present at least three standard methods.
Answer: Because your data is binned into intervals, you cannot really calculate the original sample mean because you should not make up information that you don't have access to. However, you have a couple of options.
Option 1
Your first option, which is the one many people take, is to calculate the mean based on the midpoints. This approach is an estimation subject to binning error. This is what you've done in your original post.
Option 2
Your second option is my preferred option, which is calculate an interval that the mean sits within. This can be done with the use of interval arithmetic. It has the following rules for $x_1,x_2,y_1,y_2 \in \mathbb{R}$:
$$[x_1, x_2] + [y_1, y_2] = [x_1 + y_1, x_2 + y_2]$$
$$[x_1, x_2] - [y_1, y_2] = [x_1 - y_1, x_2 - y_2]$$
$$[x_1, x_2] \cdot [y_1, y_2] = [\min \{x_1 y_1, x_1y_2,x_2y_1, x_2y_2 \}, \max \{x_1 y_1, x_1y_2,x_2y_1, x_2y_2 \}]$$
$$\frac{[x_1, x_2]}{[y_1, y_2]} = [x_1, x_2] \cdot \frac{1}{[y_1, y_2]}$$
where
$$\frac{1}{[y_1, y_2]} = \begin{cases}
      \left[\frac{1}{y_2}, \frac{1}{y_1}\right] & 0 \not\in [y_1,y_2] \\
      \left(-\infty, \frac{1}{y_1}\right] & y_1 \neq 0 \land y_2 = 0 \\
      \left[\frac{1}{y_2},\infty\right) & y_1 = 0 \land y_2 \neq 0 \\
       \left(-\infty, \frac{1}{y_1}\right] \cup \left[\frac{1}{y_2},\infty\right) & 0 \in (y_1, y_2)
   \end{cases}$$
Note that for the above rules a constant $\alpha \in \mathbb{R}$ can be thought of as the interval $[\alpha, \alpha]$ for the purposes of combining intervals with scalars.
In your case, the following can be done quickly in the Python interpreter.
Python 3.6.9
>>> import numpy as np
>>> intervals =[[10,20], [20,40], [40, 80], [80,100]]
>>> weights = [44, 240, 400, 130]
>>> result = 0
>>> for i,j in zip(intervals, weights):
...     result += np.array(i) * j
...
>>> result / np.sum(weights)
array([38.86977887, 68.15724816])

Thus the mean income sits somewhere within \$$[38869.78, 68157.25]$.
Comment: For additional descriptions of interval arithmetic, [search our site](https://stats.stackexchange.com/search?tab=votes&q=%22interval%20arithmetic%22).
Comment: Also note that the arithmetic as defined above allows for polynomials, including Taylor series approximations of exponentials, logarithms, trigonometric, and hyperbolic functions among others.
Comment: I think it's more complicated than that.  You cannot just apply a polynomial function to all the left endpoints and then to all the right endpoints to determine the resultant interval, for instance; nor can you apply a generalization of the product formula you give.  (The problem is that local extrema may occur within the interiors of the intervals).  For nonlinear functions you basically have to optimize the function subject to the interval constraints.
Comment: You're right @whuber that it isn't as simple as applying all the left and right endpoints in general. It depends on the properties of the function. See the [wiki page](https://en.wikipedia.org/wiki/Interval_arithmetic) on handling broader classes of functions.
Answer: As an approximation, assume all observations within an interval
are located at its center.
Then you have four midpoints $m_j$ with corresponding frequencies $f_j$
for $j = 1,2,3,4.$ where $n = \sum_j f_n = 814.$ Then $\bar X \approx \frac 1n\sum_j f_jm_j = 53.51,$ and $S = \sqrt{S^2} = 21.84,$ in thousands of dollars, where $S^2 \approx \frac{1}{n-1}\sum f_j(m_j-\bar X)^2.$ [Using R.]
m = c(15, 30, 60, 90)
f = c(44, 240, 400, 130)
[1] 814
a = sum(f*m)/n;  a
[1] 53.51351
s = sqrt(sum(f*(m-a)^2)/(n-1)); s
[1] 21.84175

A more elaborate and perhaps slightly more accurate method is to
'reconstruct' the sample by assuming that observations are spread
uniformly at random in their respective intervals. Notice that this is
a random reconstruction and additional runs of the 'reconstruction' program
(without using the set.seed statement) will give slightly different
answers.
set.seed(623)
x = c(runif(44, 10, 20), runif(240, 20, 40),
      runif(400,40, 80), runif(130, 80,100))
mean(x);  sd(x)
[1] 53.84582
[1] 23.48832

The approximate mean $\bar X \approx 53.8$ and standard deviation $S\approx 23.5$
are not much different from the previous approximations.
A histogram based on the given intervals roughly suggests the
shape of the sample from which such a sample might have been taken.
It seems unlikely that the distribution of if incomes is normal. [Tick marks. from rug,
along the horizontal axis show the locations of the reconstructed data values.]
hist(x, br=c(10,20,40,80,100)); rug(x)

Using the reconstructed the sample,
one can get one kind of 95% bootstrap confidence interval $(52.3,\, 55.4)$, in which
the population mean $\mu$ might lie.
set.seed(2021)
a.re = replicate( 4000, mean(sample(x,rep=T)) )
ci = quantile(a.re, c(.025,.975)); ci
    2.5%    97.5%
52.28877 55.44453

hist(a.re, prob=T)
hdr = "Bootstrap Dist'n of Resampled Means"
hist(a.re, prob=T, col="skyblue2", main=hdr)
 abline(v=ci, col="red", lwd=2, lty="dotted")

Note: As @NickCox has suggested, alternate methods of approximation
and reconstruction might be used if you have some idea of the shape of
the income distribution. Also, as here, using beta distributions to reconstruct the lowest and highest intervals might be more realistic.
Comment: The smaller the bins, the better the assumption of uniformity of the data within each bin will hold. But the smaller the bin, the noisier the histogram will be.


How to decide in hook_nodeapi() if it was invoked after creating/updating node via Services module?

Question: I am developing a custom module, which should do things in hook_nodeapi() only if the node is being created/edited via Services. I couldn't find any data that is available at this point for deciding if the node is via Services or not.
I am aware of a possible solution, using request_uri() and deciding based on that (https://drupal.stackexchange.com/a/8568/1930), but it seems so wrong. Hardcoding the endpoint name is plain wrong. Workaround this by providing an admin interface and depend on configuration?
So, I would rather avoid the above, but couldn't come up with anything else so far. I am curious if others have had similar problems before and if there is a better solution.
UPDATE
The accepted answer should be used, as that is the cleanest solution. Unfortunately, I had to use a different one, which might still be useful to others so I am sharing it here: https://gist.github.com/Temaruk/5884209
Answer: I think there's a point in the system not normally telling you this, since we want to avoid any kind of coupling between the systems. Based on that I guess there's no built in way to get the information you want. Strictly speaking, you should probably consider why you are doing what you are doing, as it's not good practice.
Possible methods:
You could implement a custom node resource, which hands over node creation to the regular services callback after having done
$node->creator = 'services';

or possibly:
$node_origin = &drupal_static('node_creation_tracker');
$node_origin = 'services';

after which you could retrieve this data with the same method. Implementing a resource is not a complicated process, but requires quite a bit of knowledge about services.
Comment: Very good point and probably the most "kitten-safe" way of doing it. Unfortunately, I had to go with a different method (updated my question with what I did)... Thanks for the nice solution!
Answer: You might be able to do something with user roles, eg, have all "real" people assigned a role in addition to just "authenticated user" and then check for that inside of nodeapi() (and then set a field inside the content to reflect that if you need this to have some permanence)


If a linear operator $T$ has minimal, characteristic polynomial $q^k$ for $q$ irreducible, a $T$-invariant subspace has no $T$-invariant complement.

Question:
Let $T$ be a linear transformation on a finite dimensional vector space $V$ over the field $F$. Let $p_T$ be the minimal polynomial of $T$ and $f_T$ be the characteristic polynomial of $T$. If $p_T = f_T = q^k$ for some irreducible $q$ with $k > 1$, show that no nonzero proper $T$-invariant subspace can have a $T$-invariant complement.

My approach so far is the following: Let $W$ be a nonzero $T$-invariant proper subspace of $V$. Suppose that $W$ has a $T$-invariant complement $W'$.
We know that since $p_T = f_T$, $T$ has a cyclic vector $\alpha$ and that $V$ has a basis $\{\alpha, T\alpha, \dotsc, T^{n-1}\alpha\}$. If $\alpha$ is in $W$ then $W' = \{0\}$ and we are done (and vice versa), so suppose $\alpha = w + w'$ where $w \in W$ and $w' \in W'$.
From here, though, I am not sure how to proceed. Is this the best approach? Is there a better one?
Comment: If $V=W_1\dotplus W_2$, $\dim W_j<\dim V$, then the characteristic polynomial of $T|_{W_j}$ must be of the form $q^n$ with $n1$ is superfluous, since for $k=1$ the statement is vacuously true (there are no nonzero proper $T$-invariant subspaces in that case).
Comment: See also [this question](http://math.stackexchange.com/q/377834/18880).
Answer: As per Christian's observation in a comment on the origin question:
Let $p_W$ and $p_{W'}$ be the minimal polynomials of $W$ and $T$, respectively. Since $p_T = q^k$ with $q$ irreducible ($k = \dim V$), $p_W = q^m$ and $p_{W'} = q^{m'}$.
Now, since both $W$ and $T'$ are $T$-invariant, i.e., $TW \subseteq W$ and $TW' \subseteq W'$, we must have $m < k$ and $m' < k'$ for otherwise $W = 0$ or $W' = 0$, contrary to our assumptions.
Let $n = \max{m,m'}$; $q^n$ annihilates both $W$ and $W'$, so $q^n$ annihilates $W \oplus W' = V$. However, $n < k$, and $q^k$ is the minimal polynomial of $W$, which is a contradiction.
Therefore, if $W$ is a $T$-invariant subspace, then it cannot have a nontrivial $T$-invariant complementary subspace.
Comment: I don't think you properly interpreted Christains hint, and I don't understand the thrid paragraph (in which $k'$ should probably be $k$). Where exactly do you use that the minimal polynomial is also characteristic polynomial?
Comment: More precisely the strict inequalities $m,m'<k$ are not justified: a the restriction to a subspace can in general very well have the same minimal polynomial as the full operator. Also the remark $k-\dim V$ is wrong; instead $\dim V=\deg(q^k)=k\deg(q)$ since $q^k$ is (also) the characteristic polynomial.


Preventing SwiftUI Frame Size Changes from Affecting Window Size in a macOS App

Question: I'm developing a macOS app using SwiftUI and have encountered a situation where adjusting the frame size of a SwiftUI View (specifically, a Rectangle) dynamically with a Slider causes the window size to change accordingly.
My app requires a variable window size that adapts to content, but I need the window size to remain unaffected by specific internal view size adjustments.
Common solutions like placing the view within a fixed size container or making the fixed window size explicitly aren't viable for my needs.
Thanks.
Here's a simplified version of sample:
import SwiftUI

struct ContentView: View {
    @State private var rectWidth: CGFloat = 100

    var body: some View {
        VStack {
            Rectangle()
                .frame(width: rectWidth, height: 100)
                .foregroundColor(.blue)
            Slider(value: $rectWidth, in: 50...2000)
                .padding()
        }
    }
}

Answer: Using GeometryReader solved the problem.
   import SwiftUI

    struct ContentView: View {
        @State private var rectWidth: CGFloat = 100

        var body: some View {
            GeometryReader { geometry in
                VStack {
                    Rectangle()
                        .frame(width: rectWidth, height: 100)
                        .foregroundColor(.blue)
                    Slider(value: $rectWidth, in: 50...2000)
                        .padding()
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity)
            }
        }
    }


I'm trying to make a clicker game for Python using pygame

Question: I'm relatively new to Python, and have been using pygame to make a simple idle clicker game. I'm a second year engineering student in high school, so I have a small background in C, but Python is a new territory for me.
I've made it to the point where I have two buttons, one for a multiplier, and one, which is the main button you click. I'm trying to figure out how I can make some kind of upgrade path that allows money to be passively generated over time. (i.e. when the button is pressed the first time, the cost is subtracted, and 1 money is added every second, then 2 when the button is pressed again, then 4, and so on).
I've tried to use some kind of while loop, but that results in the game dramatically slowing down, and the other buttons not responding. I've tried placing this code in different places, and have swapped out while and if multiple times, but that either doesn't work, or it yields the same result, mentioned above. Here is the loop for adding the money. The code below uses import time.
  while autocost == 1:
      time.sleep(1)
      money = money + autolvl

Here is an example button for the multiplier.
class multiplier:
def __init__(self, x, y, image, scale):
    width = image.get_width()
    height = image.get_height()
    self.image = pg.transform.scale(image, (int(width * scale), int(height * scale)))
    self.rect = self.image.get_rect()
    self.rect.topleft = (x, y)
    self.clicked = False
def draw(self):
    global money
    global multlvl
    global multcost
    pos = pg.mouse.get_pos()
    if self.rect.collidepoint(pos):
        if pg.mouse.get_pressed()[0] == 1 and self.clicked == False:
            self.clicked = True
            if money >= multcost:
                money = money - multcost
                multcost = multcost * 3
                multlvl = multlvl *2
    if pg.mouse.get_pressed()[0] == 0:
        self.clicked = False
    screen.blit(self.image, (self.rect.x, self.rect.y))

Values would be changed based on the needs of the button (in this case, swapping out variables like, autolvl and autocost.
Comment: Questions that ask for general guidance regarding a problem approach are typically too broad and are not a good fit for this site. Give a good read over [Where to Start](https://softwareengineering.meta.stackexchange.com/questions/6366/where-to-start/6367#6367), and  [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example "Minimal Reproducible Example") then edit your post to focus your question on a much narrower problem
Answer: If a loop is very fast, in your case you will get money faster.
Therefore you have to multiply the autolevel with the time that the loop took. If a loop takes 5 seconds, you need to add 5 times the money. If a loop takes 0.001 seconds, you need to add 0.001 times the money.
You added a sleep function that slows down the loops, but doesn't time the loop to exactly 1 second (or 1 millisecond, i am not sure)
import time

loop_start = time.time()

while True:
    if autocost == 1:
        money += autolevel * loop dt

    loop_dt = time.time() - loop_start
    loop_start = time.time()


Check if form field contains particular value, if so, do not allow user save

Question: I am having a lot of spam signups on a drupal site. I am even using captcha and mollum, but still getting a lot. I have a field that asks 'why are you signing up?' which, when a human user / non-signup signs up, is filled with proper information, however, it seems there are a lot of robots / fake sign ups that all fill the field with a value which is just the literal path to the node field value like why_are_you_Signing_up[und][0][value]. It is always the same. So I thought I could check for this value and cancel the sign up.
I have looked at hook_user_presave and hook_save. These look like good starting points.
Comment: As an aside, have you seen the [Spambot module](http://drupal.org/project/spambot)? It _"protects the user registration form from spammers and spambots by verifying registration attempts against the Stop Forum Spam (www.stopforumspam.com) online database. "_. Just another tool for the arsenal
Answer: hope I'm not stating the obvious but if your form resides in a template or module you can add server-side validation to the form values using a function like:
<code>function your_form_validate($form, &$form_state) {
  if ($form_state['values']['your_form_field_name']) {
    // Perform PHP validation, and return FALSE if rejected.
  }
}
</code>
Also, see Form generation.
Comment: For system forms like `user_register_form` you would need to use [`hook_form_alter`](http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_alter/7) to add your own validation function in `#validate` array of the form.


Meaning of integral in equation

Question: I was wondering that if $\int_0^xv(t)dt+C=\int v(x)dx$ where v is the velocity function and x is time, what is the meaning of $\int_0^xv(t)dt$ in the context of velocity or position or change in position? Does it even have any meaning because since $\int_0^xv(t)dt=\int v(x)dx-C$ and since C is unknown and $\int v(x)dx$ is an indefinite integral, I don't think $\int_0^xv(t)dt$ has meaning.
Comment: Physically in the expression $\int_0^x v(t) dt$, the upper limit of integration has the wrong units, so the expression is incorrectly labeled (i.e. really you are integrating against position and you just deceptively called the position along the integration $t$).
Answer: According to Newton's law of motion, one has
\begin{align*}
\textbf{R} = \frac{\mathrm{d}\textbf{p}}{\mathrm{d}t} = m\frac{\mathrm{d}\textbf{v}}{\mathrm{d}t} = m\textbf{a}
\end{align*}
where $\textbf{R}$ represents the resultant force acting on the body, $t$ is the time variable, $\textbf{p} = m(t)\textbf{v}(t)$ is the linear momentum ($m$ stands for the mass, $\textbf{v}$ stands for the velocity and $\textbf{a}$ stands for the acceleration). If we consider that the mass is constant, we can factor out it from the derivative of $\textbf{p}$, as previously shown. Based on such equation, we can now answer your question. By definition, the acceleration $\textbf{a}(t)$ is the derivative of the velocity. The velocity $\textbf{v}(t)$, by its turn, is the derivative of the position $\textbf{s}(t)$. Therefore we can interpret the given integral as
\begin{align*}
\int_{0}^{T}\textbf{v}(t)\mathrm{d}t = \int_{0}^{T}\frac{\mathrm{d}\textbf{s}}{\mathrm{d}t}\mathrm{d}t = \int_{0}^{T}\mathrm{d}\textbf{s} = \textbf{s}(T) - \textbf{s}(0)
\end{align*}
Thus, if you know the velocity, you know the position and the acceleration as well. Hope this helps.
Answer: The (definite) integral of the velocity between two times (in your case $0$ and $x$) is the (net) distance traversed in that time interval.
If you measure the position as the net distance from some fixed position you have a function whose derivative is the velocity. In that sense the position is an indefinite integral of the velocity. The "arbitrary constant" is there because the fixed starting position is arbitrary.

Meaning of integral in equation


Is $x^x=y$ solvable for $x$?

Question: Given that

$x^x = y$; and
given some value for $y$

is there a way to expressly solve that equation for $x$?
Comment: Take logs, set $x = e^t$ and apply this: http://math.stackexchange.com/questions/10261/inverse-of-y-xex
Comment: Assume $y$ is positive we have $x^x=y$ so $x\ln x=\ln y$ so $\ln x e^{\ln x}=\ln y$ so $\ln x=W(\ln y)$ so $x=e^{W(\ln y)}=\frac{\ln y}{W(\ln y)}$.
Comment: For $e^{-1/e} \lt y \le 1$ there will be two non-negative solutions for $x$ and for $y \lt e^{-1/e}$ there will be none
Comment: It is also known as the super-square root of $y$.
Answer: As Aryabhata mentions this is another application for the Lambert W function. The solution to your problem is presented in the wikipedia article. Using elementary substitutions you have
$$x=\frac{\ln(y)}{W(\ln y)}$$
If you are interested in the asymptotic growth of $x$ relative to $y$, note that for every $z$: $W(z) = \ln{z} - \ln\ln{z} + o(1)$. Hence:
$$x=\frac{\ln(y)}{\ln{\ln y} - \ln\ln{\ln y} + o(1)} = \Theta\left( \frac{\ln y}{\ln \ln y}\right)$$
Comment: Wow - thanks - I really didn't think it was possible.
Comment: @Josh: in fact this might as well be solved by defining a new ad-hoc function $Z(x)$ such that $Z(x)^{Z(x)}=x$, so that the solution of the equation is $x=Z(y)$; Lambert is defined by $W(x)e^{W(x)}=x$, there is little magic. The main advantage of reducing to the special Lambert function is that it has already been studied.
Answer: You should try WolframAlpha for similar problems. WolframAlpha would solve y=x^x for y=5 as shown here (using Lamber W Function as suggested before).
Comment: If you're just going to post a link to wolframalpha, you could at least make sure that it works...
Comment: I guess part of GSBabil's point is that Josh should have tried that first, before posting here.
Comment: If a natural number y is entered in "solve x^x=y" WA will give the numeric answer. Strangely it doesn't work for all real y. However, I downvoted since the link is no help in understanding how the solution was reached.
Answer: Given y, you can solve y = x**x with a simple iteration:

Set x_0 = 2 (or anything else really)
x_(i+1) = ln y / ln x_i
Repeat 2 until abs(x_(i+1) - x_i) < threshold

It's akin to Newton's method of finding square roots.
The convergence of this process is the "natural base of y to itself", or the "exponential root" of y.
If you think about this iteration, you're iteratively performing the base-change logarithm formula. So at first you get y's logarithm (or "bit length") in base 2. Then in base of what y was in base 2, and so on. Successive values oscillate around the "natural base of y to itself" until it converges.
It's pretty interesting. I wonder if there's anything special about the value of x for each y.
As other people have said, you can take log of each side, to get:
ln y = ln x**x, which is ln y = x ln x, and the iteration

Is $x^x=y$ solvable for $x$?


How to make strings from floating-point numbers with '.' (dot) as a decimal separator and not more than 3 digits after floating point?

Question: I have this code:
public String formatDouble(double d) {
   return String.format("???", d); //Should I use NumberFormat here?
}

For the sample input:
1.00
1,00
1,23
1.234567

I would like to get this output:
1
1
1.23
1.234

How can I configure the pattern (or maybe NumberFormat instance) for producing the correct output?
Answer: This would do roughly what you need:
Decimalformat df = new DecimalFormat("0.###");
df.setRoundingMode(RoundingMode.FLOOR);
df.format(1.2345);

However, the decimal separator (the dot) will be dependent on current locale. To override it, you may want to provide your own format symbols (see DecimalFormat.setDecimalFormatSymbols()).
Answer: Simple way: String.format("%.2f", 1234.23)
If you need thousand separator, add a comma before the dot: String.format("%,.2f", 1234.23) -> the result: 1,234.23.
Answer: DecimalFormat should do what you need.


Jquery Save Score

Question: How do you make the score update though input
At the moment if you input say 10 it returns 10 and doesn't save the new score.
What i want it to do is, say we play rounds , round 1 , round 2, round 3
var score = 0

Round 1 : i inputted 5 so my new score is 5 (var score  = 5)
Round 2 : i inputted 10 so my new score should be 15 (var score  = 15)
Round 3 :  i inputted 50 so my new score should be 65 (var score  = 65)

  <input id="number_1">
        Total

    <button id="add_score">Add</button>

Answer: Replace your line
totalScore = score + scoreAdd;
$('#counter').html(totalScore);

with the following.
score = score + scoreAdd;
$('#counter').html(score);

var score = 0;
$('#add_score').click(function() {
  scoreAdd = parseInt($('#number_1').val());
  score = score + scoreAdd;
  $('#counter').html(score);
});

<input id="number_1">
Total

<button id="add_score">Add</button>

Jquery Save Score