Insert clock into a program

Question: I want to ask if there is any way by which I can open a file to read after every 30 seconds.  Like, I want to insert a clock in which I call a file open function after every 30 seconds.
Thanks
Answer: You can periodically run code using alarm().
Comment: could u please tell me how to use alarm() or what it does thanks
Comment: be careful with signal handlers : your program can be interrupted anytime. it could be interrupted in the midle of a computation or a memory write operation. Your data is most likely inconsistent when executing the signal handler.
Answer: I'm not quite sure what your program does within the 30 seconds. But if you just want to do a short operation with your file and the wait until the next 30 seconds, then you could just run these operations in a loop and sleep for 30 seconds:
<code>#include <unistd.h>
#include <stdio.h>

int main( int argc, char *argv[] ) {

   while( true ) {
      FILE* myFile = fopen( "foo.txt", "r" );
      // do whatever you like with your file.
      fclose( myFile );

      // sleep for 30 seconds and then open the file again.
      sleep( 30 );
   }
}
</code>
If you want to do a lot of other computation during these 30 seconds you should consider multithreaing but that's another topic ;-)
Answer: To complete Sjoerd's answer, here is a possibility:
<code>#include <unistd.h>
#include <signal.h>
#define FREQ 30
void sig_handler(int signum) {
    // do whatever you want every FREQ seconds

    //reenable the timer
    alarm(FREQ) ;
}

int main() {
    signal(sig_handler, SIGALRM) ;

    //enable the timer
    alarm(FREQ) ;

    while(1) {
        //do whatever you want between signals
    }
}
</code>
it seems to work in my quick test
Comment: if there is a lot of work to be done every 30 seconds, you probably don't want this to happen in the sig_handler itself.  Then the sig_handler() should set a flag, and you could test for that flag in the while()-loop.  But then you will run in to a whole lot of other trouble.  I suppose "Advanced UNIX programming" cover this in great detail.  http://basepath.com/aup/
Answer: There isn't any reason as to why it can not be done. Its not just opening files, you can do whatever you want after a certain interval. There are several ways to implement it, even by using services provided by linux.
You may like to add a bit more detail as to what you want to achieve.
Comment: You didn't answer the question, so this isn't an answer. If you want to ask for more information, please add a comment instead of an answer.
Comment: i have ha file in which data will be updated after every 30 sec.i want to ask is there any built in function like which i gave an interval and it will call the file updation function after every 30 sec thanks

Insert clock into a program


java.lang.IllegalStateException : Could not find backup for factory javax.faces.context.FacesContextFactory

Question: I created my hello world JSF project, but when I deploy to Tomcat 7, I get this exception:
java.lang.IllegalStateException: Could not find backup for factory javax.faces.context.FacesContextFactory.
    at javax.faces.FactoryFinder$FactoryManager.getFactory(FactoryFinder.java:1135)
    at javax.faces.FactoryFinder.getFactory(FactoryFinder.java:379)
    at javax.faces.webapp.FacesServlet.init(FacesServlet.java:350)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

I have added those JARs to my project:

jstl-1.2.jar
javax.faces-api-2.2.jar

How is this caused and how can I solve it?
Comment: duplicate of http://stackoverflow.com/questions/18897900/could-not-find-backup-for-factory-javax-faces-application-applicationfactory-jav ?
Comment: Thank's for answering . I've seen it but this didn't resolves my problem
Answer:
IllegalStateException: Could not find backup for factory javax.faces.context.FacesContextFactory

This exception is easier to understand if you replace "backup" by "implementation". It ultimately boils down to "I found the JSF API, but nowhere a JSF impl in the same classpath context as where I found the JSF API". In other words, you've a JSF API somewhere in runtime classpath which isn't accompanied with any JSF impl. E.g. having a jsf-api.jar or even javaee.jar without any jsf-impl.jar or javax.faces.jar in the same classpath context. Note that a web application can have multiple classpath contexts. The JSF impl has to be present in exactly the same location as the first encountered JSF API according to the classloading rules, and you need to make absolutely sure that there are no duplicate and/or conflicting versions.
In your specific case,

I had added this jars to my project : jstl-1.2.jar and javax.faces-api-2.2.jar

The javax.faces-api-2.2.jar alone is not right. There are 2 problems:

That's the "blueprint" API JAR, intented for JSF implementors such as Mojarra and MyFaces.
You forgot the JSF implementation JAR.

Provided that you'd like to use Mojarra, follow the installation instructions in its README. In your specific case, get rid of that javax.faces-api-2.2.jar and put the latest javax.faces-2.x.x.jar in /WEB-INF/lib or pom.xml and this exception should disappear.
See also:

How to properly install and configure JSF libraries via Maven?
Answer: Need to changed the weblogic-application.xml of the ear project to
<?xml version='1.0' encoding='UTF-8'?>
<weblogic-application xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-application" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/weblogic-application
    http://www.bea.com/ns/weblogic/weblogic-application/1.0/weblogic-application.xsd">

    <prefer-application-packages>
        <package-name>org.opensaml.*</package-name>
        <package-name>org.slf4j.*</package-name>
        <package-name>antlr.*</package-name>
    </prefer-application-packages>
    <prefer-application-resources>
        <resource-name>javax.faces.*</resource-name>
        <resource-name>com.sun.faces.*</resource-name>
        <resource-name>com.bea.faces.*</resource-name>
        <resource-name>META-INF/services/javax.servlet.ServletContainerInitializer</resource-name>
        <resource-name>META-INF/services/com.sun.faces.spi.FacesConfigResourceProvider</resource-name>
    </prefer-application-resources>
</weblogic-application>

Follwoing jar version numbers must match exactly:

javax.faces-2.x.x.jar
jsf-api-2.x.x.jar
jsf-impl-2.x.x.jar
Answer: Thanks to My colleuge , @Lookub at stackoverflow ,he added another apache server and the set the port as 8084 , it all compiled. As ide, we are using netbeans 8.2.You may do this at Services>>Servers menu . Hope this helps.


Fixing slider alignment with background image

Question: I have made a slider containing a set of images. I want to fit the slider exactly into the (screen) background image of an iphone. The issue I am facing is that the slider and background images are not aligning properly as I want them to. I am a new to web development so can anyone guide me as how to align the slider to the background image. Any help will be appreciated. Thanks.
My code is here
Comment: Can we have a fiddle demo please.
Comment: Sorry for the trouble but I am finding it a bit complex to represent it in fiddle. Can you try it this way it would be really helpful.
Comment: Do you have full image of the mobile because as i am seeing its half cut.
Comment: half is enough for me @Steevan
Answer: In order to align elements and help simplify the development for mobile devices, CSS 3 Offers, among others, the media-query.
You can read all about CSS3 and walk through the tutorial at W3Schools
It is very helpful and easy guide for beginners in this section.


Count by ID if value is lower than and set the value 1

Question: I have a problem.
My table is tableXYZ
I have a row a where i set the year.
I have a row b where i need to set value 1 if the year from row a is lower than 2019 and 0 if is > 2019.
After all i need to make a count from row b only the 1 values as total.
How can i do that, because i tried a lot of examples but doesn't work.
Comment: Sample data, desired results, and an appropriate database tag would all help.
Comment: _because i tried a lot of examples but doesn't work_ then please post a query have you tried
Answer: This might help:
<code>SELECT COUNT(1) AS [b_count]
FROM (
    -- Use case to evaluate column a and set value for column b
    SELECT a,
    CASE WHEN a < 2019 then '1' else '0' end as [b]
    FROM tableXYZ
) AS X -- Alias of subquery
WHERE X.b = '1' -- Select only rows where b = '1'
</code>


Efficient floating point comparison (Cortex-A8)

Question: There is a big (~100 000) array of floating point variables, and there is a threshold (also floating point).
The problem is that I have to compare each one variable from the array with a threshold, but NEON flags transfer takes a really long time (~20 cycles in accordance to a profiler).
Is there any efficient way to compare these values?
NOTE: As rounding error doesn't matter, I tried the following:
float arr[10000];
float threshold;
....

int a = arr[20]; // e.g.
int t = threshold;
if (t > a) {....}

But in this case I getting the following processor command sequence:
vldr.32        s0, [r0]
vcvt.s32.f32   s0, s0
vmov           r0, s0    <--- takes 20 cycles as `vmrs APSR_nzcv, fpscr` in case of
cmp            r0, r1         floating point comparison

As conversion happens at NEON, there is no matter if I compare integers, by described way or floats.
Comment: Your code is inconsistent with your problem statement - the data is float but you show threshold as int - you also cast each float data value to int - why ? If you data is float then the threshold should be float and you should do a float comparison (i.e. no int-float conversions). Also, what do you plan to do with values that are greater than (or less than) threshold (this will determine whether NEON is appropriate or not) ?
Comment: Many people ditch NEON for being slower than ARM without knowing what to avoid and how to program SIMD properly. Depending on what you exactly want, it's either not SIMD feasible to start with, or you don't know how to handle if-else with NEON.
Comment: if-else on NEON : 1. create a mask value with a VCnn instruction. 2. calculate results for both cases (if, else) in two different registers. 3. combine both results with a VBnn instruction using the mask value from 1.
Comment: Since you always have to calculate both cases on NEON regardless of the condition met, it might be slower than on ARM, if the calculations are very complex. If there are multiple associated if-elses, forget NEON.
Comment: NEON->ARM register transfers always suffer 11~14 cycles. This should be avoided at all costs within loops. And why those type castings when you can compare floats very fast even without rounding errors? I'll show you how in a separate answer.
Comment: People over at codereview.stackexchange.com might have to say something to this too.
Comment: @Jake'Alquimista'LEE unfortunately, I can't forget about NEON as I have to use it for all floating point calculations.
Answer: If floats are 32-bit IEEE-754 and ints are 32-bit too and if there are no +infinity, -infinity and NaN values, we can compare floats as ints with a little trick:
#include <stdio.h>
#include <limits.h>
#include <assert.h>

#define C_ASSERT(expr) extern char CAssertExtern[(expr)?1:-1]
C_ASSERT(sizeof(int) == sizeof(float));
C_ASSERT(sizeof(int) * CHAR_BIT == 32);

int isGreater(float* f1, float* f2)
{
  int i1, i2, t1, t2;

  i1 = *(int*)f1;
  i2 = *(int*)f2;

  t1 = i1 >> 31;
  i1 = (i1 ^ t1) + (t1 & 0x80000001);

  t2 = i2 >> 31;
  i2 = (i2 ^ t2) + (t2 & 0x80000001);

  return i1 > i2;
}

int main(void)
{
  float arr[9] = { -3, -2, -1.5, -1, 0, 1, 1.5, 2, 3 };
  float thr;
  int i;

  // Make sure floats are 32-bit IEE754 and
  // reinterpreted as integers as we want/expect
  {
    static const float testf = 8873283.0f;
    unsigned testi = *(unsigned*)&testf;
    assert(testi == 0x4B076543);
  }

  thr = -1.5;
  for (i = 0; i < 9; i++)
  {
    printf("%f %s %f\n", arr[i], "<=\0> " + 3*isGreater(&arr[i], &thr), thr);
  }

  thr = 1.5;
  for (i = 0; i < 9; i++)
  {
    printf("%f %s %f\n", arr[i], "<=\0> " + 3*isGreater(&arr[i], &thr), thr);
  }

  return 0;
}

Output:
-3.000000 <= -1.500000
-2.000000 <= -1.500000
-1.500000 <= -1.500000
-1.000000 >  -1.500000
0.000000 >  -1.500000
1.000000 >  -1.500000
1.500000 >  -1.500000
2.000000 >  -1.500000
3.000000 >  -1.500000
-3.000000 <= 1.500000
-2.000000 <= 1.500000
-1.500000 <= 1.500000
-1.000000 <= 1.500000
0.000000 <= 1.500000
1.000000 <= 1.500000
1.500000 <= 1.500000
2.000000 >  1.500000
3.000000 >  1.500000

Of course, it makes sense to precalculate that final integer value in isGreater() that's used in the comparison operator if your threshold doesn't change.
If you are afraid of undefined behavior in C/C++ in the above code, you can rewrite the code in assembly.
Comment: Seems to be great idea. I still facing the issue with vmov.32 but mainly it's a good idea. Thanks.
Comment: @vasile: What bug are you talking about? What is complex? If it is, how do you make it simpler?
Comment: I was referring to  @Paul-R answer.
Answer: If your data is float then you should do your comparisons with floats, e.g.
float arr[10000];
float threshold;
....

float a = arr[20]; // e.g.
if (threshold > a) {....}

otherwise you will have expensive float-int conversions.
Comment: Well if there's a lot of code then the cost of the test should be negligible (unless the overwhelming majority of data points do not need processing ?).
Comment: If I make a comparison between 2 floats it causes expensive flag-register transfer. That's why I tried to make a comparison between 2 integers.
Comment: What operations are you subsequently performing when the threshold test is true/false ?
Comment: vcmpe.f32 s17, s16
       vmrs APSR_nzcv, fpscr
If I got your question.
Comment: Alex: what I meant was: what happens in the `{ ... }` after your threshold test ? This will determine whether using NEON for the test is appropriate or not.
Comment: There is a lot of code after test, that's why I marked it as `...`.
Answer: Your example shows how bad compiler-generated codes can be :
It loads a value with NEON just to convert it to int, then does a NEON->ARM transfer that causes a pipeline flush resulting in 11~14 cycles wasted.
The best solution would be writing the function completely in hand assembly.
However, there is a simple trick that allows fast float comparisons without typecasting AND truncation:
Threshold positive (exactly as fast as int comparison) :
void example(float * pSrc, float threshold, unsigned int count)
{
  typedef union {
    int ival,
    unsigned int uval,
    float fval
  } unitype;

  unitype v, t;
  if (count==0) return;
  t.fval = threshold;
  do {
    v.fval = *pSrc++;
    if (v.ival < t.ival) {
      // your code here
    }
    else {
      // your code here (optional)
    }
  } while (--count);
}

Threshold negative (1 cycle more per value than int comparison):
void example(float * pSrc, float threshold, unsigned int count)
{
  typedef union {
    int ival,
    unsigned int uval,
    float fval
  } unitype;

  unitype v, t, temp;
  if (count==0) return;
  t.fval = threshold;
  t.uval &= 0x7fffffff;
  do {
    v.fval = *pSrc++;
    temp.uval = v.uval ^ 0x80000000;
    if (temp.ival >= t.ival) {
      // your code here
    }
    else {
      // your code here (optional)
    }
  } while (--count);
}

I think it to be quite a lot faster than the accepted one above. Again, I'm a bit too late.
Answer: If the rounding errors do not matter, then you should use std::lrint.
The Faster Floating Point to Integer Conversions recommends to use it for float to int conversion.


Render Bootstrap modal from partial in rails

Question: I am attempting to clean up my code a bit by placing my modal code inside of a partial, however I am encountering problems when trying to call the modal.
I tried the solution provided by How to show twitter bootstrap modal via JS request in rails?, but if I understand correctly I have to add code to a particular controller to display the modal. That would be fine however I would like to display the modal regardless of the controller/view it is in. Is this possible?
What I have (completely from the above question):
current link (views/static_pages)
<%= link_to "ModalTest", 'shared/testmodal', {:remote => true, 'data-toggle' => 'modal', 'data-target' => "testmodal" }%>

show.js.erb
$('.modal-body').html('<%= escape_javascript(render :partial => 'shared/testmodal'%>');
$('.modal-header').remove();

previous attempt:
<%= link_to "ModalTest", render(:partial => 'shared/testmodal') %>

Answer: You can include the modal contents you put in the partial, in any view you need or in your application.html, with:
<%= render "shared/testmodal" %>

And toggle it with:
<%= link_to "ModalTest", "#testModal", "data-toggle" => "modal" %>

Where #testModal is your modal id.
Comment: It worked for the given example, but I've got one question. As you said you wanted to "display the modal regardless of the controller", how did you do that part to load the instance variables from the right controller asynchronously?
Comment: I created the variable inline in the form itself


Sem retorno de geolocalização utilizando Phonegap

Question: Estou usando o código para pegar a geolocalização do Phonegap, mas mesmo assim, quando eu emulo o app, ele não me retorna nada. Existe alguma coisa errada no código?
index.html

    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
    <link rel="stylesheet" type="text/css" href="css/index.css" />
    <title>Hello World</title>

Watching geolocation...

        <button onclick="clearWatch();">Clear Watch</button>

config.xml
<feature name="Geolocation">
    <param name="android-package" value="org.apache.cordova.geolocation.GeoBroker" />
</feature>
<feature name="NetworkStatus">
    <param name="android-package" value="org.apache.cordova.networkinformation.NetworkManager" />
</feature>

AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Comment: Certo, você configurou o emulador para simular a existência de um GPS, mas isso por si só não te informa as coordenadas. Para isso, abra a perspectiva DDMS e com o emulador iniciado, seleciona a aba Emulator Control e na seção Location Controls você pode manualmente informar uma latitude e longitude para enviar, ai sim o seu GPS simulado irá entrar em ação.
Comment: Usando o emulador, é preciso também simular a localização pelo DDMS, caso você esteja usando o Eclipse. Isso já foi feito?
Comment: Olá @LuannaIozzi se você conseguiu achar uma solução por favor poste ela no campo de resposta para outras pessoas com o mesmo problema que você ser beneficiadas ;) Obrigado..
Comment: Então, eu configurei o DDMS na minha maquina e não funcionou, mas uma outra pessoa que esta trabalhando comigo neste projeto, configurou e funcionou normalmente. Acredito que seja as minhas configurações de eclipse.
Comment: Eu configurei o AVD seguindo os passos descritos neste link [Developer Android](http://developer.android.com/tools/devices/managing-avds.html#hardwareopts). Configurei o **hw.gps**
Comment: Muito obrigada. vou configurar aqui e tentar simular o GPS. Caso não consiga, te informo =D
Answer: Adicione isso ao seu AndroidManifest.xml
 <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />

E então tente simular suas localizações dentro do próprio aplicativo e depois no DDMS para verificar se pode ser uma restrição ou bug do PhoneGAP.


Fixed effects gamma estimator?

Question: Question 18.12 in Wooldridge's Econometric Analysis of Cross Section and Panel Data describes a "fixed effects gamma estimator", which appears to be analogous to a fixed effects Poisson estimator, with the obvious change in distribution assumption.
I am interested in using this estimator in another context, and would like to know something about its properties, but this textbook problem is the only reference I can find.  I've tried to find more information about it, with no success at all.  Can anybody point me to a book, a published paper, a dissertation, anything?
Comment: @Xi'an: I didn't add the self-study tag because I don't think the self-study tag is appropriate.  I am _not_ asking for help with an exercise; I am not even trying to do the exercise.
Comment: Please add `self-study` as a tag and provide details about the problem and your issues.
Comment: @Xi'an: I have edited the question to make this clearer.
Answer: I'm going to provide a partial answer to my own question.
It helps if we look at consider the fixed effects Poisson (FEP) estimator first.  The following is based on exercise 19.7 in Wooldridge.  I'll just sketch it out because I don't want to provide a full answer to someone's homework!
Fixed effects Poisson
The standard FEP assumptions are that, conditional on $(\mathbf{x}_i,c_i)$, $y_1 \ldots y_T$ are independent Poisson variables with means $c_i m(\mathbf{x}_i,\beta)$.  Given that, the conditional log likelihood for unit $i$ is
$l_i(c_i,\beta) = \sum_{t=1}^{T} \left[ -c_i m(x_{it},\beta) + y_{it} \log(c_i) + y_{it} \log(m(x_{it},\beta)) \right] $
where we're treating $c_i$ here as a parameter to estimate along with $\beta$, and we omit a term that doesn't depend on $c_i$ or $\beta$.
Note: I think the problem in the textbook has a typo here.  In the text, $y_{it}$ does not multiply $\log(c_i m(x_{it},\beta))$.
Now, just to see what happens, let's not do the usual conditional maximum likelihood approach for FEP, and instead treat $c_i$ as parameters to estimate along with $\beta$.  If we let $n_i=\sum_{t=1}^{T} y_{it}$, assume that $n_i>0$, and maximize $l_i$ with respect to $c_i$.  It's easy to show that we obtain
$c_i(\beta) =  \frac{n_i}{\sum_{\tau=1}^{T} m(x_{i \tau},\beta)}$
If we plug this back into the log likelihood, we get log likelihood as a function of $\beta$ alone:
$l_i(c_i(\beta),\beta) = \sum_{t=1}^{T} \left[ -\frac{n_i m(x_{it},\beta)}{\sum_{\tau=1}^{T} m(x_{i \tau},\beta)} + y_{it} \log(\frac{n_i m(x_{it},\beta)}{\sum_{\tau=1}^{T} m(x_{i \tau},\beta)}) \right] $
Defining $p_t(\mathbf{x_i},\beta) = \frac{m(x_{it},\beta)}{\sum_{\tau=1}^{T} m(x_{i \tau},\beta)}$, we have
$l_i(c_i(\beta),\beta) = \sum_{t=1}^{T} \left[ -n_i p_t(\mathbf{x_i},\beta) + y_{it} \log(n_i p_t(\mathbf{x_i},\beta)) \right] $
which simplifies to
$l_i(c_i(\beta),\beta) = \sum_{t=1}^{T} y_{it} \log(p_t(\mathbf{x_i},\beta)) -n_i + n_i \log(n_i)$
Note: Again, I think the text has a typo here.  It has $(n_i-1)\log n_i$ instead of $n_i (\log (n_i) -1)$.
Now note that
$l_i(c_i(\beta),\beta) = \sum_{t=1}^{T} y_{it} \log(p_t(\mathbf{x_i},\beta))$
is the conditional log likelihood for unit $i$ under the standard conditional MLE approach to estimating the FEP model.  So the log likelihood is the same up to terms that don't depend on $\beta$.  In other words, the standard conditional MLE approach is equivalent to (yields the same estimator as) a MLE approach, i.e. just throwing in dummy variables for each unit along with the original explanatory variables $\mathbf{x_i}$.
Fixed effects gamma
This property does not hold for the fixed effects gamma model.  The following is based on exercise 19.12 in Wooldridge.  Again, I'll just sketch it out.
The fixed effects gamma assumptions are that, conditional on $(\mathbf{x}_i,c_i)$, $y_1 \ldots y_T$ are independent gamma variables with means $c_i m(\mathbf{x}_i,\beta)$ and variances $c_i^2 m(\mathbf{x}_i,\beta)$, i.e.
$y_{it} | \mathbf{x_i}, c_i \sim Gamma(m(\mathbf{x}_i,\beta), 1/c_i)$.
One can show, with a little work, that the density of $y_{i1} \ldots y_{iT}$ conditional on $n_i=\sum_{t=1}^{T} y_{it}$ does not depend on $c_i$.  This leads to the fixed effects gamma estimator, which is based on the conditional log likelihood
$l_i(\beta) = \log \Gamma \left( \sum_{t=1}^T m(x_{it},\beta) \right)
- \sum_{t=1}^T \log \Gamma \left( m(x_{it},\beta) \right) + \sum_{t=1}^T  m(x_{it},\beta) \log y_{it} - \left(\log n_i\right)  \sum_{t=1}^T m(x_{it},\beta) $
up to terms that do not depend on $\beta$.
If we try the other approach, where we maximize the full likelihood with respect to $c_i$, and then plug that in, we again obtain
$c_i(\beta) =  \frac{n_i}{\sum_{\tau=1}^{T} m(x_{i \tau},\beta)}$
However, the resulting log likelihood with the $c_i$ concentrated out is
$l_i(c_i(\beta),\beta) = \left( \sum_{t=1}^T m(x_{it},\beta) \right) \log \left(\sum_{t=1}^T m(x_{it},\beta)\right)
- \sum_{t=1}^T m(x_{it},\beta) + \left( \sum_{t=1}^T m(x_{it},\beta) \right) - \sum_{t=1}^T \log \Gamma \left( m(x_{it},\beta) \right) + \sum_{t=1}^T  m(x_{it},\beta) \log y_{it} - \left(\log n_i\right)  \sum_{t=1}^T m(x_{it},\beta) $
up to terms that do not depend on $\beta$.  This is not the same (up to terms that do not depend on $\beta$) as the conditional ML.  If the conditional ML is consistent, then the "full likelihood with estimates for $c_i$ plugged in" is not consistent.  However, I think this is in the $N \rightarrow \infty$ limit.  The first two terms in the "full + plugin" likelihood look like Stirling's approximation for the first term in the conditional likelihood.  So I suspect that, for what it's worth, the second estimator is consistent in the $T \rightarrow \infty$ limit.

Fixed effects gamma estimator?


Let $f(x) = x^n$. Show that $f^{(n)} = n!$ and $f^{(m)} (x) = 0$ for all $m > n$.

Question: I'm supposed to use mathematical induction to solve this

Show that $P(1)$ is true
Assume $P(K)$ is true
Show that $P(K+1)$ is true

How do I approach this problem?
Comment: Wow, this question needs some serious editing!
Comment: If $f(x)=x^{n+1}$ then $f'(x)=(n+1)x^n$. Note that $f^{(n+1)}(x)=f' ^{(n)}(x)$.
Answer: You approach the problem by following the steps. Keep in mind that $P(n)$ is the statement

$f^{(n)} = n!$ and $f^{(m)}(x)=0$ for $m>n$.

Now, if this is $P(n)$, what is $P(1)$?
How would you prove that $P(1)$ is true?

Once that is done, try to write down $P(k)$ (which is what you assume to be true) and $P(k+1)$ (which is what you want to prove). Write them both down and try to see what the connection between them is. The statements will be very similar.
Comment: First and second steps seem pretty clear. I got $f^{(k+1)}(x) = k(k-1)x^{k-2}$ in the third step; which looks similar to the proof @Jan showed below. Is this right?
Comment: The equation $f^{(k+1)}(x) = k(k-1)x^{k-2}$ makes no sense without telling me what you are proving.
Comment: I'm trying to prove $f^{(n)} = n!$ and $f^{(m)}(x) = 0$ when $m > n$. I kinda see it but i don't have a clue how to show it
Answer: Notice, $n\in\mathbb{Z^+}$:
$$\frac{\text{d}^n}{\text{d}x^n}\left(x^a\right)=\begin{cases}a!\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\text{when}\space n=a\\
0\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\text{when}\space n>a\\
\frac{a!}{(a-n)!}\cdot x^{a-n}\space\space\space\space\space\space\space\space\text{when}\space n<a
\end{cases}$$
Because (example):
$$\frac{\text{d}^3}{\text{d}x^3}\left(x^2\right)=\frac{\text{d}^2}{\text{d}x^2}\left(2x^1\right)=\frac{\text{d}}{\text{d}x}\left(2x^0\right)=0$$
$$\frac{\text{d}^3}{\text{d}x^3}\left(x^3\right)=\frac{\text{d}^2}{\text{d}x^2}\left(3x^2\right)=\frac{\text{d}}{\text{d}x}\left(6x^1\right)=6x^0=6=3!$$
And to proof those, use this:
$$\frac{\text{d}}{\text{d}x}\left(x^a\right)=ax^{a-1}$$
$$\frac{\text{d}^2}{\text{d}x^2}\left(x^a\right)=a(a-1)x^{a-2}$$
$$\frac{\text{d}^3}{\text{d}x^3}\left(x^a\right)=a(a-1)(a-2)x^{a-3}$$
$$\frac{\text{d}^4}{\text{d}x^4}\left(x^a\right)=a(a-1)(a-2)(a-3)x^{a-4}$$
$$\frac{\text{d}^5}{\text{d}x^5}\left(x^a\right)=a(a-1)(a-2)(a-3)(a-4)x^{a-5}$$


Expression logical statements using rules of inference with quantifiers

Question: So in my Discrete Mathematics class, the professor went well over the topics of both Propositional & Predicate logic as well as Rules of Inference but he did not explain how to express logical, propositional statements using rules of inference with quantifiers.
I have the following sets:
A = {Discrete Math Students}
B = {Boolean Algebra Students}
C = {All Students}
I am asked to formalise the following statement:
P: If someone is a student of Discrete Mathematics, then, they must study Boolean Algebra.
With propositional logic, this would be something like p -> q but I'm really stuck.  How do I express these statements in the way that is asked?
Comment: $\forall x (x\in A \implies x\in B)$, no?
Comment: If x $\in A$ then $x\in B$, no?
Comment: @topologicalmagician I think it involves notation like ∀ and ∃ but not sure.
Comment: @topologicalmagician I guess.  It looks about right but I'm not exactly sure.
Answer:
If someone is a student of Discrete Mathematics, then, they must study Boolean Algebra.

The "someone" is a bit of a miscue, since "they must" actually indicates that this is in fact a universal statement.
Thus you need to express: "For any one, if they are in the set of Disctrete Mathematics Students, then they are in the set of Boolean Algebra Students," using a universal quantifier ($\forall$), a term (such as $x$), the inclusion operator ($\in$), the conditional operator ($\to$), and whichever of the sets ($A,B,C$) are appropriate.


SpringBoot - activiti - Injecting org.activiti.engine.TaskService

Question: I've created this class:
public class ActivitiWorkflowService  {

    private final TaskService taskService;

..
}

but I have this problem when init the project:
     No qualifying bean of
type 'org.activiti.engine.TaskService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

Answer: I expect that your class has a constructor such as:
public class ActivitiWorkflowService  {

    private final TaskService taskService;

    public ActivitiWorkflowService(TaskService taskService) {
        this.taskService = taskService;
    }
}

The error you are getting is because Spring cannot autowire this class to the ActivitiWorkflowService - it probably was not defined in the Spring context.
Depending on the configuration you use you can either:
Define class with @Component or @Service annotation and let @ComponentScan do its work:
@Component //@Service
public TaskService {
...
}

or if you are using @Configuration class define the bean of type TaskService
@Configuration
public class AppConfig {
    @Bean
    public TaskService taskService() {
         return new TaskService();
    }

    @Bean
    public ActivitiWorkflowService activitiWorkflowService(TaskService taskService) {
        return new ActivitiWorkflowService(taskService);
    }
}


How to stop recursive os.walk on a parent path that contains the first instance of a string from a list, while allowing os.walk to query sibling dirs

Question: I am using os.walk to query a directory tree for directories with names that include any strings from a my_list.
Directory tree:
./user/zebra/
./user/zebra/zebra_01/
./user/zebra/zebra_02/
./user/lion/
./user/lion/lion_01/
./user/lion/lion_01/giraffe_02
./user/giraffe/
./user/giraffe/giraffe_01

my_list = ['zebra', 'giraffe']

My script:
for dirpath, dirnames, filenames in os.walk(<path_to_directory_tree>, topdown=True):
    for folders in dirnames:
        for x in my_list:
            if x in folders:
                source_paths = os.path.join(dirpath, folders)

Output (i.e. print(source_paths)):
./user/zebra/
./user/zebra/zebra_01/
./user/zebra/zebra_02/
./user/lion/lion_01/giraffe_02/
./user/giraffe/
./user/giraffe/giraffe_01

I can then further process this output to retain only the desired paths:
./user/zebra/
./user/lion/lion_01/giraffe_02/
./user/giraffe/

But with a massive directory tree, this method takes a very long time. Therefore, I want to avoid generating and then filtering the initial output by having os.walk stop searching recursively for "my_list" directories once there is a parent path match, such that only the desired path output is generated.
I have seen dirnames[:] = [] used, but this would retain only ./user/giraffe/ (but not ./user/zebra/)
Comment: It's unclear your desired output. Can you explain the criteria for desired output?
Why `./user/lion/lion_01/giraffe_02/` in the desired output ?
Comment: Sure, sorry about that. I do not want os.walk to generate any path that contains multiple instances of strings in my_list (including multiples of the same string), such that the output is all paths that contain only one instance of any string found in my_list
Answer: You can take the count element in my_list and filter accordingly,
result = []
my_list = ['zebra', 'giraffe']
for dirpath, dirnames, filenames in os.walk(<path_to_directory_tree>, topdown=True):
    for folders in dirnames:
        source_path = os.path.join(dirpath, folders)
        if sum(source_path.count(x) for x in my_list) == 1:
            result.append(source_path)

Working demo with a list of files.
In [40]: l
Out[40]:
['./user/zebra/',
 './user/zebra/zebra_01/',
 './user/zebra/zebra_02/',
 './user/lion/lion_01/giraffe_02/',
 './user/giraffe/',
 './user/giraffe/giraffe_01']

In [41]: for i in l:
    ...:     if sum(i.count(x) for x in my_list) == 1:
    ...:         print(i)
    ...:
./user/zebra/
./user/lion/lion_01/giraffe_02/
./user/giraffe/

Edit:
for dirpath, dirnames, filenames in os.walk(<path_to_directory_tree>, topdown=True):
    dirnames[:] = [d for d in dirnames if sum(d.count(x) for x in my_list) > 1]
    for folders in dirnames:
        source_path = os.path.join(dirpath, folders)
        result.append(source_path)

dirnames[:] = [d for d in dirnames if sum(d.count(x) for x in my_list) > 1] - This will exclude the directory with multiple occurrences in my_list from the os.walk.
Reference
Comment: This does generate the desired output, but I am looking for a way to prevent os.walk from doing an exhaustive recursive search of my directory tree. So, for example, instead of finding ./user/giraffe/giraffe_01 and removing it later, I want os.walk to find ./user/giraffe/ and then stop querying subdirectories of ./user/giraffe/ while still querying other paths until all paths with one (and only one) list element is identified (so I do not want to generate the list of paths containing one or more elements in the list)
Comment: dirnames[:] = [d for d in dirnames if sum(d.count(x) for x in my_list) > 1] returns an empty list and ==1 appears to capture only the dirnames with exact matches to elements in the list. So ./user/lion/lion_01/giraffe_02/ is excluded with my_list = ["giraffe", "zebra"], and (for example) ./user/zebra/zebra_01/ is retained


Apply-recur macro in Clojure

Question: I'm not very familiar with Clojure/Lisp macros. I would like to write apply-recur macro which would have same meaning as (apply recur ...)
I guess there is no real need for such macro but I think it's a good exercise. So I'm asking for your solution.
Answer: Well, there really is no need for that, if only because recur cannot take varargs (a recur to the top of the function takes a single final seqable argument grouping all arguments pass the last required argument). This doesn't affect the validity of the exercise, of course.
However, there is a problem in that a "proper" apply-recur should presumably handle argument seqs returned by arbitrary expressions and not only literals:
;; this should work...
(apply-recur [1 2 3])

;; ...and this should have the same effect...
(apply-recur (vector 1 2 3))

;; ...as should this, if (foo) returns [1 2 3]
(apply-recur (foo))

However, the value of an arbitrary expression such as (foo) is simply not available, in general, at macro expansion time. (Perhaps (vector 1 2 3) might be assumed to always yield the same value, but foo might mean different things at different times (one reason eval wouldn't work), be a let-bound local rather than a Var (another reason eval wouldn't work) etc.)
Thus to write a fully general apply-recur, we would need to be able to determine how many arguments a regular recur form would expect and have (apply-recur some-expression) expand to something like
(let [seval# some-expression]
  (recur (nth seval# 0)
         (nth seval# 1)
         ...
         (nth seval# n-1))) ; n-1 being the number of the final parameter

(The final nth might need to be nthnext if we're dealing with varargs, which presents a problem similar to what is described in the next paragraph. Also, it would be a good idea to add an assertion to check the length of the seqable returned by some-expression.)
I am not aware of any method to determine the proper arity of a recur at a particular spot in the code at macro-expansion time. That does not mean one isn't available -- that's something the compiler needs to know anyway, so perhaps there is a way to extract that information from its internals. Even so, any method for doing that would almost certainly need to rely on implementation details which might change in the future.
Thus the conclusion is this: even if it is at all possible to write such a macro (which might not even be the case), it is likely that any implementation would be very fragile.

As a final remark, writing an apply-recur which would only be capable of dealing with literals (actually the general structure of the arg seq would need to be given as a literal; the arguments themselves -- not necessarily, so this could work: (apply-recur [foo bar baz]) => (recur foo bar baz)) would be fairly simple. I'm not spoiling the exercise by giving away the solution, but, as a hint, consider using ~@.
Answer: apply is a function that takes another function as an argument. recur is a special form, not a function, so it cannot be passed to apply.
Comment: Sure, although I took the question to mean "given that one can't just write `(apply recur ...)`, how would one go about writing a macro which would capture the intended sense of that".
Comment: Yes Michał, I meant it like that. Thanks to both of you.

Apply-recur macro in Clojure


Retorno de json_encode tira a ordem do asort()

Question: O método asort() é usado para ordenar arrays, sem perder o índice.
Faço a ordenação, tanto na busca do SQL quanto no array. Porém, ao enviar os dados via JSON (usando json_encode), ele reordena as chaves.
Exemplo de Array, ordenado, montado com cidades e meu índice na tabela:
Array
(
    [4550] => AGUA BRANCA
    [8339] => ANADIA
    [3292] => ARAPIRACA
    [7509] => ATALAIA
    [21265] => BARRA DE SANTO ANTONIO
    [9109] => BARRA DE SAO MIGUEL
    ...

Exemplo de JSON, mostrado no PREVIEW do navegador (ainda ordenado):
"cidades":{"4550":"AGUA BRANCA","8339":"ANADIA","3292":"ARAPIRACA","7509":"ATALAIA","21265":"BARRA DE SANTO ANTONIO","9109":"BARRA DE SAO MIGUEL","6127"

Exemplo de Options, gerados via ajax, dos dados:
<option value="314">MACEIO</option>
<option value="872">PILAR</option>
<option value="1145">UNIAO DOS PALMARES</option>
<option value="1432">RIO LARGO</option>
<option value="1647">MARIBONDO</option>
<option value="1648">SAO MIGUEL DOS CAMPOS</option>
<option value="1845">PARIPUEIRA</option>

Na recepção do ajax, não peço pra ordenar por chave, que é o que acontece. A geração do meu SELECT é simplesmente:
$.each(data.cidades,function(k,v){
    options += "<option value='"+k+"'>"+v+"</option>";
});
$("#consumidor_cidade").html(options);

Comment: Acredito que o seu problema seja relacionado a forma como o javascript armazena internamente seus objetos. Acredito que não tenha como você garantir a ordenação dos registros através de propriedades. Por este motivo, sugiro que mude seu json para ser um array ao invés de um objeto
Comment: Tenta dar um `console.log(v)` dentro do each pra ver se ele está ordenado
Comment: @jlHertel Esse foi o problema: A necessidade de se enviar um Objeto. Antes era como array, sem índice. Mas houve a necessidade de se gravar índice no retorno.
Answer: O problema não é no json_encode, como você mesmo mostrou no preview vem na ordem correta.
O problema acontece pois no JavaScript apenas arrays tem ordem definida, mas não possuem indices associativos, então ao fazer um json_encode o PHP gera um JSON no formato de objeto - que não possui ordem definida.
O que você pode fazer é enviar um atributo a mais na lista com a ordem, ou deixar o índice do array sequencial na ordem que você quer exibir e salvar o id e o nome numa estrutura interna.
Uma estrutura nesse estilo ira manter a ordem.
$arr = [
  ['codigo'=>'4550', 'nome'=>'AGUA BRANCA'],
  ['codigo'=>'8339', 'nome'=>'ANADIA']
]

Ou então especificando a ordem:
$arr = [
  ['codigo'=>'4550', 'nome'=>'AGUA BRANCA', 'order'=>0],
  ['codigo'=>'8339', 'nome'=>'ANADIA', 'order'=>1]
]

EDIÇÃO DO REQUISITANTE PARA MOSTRA DA RESPOSTA CERTA
Na montagem do meu array, foi feita dessa forma:
while ($resultado = pg_fetch_object($res)) {
    $cidades[] = array("cidade_id" => $resultado->cidade, "cidade_nome" => $resultado->cidade_nome);
}
/*envio*/
return json_encode(array("ok"=>true,"cidades" => $cidades));

E a montagem pelo jQuery foi descrita na resposta do Hertel.
Comment: @WilliamAparecidoBrandino como coloquei na resposta, o javaScript não mantém essa ordem, você vai ter que enviar esses dados em uma estrutura que tenha explicito essa ordem para poder remontar a listagem.
Comment: @WilliamAparecidoBrandino adicionei um exemplo de uma estrutura para manter a ordem.
Comment: Até editei o título para "retirar a culpa" do `json_encode`, mas como disse no comentário da pergunta, na mudança da necessidade do recebimento da informação, aconteceu essa desordem.
Answer: Como o @Marcos já comentou, seu problema não está na função json_encode, mas sim no modo como as propriedades são indexadas internamente pela engine do Javascript.
Uma solução alternativa ao seu problema é utilizar um array e ter vários objetos ordenados dentro dele:
<?php
$array = [
   [
     "indice" => 4550,
     "nome"   => "AGUA BRANCA"
   ],
   [
     "indice" => 8339,
     "nome"   => "ANADIA"
   ]
];

E no javascript faça:
$.each(data.cidades,function(k,v){
    options += "<option value='"+v.indice+"'>"+v.nome+"</option>";
});
$("#consumidor_cidade").html(options);

Comment: Sim, montei aqui e agora funcionou. Tive que fazer o que vocês disseram. Como os dois responderam a mesma coisa, não sei em quem eu marco a resposta certa.
Comment: @WilliamAparecidoBrandino, o importante é que seu problema foi solucionado. Pode marcar qualquer um dos dois que está ótimo.


Circles1 with maximum and minimum values

Question: I have a question regarding the maximum and minimum values of $y-3x+4$ for which point $(x,y)$ moves along circle $(x-2)^2+y^2=1$.
I can calculate the question but I do not know where to locate the maximum and minimum values on the graph.
Comment: The maximum value is $-2+sqrt10$
Answer: Approach the problem geometrically:

Find the intersections point(s) between line and circle (solve system of equations).
If there are two points, the max will occur at the right point (bc line has positive slope).
If there is only one intersection, the single intersection point will be the maximum (tangent to circle).

Also, the max value is not $-2+\sqrt{10}$ as you can see in picture.
Comment: I use $y-3x+4=k$, and $y=3x+k-4....(1)$, and circle is $(x-2)^2+y^2=1.......(2)$.  By using the Quadratic formula I got $k=-2+\sqrt(10) and k=-2-\sqrt(10)$.
Comment: Ok, I assumed $k = 0$.
Comment: I am using a pre-calculus method by considering $y-3x+4=k$ If $k$ varies the line moves in parallel to itself.
Comment: Can you show me where the maximum and minimum values are on the graph? I am a little bit confused.
Comment: Maximum is the largest $y$-value of the two points.
Comment: Thank you very much. These were my points too, but I wanted to confirm. Much appreciated.


A Question About The First Step In Induction

Question: I am currently learning mathematical induction from this site (https://www.mathsisfun.com/algebra/mathematical-induction.html). It has broken induction into 3 steps:

Show that it is true for n=1
Assume it is true for n=k
Show that it is true for n=k+1

I have 4 questions:

Why, of all numbers do we pick n=1? Can't we pick something like n=1, n=2, or the like?
Why do we need the 3rd step? I get a feeling it is to prove that it is true for all n=k, but if that is so, how does it do it? It does prove that it is true for all n=k+1, but that is based on the assumption that n=k; and therefore doesn't prove it. Because if a proof is based on an assumption, how does that prove anything?
Why do we need the first step when we show that it is true for all n=k+1?
In n=k+1, why do we add 1? Why can't we subtract 1, or add 2, etc? Why must it be n=k+1?

Is it possible to answer the question at the level of a Pre-Calc student, who hasn't learnt Calculus (obviously), set theory, and all those complicated stuff?
This question is different from "Dominoes and induction, or how does induction work?" because I have learnt neither limit notation nor L'Hopital's rule, and the other question contains them. This is important for a Precalc student who understands neither of them.
Comment: @Yagger: Starting from $-1$ would be great if you are trying to prove something for all integers bigger than or equal to $-1$.
Comment: You want to prove that a property holds for all natural numbers. Modifying the process, say picking n=2 instead of n=1 would prove it holds for 2,3,4... but that's not what you want.
Comment: Possibly helpful: https://matheducators.stackexchange.com/questions/10021/why-are-induction-proofs-so-challenging-for-students/10057#10057
Comment: @Yagger Can you explain why that isn't something we want? What's wrong with proving it holds for 2,3,4 etc, or even 0 or -1 etc.
Comment: -1 isn't even a natural number so it doesn't make sense to start from there. What I mean is if you want to prove that a property holds for all naturals you have to take n=1 as the base case, as it has been pointed out in the answers. Starting from n=2 or proving that if something holds for n=k then it does for n=k+2 may be useful to prove something else, but not to prove that a property holds for any natural.  By the way the source that you posted doesn't seem too reliable.
Answer: Actually steps 2 and 3 should be grouped: what we have to prove is that from one case follows the next case, i.e. if we denote the property to be proved as $P(k)$, we really prove this:
$$\forall k,\enspace P(k)\implies P(k+1),$$
and as for all implications, to prove $\;A\implies B$, we show that if the premise $A$ is true, then the conclusion $B$ is necessarily true.
Intuitively, why does this work?
Well we've proved the initial case $n=1$ (or whatever …). If the inductive step has been proved, there follows that the case $n=2$ is true. So the case $n=3$ is true. Repeat this, say, 99 times, and you've proved it's true for $n=100$.
The induction theorem asserts that if you've proved an initial case $n_0$, and you've proved the inductive step: $P(n)\implies P(n+1)$ (not $P(n)$ nor $P(n+1)$ alone, but the implication), then  $P(n)$ is true for all $n\ge n_0$.
Answer:
You can prove it for $n=2$ or even $n=1000$ but then the induction proves the statement is true for $N\geq 1000$ rather than $N\geq 1$. It really depends on what you are trying to prove.

The rest of the questions sound a little like rambling because you do not understand what is happening when you use a proof by induction. I will try to explain that to you.
So first we prove that the statement is true for $n=1$ (or some other number, that is irrelevant).
Next, we show that if the statement is true for $n=k$ then it is true for $n=k+1$. Keep in mind, that we have not proved that the statement is true for $n=k$, we have proved the implication, " If the statement is true for $n=k$, then it is true for $n=k+1$". In layman terms, we have proved that if the statement is true for some number, then the statement has to be true for the next one.
Once we have done that, we go back to the first step we have done. We have shown that the statement is true for $n=1$, by our proof, that means the statement is true for the next number, $n=2$. But now, we know it is true for the next number $n=3$. etc, we do that continuously and so we have proven that the statement is true for all $N\geq 1$
Regarding question 4. If you prove the implication for $n=k+2$ then try to think why the reasoning above does not apply.
Comment: A "for example" on your last paragraph would help. Or even talking about how some inductions have different behaviours on odd and even indexes. Or stuff with a multi-step recurrence like X_n+2 =f(x_n)+g(x_n+1)
Comment: @JKreft I honestly did not want to overcomplicate it. Sure induction works if you prove it for $n=k+2$ and just show the statement is true for two consecutive starting values, but I felt it was not necessary.
Comment: Fair enough. I just thought you might help in thinking along why the reasoning might not apply. :)
Answer: Close your eyes and imagine you have a three years old boy and a very tall ladder.
The boy learns how to climb one step at the time.
If the boy does not get on the ladder then you can relax.
On the other hand if  the boy somehow gets on the first step of the ladder you will soon find him on the second and on the third and so forth.
Thus it is important to start at some point and it could be one or two or any other integer.It is also important to know that we can go one step higher at any time.
Now if you have P(1) and if you can conclude P(k+1) from P(k), and if you accept the Mathematical Induction as a valid proof, then the statement P(n) is true for all $n\ge 1 $
Comment: @mr_e_man          If the boy does not get on the ladder then you can relax.


Javascript loop object array

Question: Hi i m trying to get the data from a loop i wrote to go through a object and get some data from there.
my object looks like this
    {
id:12,
cities:[london, lisbon, berlin],
images[{id:1, image_urls:abc,},{id:2, image_url:bcd}, {id:3, image_url: cde}],
status: "published"

}

the function i wrote is to get the image_url data from this object:
 imagesUrlFunction() {
    console.log("array Length");
    console.log(this.images.length);
    let keys = this.images.length;

    for (let n = 0; n < keys; n++) {
      this.imagesUrls = this.images[n].image_url;

      console.log("imageUrlMedia Var");
      console.log(this.imagesUrls);
      // console.log(this.images[n]);
    }
  }

When i console log this.imagesUrls i can get my data, that is my url, and because is in loop i can get all the urls, or at least console log all urls.
My problem is i want to put that that into an object so i can use it with an *ngFor directive, but i cant.
I tried to create an empty object and assign imagesUrls to it, but with no sucess.
Can anyone help?
Thanks for your patient, i am just a newbie in javascript and educating my self on it.
Comment: By object do you mean you want to put the urls in an array by themselves? If not please show an example of what you expect to output
Comment: Your object is broken syntactically.
Comment: The first object in your array has a property `image_urls` and the others have a property `image_url`.  I assume the `s` at the end of the first one is just a typo, but you may want to fix that ;)
Answer: declare variable in component;
var images: any[];

ngOnInit(){

    var obj // Logic of get object

    this.images = obj.images;
}

use images var in view

    {{img.image_url}}

Answer: in your component.ts, add
response = {};

this.response =  {
id:12,
cities:[london, lisbon, berlin],
images:[{id:1, image_urls:abc,},{id:2, image_url:bcd}, {id:3, image_url: cde}],
status: "published"

}

in you component.html
(if you are using li, or use any as your need )

Answer: According to my understanding, you are mainly trying to make an array of image urls, You can simply use Array.map() for that :

var obj = {
  id:12,
  cities:["london", "lisbon", "berlin"],
  images:[{id:1, image_url:"abc"},{id:2, image_url:"bcd"}, {id:3, image_url: "cde"}],
  status: "published"
};

var result = obj.images.map((a) => a.image_url);

console.log(result);

Javascript loop object array


Why does a covering map has the injective induced homomorphism?

Question: Below is how I tried:
Let $p:(C,c_0)\rightarrow (X,x_0)$ be a covering map.
Let $[\gamma]\in \ker(p_*)$
Let $e_X,e_C$ be the constant loops at $x_0,c_0$ respectively.
Then $[e_X]=[p\circ \gamma]$.
Let $F$ be a path-homotopy between $e_X$ and $p\circ \gamma$.
Then, there exists a unique homotopy $G:I\times I\rightarrow C$ such that $p\circ G=F$ and $G(s,0)=c_0$, by homotopy path lifting theorem.
I have no idea how this applies that $p_*$ is injective.. Please help.. Why is $[\gamma]=[e_C]$?
Comment: Check out Munkres. I rather like his treatment of these topics (it's very, very clear).
Comment: Moreover, someone please recommend me a basic algebraic topology text which covers "covering space". Hatcher is extremly terse for beginners I guess so..
Comment: For an approach using covering morphisms of groupoids see my book "Topology and Groupoids", do a web search for info. This idea has been around since the first 1968 edition. The point is that a covering **map** is modelled algebraically by a covering **morphism**.
Comment: @CameronWilliams On which page of Munkres has this theorem? I can't find
Comment: I think it's in section 53 or something? Just search for covering spaces. It'll be in that general vicinity.
Comment: i found the one in 54. Thank you :)
Answer: Show that $G$ is a path homotopy between $\gamma$ and the constant loop $e_C$.
This should imply that $[\gamma] = [e_C]$ which means $\ker (p_*)$ is trivial, which means that $p_*$ is injective.


SSH config file?

Question: Is there a SSH config file (~/.ssh/config) information page with all attributes you can have in that file?
Who is managing the SSH protocol and its implementation in Mac (dont know what ssh client Mac uses)?
Comment: Belongs on server fault.
Comment: Would be better on Super User than Server Fault. This is a user issue, not an administrator issue.
Comment: the config files are all hidden in some deep directories, and they use a plist format, i messed with them at one point, but i don't remember where the files are, sorry.  Pretty much its all in an xml style formatting, instead of a simple unix type config.
Answer: These links should help you:

http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man5/ssh_config.5.html
http://www.panix.com/help/sw.macosx-ssh.html
Answer: Depends on your ssh client.
For OpenSSH there's man ssh_config.

SSH config file?


Find all natural divisors of a number (with Prolog)

Question: I want to create a predicate divisors(X,[Y]) which is true if
X>1 and Y is the list of all divisors of X starting with X and going down to 1.
What my code right now looks like:
divisors(1,[1]).
divisors(X,[Y,Z|Ys]) :-
    X>0,
    Y is X,
    Y>Z,
    divides(X,[Z|Ys]).

divides(X,[Y,Z|Ys]) :-
    Y>Z,
    0 is X mod Y,
    divides(X,[Z|Ys]).
divides(X,[1]).

But there are several problems with it:

prolog returns an error if asked for the list (e.g. ?-divisors(10,X).)
?- divisors(X,[Y]). Where [Y] is an incomplete list of divisors is true...

Edit by Guy Coder
This answer is by the OP and was posted in a comment below.
Moving here so others can see it.
divisors(X,R) :-
  X > 1,
  divisors(X,1,[],R).

divisors(X,D,R,R):-
  D>X.

divisors(N,D0,R0,R) :-
  divisors_0(N,D0,R0,R1),
  D is D0 + 1,
  divisors(N,D,R1,R).

divisors_0(N,D,R0,[D|R0]) :-
  divides(N,D).

divisors_0(N,D,R0,R0).

divides(N,D) :-
  0 is N mod D.

Op also noted some errors in this version:

It doesn't terminate if I ask a wrong statement like (10,[1,2,3]).
It throws an error if I ask a statement like (X, [10,5,2,1]). (-> Arguments are not sufficiently initialized.)
Comment: It might be better *not* to construct a list. It is quite common in Prolog if there are multiple answers, to unify these individually, one can use `findall/3` to construct a list of answers to a certain predicate.
Answer: In Prolog, it is quite common to use backtracking and propose multiple solutions to the same query. Instead of constructing a list of dividers, we thus can construct a predicate that unifies the second parameter with all divisors. For example:
divisor(N, D) :-
    between(1, N, D),
    0 is N mod D.

This then yields:
?- divisor(12, N).
N = 1 ;
N = 2 ;
N = 3 ;
N = 4 ;
N = 6 ;
N = 12.

The above algorithm is an O(n) algorithm: we scan for divisors linear with the value of the item for which we want to obtain the divisors. We can easily improve this to O(√n) by scanning up to √n, and each time yield both the divisor (of course in case it is a divisor), and the co-divisor, like:
emitco(D, _, D).
emitco(D, C, C) :-
    dif(D, C).

divisor(N, R) :-
    UB is floor(sqrt(N)),
    between(1, UB, D),
    0 is N mod D,
    C is N / D,
    emitco(D, C, R).

This still yield the correct answers, but the order is like a convergent alternating sequence:
?- divisor(12, N).
N = 1 ;
N = 12 ;
N = 2 ;
N = 6 ;
N = 3 ;
N = 4.

?- divisor(16, N).
N = 1 ;
N = 16 ;
N = 2 ;
N = 8 ;
N = 4 ;
false.

We can obtain a list of the divisors by using a findall/3 [swi-doc] or setof/3 [swi-doc]. The setof/3 will even sort the divisors, so we can implement divisors/2 in terms of divisor/2:
divisors(N, Ds) :-
    setof(D, divisor(N, D), Ds).

For example:
?- divisors(2, N).
N = [1, 2].

?- divisors(3, N).
N = [1, 3].

?- divisors(5, N).
N = [1, 5].

?- divisors(12, N).
N = [1, 2, 3, 4, 6, 12].

?- divisors(15, N).
N = [1, 3, 5, 15].

We can use reverse/2 to reverse that result.
Answer: While the answer by William is nice and probably faster here is answer closer to what you were writing.
divides(N,D) :-
    0 is N mod D.

divisors_0(N,D,R0,[D|R0]) :-
    divides(N,D).

divisors_0(N,D,R0,R0) :-
    \+ divides(N,D).

divisors(_,0,R,R).

divisors(N,D0,R0,R) :-
    divisors_0(N,D0,R0,R1),
    D is D0 - 1,
    divisors(N,D,R1,R).

divisors(X,R) :-
    X > 1,
    divisors(X,X,[],R), !.

Example:
?- between(1,15,N), divisors(N,Rs).
N = 2,
Rs = [1, 2] ;
N = 3,
Rs = [1, 3] ;
N = 4,
Rs = [1, 2, 4] ;
N = 5,
Rs = [1, 5] ;
N = 6,
Rs = [1, 2, 3, 6] ;
N = 7,
Rs = [1, 7] ;
N = 8,
Rs = [1, 2, 4, 8] ;
N = 9,
Rs = [1, 3, 9] ;
N = 10,
Rs = [1, 2, 5, 10] ;
N = 11,
Rs = [1, 11] ;
N = 12,
Rs = [1, 2, 3, 4, 6, 12] ;
N = 13,
Rs = [1, 13] ;
N = 14,
Rs = [1, 2, 7, 14] ;
N = 15,
Rs = [1, 3, 5, 15].

Edit
OP modified their code, see update in question and had some errors.
This version resolves those errors.
divisors(X,R) :-
  (
    var(X)
  ->
    false
  ;
    (
      var(R)
    ->
      X > 1,
      divisors(X,1,[],R)
    ;
      divisors_2(X,R), !
    )
  ).

divisors_2(_,[]).

divisors_2(X,[H|T]) :-
  divides(X,H),
  divisors_2(X,T).

divisors(X,D,R,R):-
  D>X.

divisors(N,D0,R0,R) :-
  divisors_0(N,D0,R0,R1),
  D is D0 + 1,
  divisors(N,D,R1,R).

divisors_0(N,D,R0,[D|R0]) :-
  divides(N,D).

divisors_0(_,_,R0,R0).

divides(N,D) :-
  0 is N mod D.

The first error: It doesn't terminate if I ask a wrong statement like divisors(10,[1,2,3]).
is fixed by adding to divisors/2
(
  var(R)
->
  X > 1,
  divisors(X,1,[],R)
;
  divisors_2(X,R), !
)

and
divisors_2(_,[]).

divisors_2(X,[H|T]) :-
  divides(X,H),
  divisors_2(X,T).

which just processes the list of denominators instead of generating a list.
The second error: It throws an error if I ask a statement like divisors(X, [10,5,2,1]). (-> Arguments are not sufficiently initialized.)
is resolved by further adding to divisor/2
divisors(X,R) :-
  (
    var(X)
  ->
    false
  ;
    (
      var(R)
    ->
      X > 1,
      divisors(X,1,[],R)
    ;
      divisors_2(X,R), !
    )
  ).

which checks if the first parameter X is a variable and if so just returns false. The other option would be to generate an infinite list of answers. While possible it wasn't requested.
Comment: Why not simply `?- between(1,15,N), divisors(N,Rs).` ?
Comment: Haha, only serious... more eyes see more.
Comment: Hey Guy Coder, thank you for your fast answer!
I have adapted the code a bit so that (10,[10,5,2,1]) is true as the exercises demands.
Still there are some bugs in the code:
1. It doesn't terminate if I ask a wrong statement like (10,[1,2,3]).
2. It throws an error if I ask a statement like (X, [10,5,2,1]). (-> Arguments are not sufficiently initialized.)
Comment: My code:
divisors(X,R) :-X > 1,
                divisors(X,1,[],R).
divisors(X,D,R,R):-D>X.
divisors(N,D0,R0,R) :-divisors_0(N,D0,R0,R1),
                      D is D0 + 1,
                      divisors(N,D,R1,R).

divisors_0(N,D,R0,[D|R0]) :-divides(N,D).

divisors_0(N,D,R0,R0).

divides(N,D) :-0 is N mod D.
Comment: @GuyCoder thank you for doing so, but it is actually my new code that has those flaws and errors...
Comment: If anybody knows how to get rid of them, that would be great. But it's not too important.


Somar valor total de cada categoria LINQ

Question: Tenho uma Lista de compras(ShoppingItens) assim:
Descricao: Padaria Campobelo
Valor: -24.00
Data: 06-03-2019
Categoria: Alimentacao

Descricao: Uber tecnologia
Valor: -24.00
Data: 07-03-2019
Categoria: Transporte

Descricao: Uber tecnologia
Valor: -30.00
Data: 08-03-2019
Categoria: Transporte

Gostaria de saber como faço para pegar a categoria com o maior gasto, tentei fazer da seguinte maneira:
var result = (from item in ListShoppingItens
              group item by item.Categoria into cat
              select new ShoppingItens
              {
                  Valor = cat.Sum(x => x.Valor)
             }).ToList();

Porém ele esta retornando apenas uma categoria, no caso a de viagens
A minha classe está assim:
public class ShoppingItens
{
    public enum Category
    {
        VIAGEM,
        DIVERSAO,
        ALIMENTACAO,
        HOSPEDAGEM,
        VESTUARIO,
        TRANSPORTE,
        HIGIENE,
        SEMCATEGORIA,
    }

    public DateTime Data { get; set; }

    public string Descricao { get; set; }

    public decimal Valor { get; set; }

    public Category Categoria { get; set; }
}

Comment: porque o valor é negativo? qual é mesmo o output que pretende (com exemplo)? porque na lista que deu de amostra colocou uma categoria  que não existe (supermercado)?
Comment: O valor é negativo porque é o valor que ele gastou naquela compra específica, ou seja, o dinheiro que saiu, se houver um valor positivo quer dizer que ele recebeu o dinheiro.
Answer: Fiz um exemplo em Console Application pra mostrar como pegar o valor agrupado de cada categoria.
var ListShoppingItens = new List<ShoppingItens>
        {
            new ShoppingItens { Data = DateTime.Now, Categoria = ShoppingItens.Category.ALIMENTACAO, Descricao = "TESTE", Valor = 1770 },
            new ShoppingItens { Data = DateTime.Now, Categoria = ShoppingItens.Category.DIVERSAO, Descricao = "TESTE", Valor = 1640 },
            new ShoppingItens { Data = DateTime.Now, Categoria = ShoppingItens.Category.SEMCATEGORIA, Descricao = "TESTE", Valor = 410 },
            new ShoppingItens { Data = DateTime.Now, Categoria = ShoppingItens.Category.ALIMENTACAO, Descricao = "TESTE", Valor = 150 },
            new ShoppingItens { Data = DateTime.Now, Categoria = ShoppingItens.Category.TRANSPORTE, Descricao = "TESTE", Valor = 160 },
            new ShoppingItens { Data = DateTime.Now, Categoria = ShoppingItens.Category.ALIMENTACAO, Descricao = "TESTE", Valor = 106 },
            new ShoppingItens { Data = DateTime.Now, Categoria = ShoppingItens.Category.HIGIENE, Descricao = "TESTE", Valor = 160 },
            new ShoppingItens { Data = DateTime.Now, Categoria = ShoppingItens.Category.HIGIENE, Descricao = "TESTE", Valor = 1044 },
            new ShoppingItens { Data = DateTime.Now, Categoria = ShoppingItens.Category.ALIMENTACAO, Descricao = "TESTE", Valor = 1440 },
            new ShoppingItens { Data = DateTime.Now, Categoria = ShoppingItens.Category.TRANSPORTE, Descricao = "TESTE", Valor = 150 },
            new ShoppingItens { Data = DateTime.Now, Categoria = ShoppingItens.Category.ALIMENTACAO, Descricao = "TESTE", Valor = 1550 },
            new ShoppingItens { Data = DateTime.Now, Categoria = ShoppingItens.Category.DIVERSAO, Descricao = "TESTE", Valor = 10 },
            new ShoppingItens { Data = DateTime.Now, Categoria = ShoppingItens.Category.ALIMENTACAO, Descricao = "TESTE", Valor = 12220 }
        };

        var resultado = from item in ListShoppingItens
                     group item by item.Categoria into cat
                     select new
                     {
                         Categoria = cat.Key,
                         Total = cat.Sum(x => x.Valor),
                     };

        foreach (var item in resultado)
            Console.WriteLine(item.Categoria + "-" + item.Total);

Comment: Funcionou, estava quase lá rs. Só um detalhe no seu código, a classe ShoppingItens não possui a propriedade Total, então precisei criá-la, mas mesmo assim obrigado.
Comment: No meu código a propriedade Total é anônima, por isso não foi necessário cria-la.
Fico contente que tenha funcionado. Bons códigos :)


Proof of the conjecture that the kernel is of dimension 2

Question: I already asked this question which has been answered. This question may seem very similar but the required matrix manipulations are probably very different here due to the addition of the matrix $\mathbf{P}$, which makes the problem more difficult.
"Experimentally", I found that the kernel (null space) of the following matrix is of dimension 2. I'd like to prove it, but haven't managed yet:
\begin{equation}
\text{for almost all } t>0,\quad \text{dim}\,\text{ker}\left(\mathbf{Q}_2\mathbf{Q}_1(t)-\mathbf{Q}_1(t)^{-1}\mathbf{Q}_2\right)\overbrace{=}^?\;2
\end{equation}
where:

$\mathbf{Q}_2$ is the identity matrix everywhere except in $(2n,2n)$:
\begin{equation}
\mathbf{Q}_2=\begin{bmatrix} \mathbf{I}_n & \mathbf{0}_n \\  \mathbf{0}_n & \mathbf{P}^{-1}\begin{bmatrix}1 & && \\ & \ddots && \\ & & 1& \\ &&& -1 \end{bmatrix}\mathbf{P}  \end{bmatrix}\in\mathbb{R}^{2n\times2n}
\end{equation}
where $\mathbf{P}\in\mathbb{R}^{n\times n}$ is any invertible matrix.
$\mathbf{Q}_1(t)$ is defined by:

\begin{equation}
\forall t>0,\quad\mathbf{Q}_1(t)=\begin{bmatrix}\textbf{cos}(\boldsymbol \Omega t) & \boldsymbol \Omega^{-1}\,\textbf{sin}(\boldsymbol \Omega t) \\  -\boldsymbol \Omega\,\textbf{sin}(\boldsymbol \Omega t) & \textbf{cos}(\boldsymbol \Omega t)\end{bmatrix}\in\mathbb{R}^{2n\times2n}
\end{equation}
where (... sorry...):
\begin{equation}
\boldsymbol\Omega=\begin{bmatrix} \omega_1 & & \\  & \ddots & \\  & & \omega_n  \end{bmatrix}\in\mathbb{R}^{n\times n},\quad \forall i\in\lbrace 1,\dots, n\rbrace, \omega_i>0
\end{equation}
and the four blocks are diagonal, for example:
\begin{equation}
\mathbf{cos}(\boldsymbol\Omega t)=\begin{bmatrix} \cos(\omega_1t) & & \\  & \ddots & \\  & & \cos(\omega_n t)  \end{bmatrix}\in\mathbb{R}^{n\times n}
\end{equation}

Interesting properties of $\mathbf{Q}_1$ and $\mathbf{Q}_2$:
Obviously, $\mathbf{Q}_2$ is invertible and $\mathbf{Q}_2=\mathbf{Q}_2^{-1}$.
Also, $\det(\mathbf{Q}_1)=1$ ($\omega_i>0$ and for proper $t>0$) and:
\begin{equation}
\mathbf{Q}_1(t)^{-1}=\begin{bmatrix}\textbf{cos}(\boldsymbol \Omega t) & -\boldsymbol \Omega^{-1}\,\textbf{sin}(\boldsymbol \Omega t) \\  \boldsymbol \Omega\,\textbf{sin}(\boldsymbol \Omega t) & \textbf{cos}(\boldsymbol \Omega t)\end{bmatrix}
\end{equation}
The initial equation can therefore also be written as:
\begin{equation}
\text{ker}\left(\mathbf{Q}_2\mathbf{Q}_1(t)-\mathbf{Q}_1(t)^{-1}\mathbf{Q}_2\right)=\text{ker}\left(\mathbf{Q}_2\mathbf{Q}_1(t)\mathbf{Q}_2\mathbf{Q}_1(t)-\mathbf{1}_{2n}\right)
\end{equation}
So another way of solving the problem is to prove that 1 is an eigenvalue of $\mathbf{Q}_2\mathbf{Q}_1(t)\mathbf{Q}_2\mathbf{Q}_1(t)$ with a multiplicity of 2. But I'm not sure this helps...
Any clues would be greatly appreciated.
Answer: Let $$\begin{split}A&=Q_2Q_1-{Q_1}^{-1}Q_2 \\ &=\begin{pmatrix}0&\Omega ^{-1}\sin(\Omega t)(I+P^{-1}DP)\\-(P^{-1}DP+I)\Omega\sin(\Omega t)&P^{-1}DP\cos(\Omega t)-\cos(\Omega t)P^{-1}DP\end{pmatrix}\end{split}$$
Then $$\begin{split}\phi(x)&=\pm\det(A-xI)\\
&=\det\bigg[-(P^{-1}DP+I)\sin(\Omega t)^2(I+P^{-1}DP) \\ &+x(P^{-1}DP\cos(\Omega t)-\cos(\Omega t)P^{-1}DP)-x^2I\bigg] \\
&=\det(-U+xV-x^2I) \end{split}$$
$\phi(0)=\det(-U)=0$ (because $I+P^{-1}DP$ is not invertible).
Now
$$\begin{split}\phi'(0)&=-\operatorname{tr}(\operatorname{adjoint}(U)V) \\
&=-\operatorname{tr}\bigg((\operatorname{adjoint}((P^{-1}DP+I)\sin(\Omega t)^2(I+P^{-1}DP)) \\ &\times (P^{-1}DP\cos(\Omega t)-\cos(\Omega t)P^{-1}DP)\bigg)
\end{split}$$
After a change of basis , we may assume $P^{-1}DP=\operatorname{diag}(1,\cdots,1,-1)$, $$S=\operatorname{adjoint}(\sin(\Omega t)^{2})=[s_{i,j}],C=\cos(\Omega t)=[c_{i,j}]$$
Then $\operatorname{adjoint}(U)=2^{2n-2}s_{n,n}E_{n,n}$ and consequently (if $V=[v_{i,j}]$), $$\operatorname{tr}(\operatorname{adjoint}(U)V)=2^{2n-2}s_{n,n}v_{n,n}.$$ Yet $v_{n,n}=-c_{n,n}+c_{n,n}=0$. Thus $\phi'(0)=0$  and $x=0$ is (at least) a double eigenvalue.
We consider the generic case (with respect to $\Omega,P,t$ and not only $t$). To see that, generically, $\dim(\ker(A))$ is exactly $2$, it suffices to give an instance, in dimension $n$, where $A$ is diagonalizable and $0$ is an eigenvalue with exactly the multiplicity $2$. It is not difficult (take $P=I_n,...$) - For a rigorous reasoning, you must use the Zariski's topology-.
Comment: @ anderstood , if you have some other question, then post it on the forum in the form of another question.
Comment: Very interesting, I'd never have found that. I'll enter into details tomorrow. What is $E_{n,n}$? Are you summing over $n$? Funnily enough last night I slept in an inn called... the White Wolf Inn!
Comment: @ anderstood , $E_{i,j}$ is the $n\times n$ matrix, the entries of which are $0$, except the $(i,j)$ entry that is $1$. About your inn, I think that you were in the mountains !
Comment: OK so I read your answer carefully. First of all, thank you and congrats for having found this approach. Something I'm not totally comfortable with: "after a change of basis, we may assume ...". I'm not sure if this is valid, because if we had changed the basis before, we would not have found something so "simple". Also, this does not change anything to the proof but I think $\text{adjoint}(U)=2^{4n-2}...$ instead of $2^{2n-2}$.
Comment: For the reciprocal, I'm lost: how could an example prove that dim(ker($A$)) is no greater than 2, but not prove that is no smaller than 2? (the answer must be in Zariski's topology but I've never heard about it and it is not so clear to me).
Comment: @ anderstood  1. with my change of basis, $P^{-1}DP$ becomes $D$ and $\Omega$ becomes $P\Omega P^{-1}$ ; I can do that because the fact that $\Omega$ is diagonal is useless. I do not see any mistake in my calculation of $adjoint(U)$.  2. The end of my post is not at all a converse. Always $x=0$ is an eigenvalue with multiplicity $\geq 2$. In particular $dim(\ker(A))=1$ or $2$ or more. Moreover, generically, $dim(\ker(A))=2$  because generically $discrim(A-xI,x)$ and $\phi'''(0)$ are not identically $0$.
Comment: In the end of my previous comment, read "$discrim(\det(A-xI),x))$". To show that, it suffices to find an instance of $P,\Omega,t$ satisfying the conditions given in my answer. Using algebraic topology, the conclusion, about genericity follows, but I do not want to write the details.
Comment: 1. Ok, "the fact that $\Omega$ is diagonal is useless" was what I was missing. And your calculation is correct. 2. Sure, I misused the word. Would you agree to continue on the chat later this week? I have some "extensions" to the question.
Comment: I was afraid of flooding SE with the same type of question, but there it is: http://math.stackexchange.com/questions/976987/proof-of-the-conjecture-that-the-kernel-is-of-dimension-2-extended. I did not manage to extend your demonstration because $A$ does not have the same structure with a 0 block.


Non linear curve fitting of a cosine with multiple unknown parameters

Question: I have an equation that I am able to solve with scipy curve fitting when I have good first guess values, however I was hoping to simplify this equation so that my answers are more reliable. The equation is of the following form:
$$
f(x) = p - \frac{1}{a\cdot\bigl(\cos(bx+c)+D\bigr)}
$$
Here $D$ is a known constant, $a,b,c,p$ are unknowns but I have a reasonable guess for what the values are with $p$ always close to $1$.
I am hoping to make the solutions to this equation more robust by some form of linear algebra but I cant find any solution. It seems as though all the variables can work against each other to give multiple different solutions.
Are the techniques to cosine curve fitting that I can try out? Thanks
Answer: Let us say that you have $n$ data points $(x_i,y_i)$ and you want to fit the model
$$y = p - \frac{1}{a\,\bigl(\cos(bx+c)+D\bigr)}$$ which is very highly nonlinear. You need to have good guesses before starting the nonlinear regression.
The first thing I should do is to expand the cosine and write the denominator as
$$\alpha \cos(bx)+\beta \sin(bx)+\gamma$$ with
$$\alpha=a\,\cos (c) \qquad \beta=-a\,\sin(b)\qquad \gamma=a\,D$$
Now, since you know anapproximate value of $p$, rewrite
$$z=\frac 1{p-y}=\alpha\,cos(bx)+\beta\,\sin(bx)+\gamma$$
Now, give $b$ a value; the problem is then simple since it is a linear regression of $z_i=\frac 1{p-y_i}$ as a function of $u_i=\cos(bx_i)$ and $v_i=\sin(bx_i)$. So, for this specific value of $b$ you have the sum of squares $SSQ$. Run different values of $b$ until you see the minimum of $SSQ$. When you have the $b_{\text{opt}}$, you have all parameters and you can go back to
$$y=p-\frac 1{\alpha\,cos(bx)+\beta\,\sin(bx)+\gamma}$$ When done, go back to $(a,b,c,D)$ using basic trigonometric relations.


excel alert for cell that auto changes

Question: Hi could someone help adjust this so the alert message says the value of A2 AND B2.
Private Sub Worksheet_Calculate()
    Dim myRange As Range
    Set myRange = ActiveSheet.Range("F2:F2")
    Dim cell As Range
    For Each cell In myRange
        Evaluate (cell)
        If StrComp(cell, "Yes", vbTextCompare) = 0 Then
            MsgBox Join(Application.WorksheetFunction.Transpose(Range("A1:A10").Value), Chr$(10))
        End If
    Next
End Sub

Comment: sorry i cant find out how to fix it
Answer: I have modified my original post to comply with your better explanation.
Sub Worksheet_Calculate()
    Dim myRange As Range
    Dim Cell As Range

    Set myRange = ActiveSheet.Range("F2:F2")
    For Each Cell In myRange
        Evaluate (Cell)
        If StrComp(Cell, "Yes", vbTextCompare) = 0 Then
            MsgBox "A2 = " & CStr((Cells(2, "A").Value) & vbCr & _
                   "B2 = " & CStr(Cells(2, "B").Value))
        End If
    Next Cell
End Sub

Comment: Thanks for help,  i want the alert message to state the words which are in a2 and b2
Comment: I have modified my original answer to comply with your better explanation.

excel alert for cell that auto changes


"react native pushnotificationIOS "scheduleLocalNotification" firedate object format

Question: Does anyone know the date and time format for the "fireDate" object of the "PushNotificationIOS" method "scheduleLocalNotification"
thanks in advance
Answer: I got the following error message when sending a wrong string to fireDate:
Expected format: YYYY-MM-DD'T'HH:mm:ss.sssZ

If no other format works I suggest the one above, the following code works using moment:
moment().format("YYYY-MM-DDTHH:mm:ss.sssZ")

Comment: Using `Date()`did not work but `moment` trick is better solution.
Answer: If you look here, you can see that the format is NSDate.
This being said, multiple formats work. I have tested all of the formats here and they work like a charm.
var today = new Date();
var date = new Date('December 17, 1995 03:24:00');
var date = new Date('1995-12-17T03:24:00');
var date = new Date(1995, 11, 17);
var date = new Date(1995, 11, 17, 3, 24, 0);

Answer: Old string, but just for the record, moment format for fractional seconds (milliseconds) is caps on the last three s'es ergo moment().format('YYYY-MM-DDTHH:mm:ss.SSSZ')


How to change link in a view depending on state of a certain field

Question: I have a content type called conference, there are two types of conferences; supported and unsupported.
Supported have their own node inside Drupal, unsupported link out to external websites rather than having their own node. Supported also have the same external link.
There is a field selection for this in the conference content type so the user picks whether a conference is supported or unsupported.
Now I have a view of conferences and their title is a link. However I need to check whether each conference is supported or unsupported, as this link will either be a link to the node or a link externally.
Looking for any suggestions on how to achieve this, I'm guessing views PHP would achieve this, but is this the best option?
Answer: You can use the field token of the field which is used to picks whether a conference is supported or unsupported. Then you can link it to a node or external link,
Comment: But I need logic to check the state of this field, and to change the title's link depending on this. So in the case of it being unsupported the token for the href will be [field_unsupported_link] and in the case if it being supported it will simply link to that nodes content page
Comment: You need to use the field token of the of the field which is used to pick whether each conference is supported or unsupported. This will give you the whether a conference is supported or not. Then you can put condition to link it internally to a node or externally
Comment: Ok yes, but how to create this condition in a view?


Castle DynamicProxy: Get unproxied object

Question: I'm using Castle DynamicProxy to add an interceptor to my types.
Now I need to get the underlying base type (NOT the proxy itself).
I found a few hints on SO that suggested to use the ProxyUtil class like this:
object realInstance = ProxyUtil.GetUnproxiedInstance(proxyInstance);

This does not seem to work as
bool isProxy = ProxyUtil.IsProxy(realInstance);

is always true.
I also tried using the following code snippet, which is essentially what ProxyUtil is doing:
var accessor = proxyInstance as IProxyTargetAccessor;
var realInstance = accessor.DynProxyGetTarget();

with the same results, realInstance is still a proxy.
What am I missing here?
Answer: This question is a little old but hopefully my solution (which relies on .NET 4+) will help someone.
Having created a proxy as follows:
ProxyGenerator generator = new ProxyGenerator();
MyClass proxy = generator.CreateClassProxyWithTarget(underlying, new MyInterceptor(this));

I have been able to get the underlying target with the following method:
internal static TType UnwrapProxy<TType>(TType proxy)
{
    if (!ProxyUtil.IsProxy(proxy))
        return proxy;

    try
    {
        dynamic dynamicProxy = proxy;
        return dynamicProxy.__target;
    }
    catch (RuntimeBinderException)
    {
        return proxy;
    }
}

It relies on the internal implementation of Castle - i.e. that the generated proxy has a __target member. It is nice and self contained though and backed up with a unit test or two, we should catch any changes should a later version of Castle break this. This is using v220.127.116.11 of Castle.
Comment: As of writing - i.e. 14 April 2019 - the code in this answer results in `'Castle.Proxies.IXeroServiceProxy.__target' is inaccessible due to its protection level`. I won't downvote as it is possible that it may have worked back then with a different version of both `dynamic` implementation as well as class `DynamicProxy`.
Comment: `dynamic` for the win here. Beats trying to reflect into it. That was epic fail.
Answer: If you don't have an invocation object available, or if you observe 'Castle.Proxies.IXeroServiceProxy.__target' is inaccessible due to its protection level when trying @s1mm0t's answer, you can try the following code which uses reflection instead of dynamic:
public static T UnwrapProxy<T>(T proxy) {
   if(!ProxyUtil.IsProxy(proxy)) {
      return proxy;
   }
   try {
      const System.Reflection.BindingFlags flags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance;
      var proxyType = proxy.GetType();
      var instanceField = proxyType.GetField("__target", flags);
      var fieldValue = instanceField.GetValue(proxy);
      return (T) fieldValue;
   }
   catch(RuntimeBinderException) {
      return proxy;
   }
}

Answer: I simply use an interface like this
public interface IMarker
{
  Type ActualType { get; }
}

add it to my proxy and intercept it:
public class MyInterceptor<T> : IInterceptor

...
if (invocation.Method.DeclaringType == typeof(IMarker))
{
  if (invocation.Method.Name.Equals("get_ActualType"))
  {
    invocation.ReturnValue = typeof(T);
    return;
  }
}

So in the end i only have to check
if( obj is IMarker )
  Type t = (obj as IMarker).ActualType`

Maybe there are better options to do it, but it works and keeps my code clean from castle references.
Hope this helps.
Answer: If you are building an inheritance-based proxy (generator.CreateClassProxy<MyClass>()) the proxy is the target.
Comment: I'm using `CreateClassProxyWithTarget(instance, interceptor)` to create the proxy.
The problem is with NHibernate failing because it thinks it should map the proxy, and not the target.


Hibernate ManyToOne association in a Spring Form

Question: I have two entities with a @ManyToOne association, and a form which adds a product. Everything is working fine except for the category and the manufacturer attribute. Any Idea ?
Here is the Product class :
@Entity
public class Product implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@NotEmpty(message = "Le champ nom ne peut être vide")
private String name;

@NotEmpty(message = "Le champ description ne peut être vide")
private String description;

@Min(value = 0, message = "Le prix du produit ne peux pas être négatif")
@NotNull(message = "Le champ prix ne peut pas être vide")
private Double price;

@ManyToOne
private Category category;

@Min(value = 0, message = "Le stock du produit ne peut pas être négatif")
@NotNull(message = "Le champ stock ne peut pas être vide")
private Long stock;

@ManyToOne
private Manufacturer manufacturer;

@Transient
private MultipartFile image;

Here is the Category class :
@Entity
public class Category {
@Id
private Long id;

@NotEmpty(message = "Le champ nom est vide.")
private String name;

private String description;
private String picture;

Here is the controller :
@RequestMapping(value = "admin/inventaire/ajout", method = RequestMethod.POST)
public String ajoutProduitPost(@Valid @ModelAttribute("product") Product product,
        BindingResult result, HttpServletRequest request) {

    if (result.hasErrors()) {
        return "addProduct";
    }

    productDao.addProduct(product);

    MultipartFile productImage = product.getImage();
    String contextPath = context.getRealPath("/");

    Path path = Paths.get(contextPath + "/WEB-INF/resources/images/product   /"+product.getId()+".png");

    if (productImage != null && !productImage.isEmpty()) {
        try {
            productImage.transferTo(new File(path.toString()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Product image saving failed", e);
        }
    }

    return "redirect:/admin/inventaire";
}

And finally the JSP :
    <%@include file="/WEB-INF/views/template/header.jsp" %>
<%@page contentType="text/html" pageEncoding="UTF-8" language="java"%>

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

Ajout d'un nouveau produit

        <form:form action="${pageContext.request.contextPath}/admin/inventaire/ajout" method="post"
                   modelAttribute="product" enctype="multipart/form-data">

                Name
                <form:input path="name" id="productName" class="form-control "/> <form:errors path="name" cssStyle="color:#ff0000;"/>

                Description
                <form:textarea path = "description" id="description" class ="form-control"/> <form:errors path="description" cssStyle="color:#ff0000;"/>

                Quantité en stock
                <form:input path="stock" id="stock" class="form-control"/> <form:errors path="stock" cssStyle="color:#ff0000;"/>

                Prix
                <form:input path="price" id="price" class="form-control"/> <form:errors path="price" cssStyle="color:#ff0000;"/>

                Catégorie
                <form:select path="category">
                    <form:option value="-" label="--Please Select"/>
                    <form:options items="${categoryList}" itemValue="id" itemLabel="name"/>
                </form:select>

                Image
                <form:input id="image" path = "image" type="file" class="form:input-large"/>

            <input type="submit" value="Envoyer" class="btn btn-default">
            <a href="<c:url value="/admin/inventaire" />" class="btn btn-default">Annuler

        </form:form>

    <%@include file="/WEB-INF/views/template/footer.jsp" %>

I think the problem is that the form sends the id of the category to the controller, but it expects the object Category instead. I can't find a solution around it.
Answer: first of all you need to use @JoinColumn for mapping of @ManyToOne, for example you can use refer code :
@ManyToOne
@JoinColumn(name = "id")
private Category category;

then after get the category id into controller and find the category by id. now you have object of Category Entity, set the category Object into Product. and use cascade = CascadeType.ALL, fetch = FetchType.LAZY onto  ManyToOne relation.
Answer: <form:select path="category.id">

As pointed by Mayank Add @JoinColumn(name="mapped_table_column_id") annotation to both Category and Manufacturer
Comment: That did it. Thanks!


Custom theme function for language switcher block

Question: I have a problem with theme hook suggestion for language switcher block.
I just need to place theme_links__locale_block() in MYMODULE.module file
My module:
<code>/**
 * Implements hook_theme()
 */
function MYMODULE_theme() {
  return array(
    'MYMODULE_links' => array(
        'variables' => array(
            'links'      => NULL,
            'attributes' => NULL,
            'heading'    => NULL
        )
    )
  );
}

/**
 * It doesn't work...
 */
function theme_MYMODULE__locale_block(&$variables) {
    // custom function code ...
}
</code>
It works in my template.php file:
<code>function MYTHEME_links__locale_block(&$variables) {
    // custom function code ...
}
</code>
I don't want to leave it in template.php because it is a part of my module.
Any help would be appreciated.
Comment: Isn't it answered here: http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_theme/7#comment-14989 ?
Comment: I don't see any answer for this question there. No idea what the node have to do with theme hook suggestion. I think the problem is with the hook __locale_block, but have no idea what exactly :(
Comment: Could you prepare [complete example](http://sscce.org/)?
Answer: SOLVED!
adding hook_theme_registry_alter(&$theme_registry) was the answer.
<code>/**
 * Implements hook_theme_registry_alter
 *
 */
function MYMODULE_theme_registry_alter(&$theme_registry) {

  $mod_path = drupal_get_path('module', 'MYMODULE');

  if (isset($theme_registry['links'])){
    $theme_registry['links__locale_block']['theme path'] = $mod_path;
    $theme_registry['links__locale_block']['function'] = 'MYMODULE_links';
  }
}
</code>


Prove $\sec^2\frac{\pi}{7}+\sec^2\frac{2\pi}{7}+\sec^2\frac{3\pi}{7}=24$ using the roots of a polynomial

Question: I have to

prove $\sec^2\frac{\pi}{7}+\sec^2\frac{2\pi}{7}+\sec^2\frac{3\pi}{7}=24$ by using the roots of the polynomial $x^3-21x^2+35x-7=0$

I tried to factor the polynomial but it didn't work and later found it cannot factorize with rationals. and I saw some similar problems in StackExchange. But the answers are very complex to me. I cannot use Euler's complex number formula since it's not in the syllabus. I do not want the exact answer but guidance to the answer.
Comment: https://math.stackexchange.com/questions/175736/evaluate-tan220-circ-tan240-circ-tan280-circ https://math.stackexchange.com/questions/638874/factor-z7-1-into-linear-and-quadratic-factors-and-prove-that-cos-pi-7-c
Comment: See also: https://math.stackexchange.com/questions/544228/finite-sum-sum-limits-k-1m-1-frac1-sin2-frack-pim/1083137#1083137  and https://math.stackexchange.com/questions/951522/trig-sum-tan-21-circ-tan-22-circ-tan2-89-circ
Answer: let $t=\tan(\theta)$, we have
\begin{eqnarray*}
\tan(7 \theta) =\frac{ 7t-35t^3+21t^5-t^7}{1-21t^2+35t^4-7t^6}.
\end{eqnarray*}
Set $\tan(7 \theta) =0$ then the polynomial
\begin{eqnarray*}
 7t-35t^3+21t^5-t^7=0
\end{eqnarray*}
has roots $t=0, \tan( \pi/7), \cdots ,\tan( 6 \pi/7)$. So
\begin{eqnarray*}
x^3-21x^2+35x-7=0
\end{eqnarray*}
has roots $x= \tan^2(\pi/7),\tan^2(2\pi/7),\tan^2(3\pi/7)$. Now let $y=x+1$.


What is conflict in NSManagedObject and what's the different between some of the merge Policy?

Question: NSMergeByPropertyObjectTrumpMergePolicy and NSOverwriteMergePolicy is the same in one thing. The property overwrite the one in the store.
So what's the different between them? In all cases I can think of, whether the one in persistent store have changed or not, the property override the persistent store.
Also what is conflict?
I thought conflict simply means that the data are different. Does this mean that core data is originally designed that once data is written it cannot be updated?
If conflict is something different than mere "data different", then what's the difference between NSOverwriteMergePolicy and NSErrorMergePolicy?
In both cases, mere data difference is not a conflict anyway and hence there can't be a conflict.
Answer:
Does this mean that core data is originally designed that once data is written it cannot be updated?

No. It wouldn't be much use if that was the case, would it?

Also what is conflict?

In Core Data a conflict can occur when you have more than one managed object context (MOC) accessing the same data store. This is common in multithreaded apps. Each MOC can save changes independently of the other. But you want to keep a consistent view of the data across all threads, so it's possible to be notified that changes have been saved on one MOC and merge those changes into a different context. That keeps the contexts in sync.
But what if you try to merge changes into a MOC, and it has different unsaved changes to the same data? Like, both MOCs changed the same attribute on the same instance, and they changed it to different values. This is when a conflict occurs. If you try to merge changes, the results depend on the MOC's merge policy. By default it uses NSErrorMergePolicy, which means that the merge fails and your code needs to sort out and resolve the conflict somehow. There are several built-in merge policies that apply different automatic resolution schemes to the conflict.
The four built in resolution schemes give priority to either the changes on disk or to changes in memory. They differ also in how they handle non-conflicting in-memory changes. For example, NSMergeByPropertyStoreTrumpMergePolicy updates any conflicting changes in memory to match the changes from the other MOC, but leaves non-conflicting changes in place. NSRollbackMergePolicy differs in that it completely discards in-memory changes, even if they don't conflict with new changes from the other MOC. You can also create your own merge policies if none of the built-in schemes seems right.

In both cases, mere data difference is not a conflict anyway and hence there can't be a conflict.

There most certainly can be conflicts. It's a very common scenario.
Comment: So the key here is that mere data difference is not a conflict. It's unsaved data difference on the same object that becomes a conflict.
Comment: Right, if one of the managed object contexts has no changes for an attribute, a change from a different MOC isn't a conflict-- it's just new information.


Different seven-digit numbers could Sid have meant to type

Question:
Sid intended to type a seven-digit number, but the two 3's he meant to
  type did not appear. What appeared instead was the five-digit number
  $52115$. How many different seven-digit numbers could Sid have meant to type?

First time, I attempted this problem as follows-
I considered, there are 12 places available for two 3's (as they can appear together)
_ _ 5 _ _ 2 _ _ 1 _ _ 1 _ _ 5 _ _
So, we can select 2 places from 12 places in ${12\choose 2}$ = $66$ ways.
But, I found the correct approach is simply choosing 2 places from available 7 place in ${7\choose 2}$ = 21 ways. However, I can't find my mistake in previous one. Can anyone explain what am I missing?
Answer: Consider the following possibilities:
_ 3 5 _ _ 2 _ _ 1 _ _ 1_ _ 5 _ 3
_ 3 5 _ _ 2 _ _ 1 _ _ 1_ _ 5 3 _
3 _ 5 _ _ 2 _ _ 1 _ _ 1_ _ 5 _ 3
3 _ 5 _ _ 2 _ _ 1 _ _ 1_ _ 5 3 _
All of these would give the same result of 3521153, but are counted separately by your first method.
Answer: An intuitive explanation is:
Consider 6 _ 5 _ _ 2 _ _ 1 _ _ 1 _ _ 5 _ _, we have $6$ places to put the next $6$:
6 6 5 _ _ 2 _ _ 1 _ _ 1 _ _ 5 _ _
6 _ 5 6 _ 2 _ _ 1 _ _ 1 _ _ 5 _ _
6 _ 5 _ _ 2 6 _ 1 _ _ 1 _ _ 5 _ _
6 _ 5 _ _ 2 _ _ 1 6 _ 1 _ _ 5 _ _
6 _ 5 _ _ 2 _ _ 1 _ _ 1 6 _ 5 _ _
6 _ 5 _ _ 2 _ _ 1 _ _ 1 _ _ 5 6 _
Continuing:
_ _ 5 6 _ 2 _ _ 1 _ _ 1 _ _ 5 _ _ gives $5$ (different from before) places
_ _ 5 _ _ 2 6 _ 1 _ _ 1 _ _ 5 _ _ gives $4$
_ _ 5 _ _ 2 _ _ 1 6 _ 1 _ _ 5 _ _ gives $3$
_ _ 5 _ _ 2 _ _ 1 _ _ 1 6 _ 5 _ _ gives $2$
_ _ 5 _ _ 2 _ _ 1 _ _ 1 _ _ 5 6 _ gives $1$
Adding these, $6+5+4+3+2+1=21$.
Answer: The answer 21 is got as follows: If the threes are together then we have 6 numbers (choosing one of the 6 gaps in 52115. If the threes are not together, we need to pick two places out of 6 and this can be done in $\binom{6}{2} = 15$ ways. Thus a total of 21 numbers.