exponentially increasing startup time (Spring initialization) on every added DAO interface

Question: During startup, Spring warn-logging shows errors on creating e.g.
"bean with name 'userRepositoryInterface' ... Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required"
During the next few minutes this is repeated many times for each RepositoryInterface, but in the end the the problem is solved and the application works ok.
But the startup time is unacceptable. Besides, when I added a new RepositoryInterface, the startup time expanded to 20 minutes until the server (weblogic 12c) ran out of memory.
The implementing classes of these RepositoryInterfaces are made by Spring/Mybatis (spring 4.1.3, mybatis 3.2.8 and mybatis-spring 1.2.2) that scans (xml) mapper-files to do this.
The repository (DAO) interfaces are autowired in the service-classes calling them, e.g.
@Autowired
private UserRepositoryInterface repository;

The repository interfaces are anotated with @Repository
I have a @Configuration and @MapperScan annotated PersistenceConfigurer that contains two @Bean methods:

DataSource dataSource()
SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource)

The dataSource and sqlSessionFactory are not called until the end of the startup process, that seems to be the problem.
I tried to change that by adding @Order(0) to the PersistenceConfigurer, but this had no effect.   Moving the two Beans to other Configuration classes also had no positive effect.
For Spring I use Java configuration, no xml.
In response to comments, here is the whole PersistenceConfigurer:
package org.xx.xxxxxxx.configuration;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jndi.JndiTemplate;

import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 * This class configures the application's persistence layer.
 */
@Configuration
@MapperScan(basePackages = "org.xx.xxxxxxx.repository")
public class PersistenceConfigurer {
    static Logger LOGGER = LogManager.getLogger(PersistenceConfigurer.class);
    @Value("${jdbc.datasource}")
    private String jdbcDatasource;   // in jdbc.properties: jdbc.datasource=jdbc/OurDS

@Value("classpath*:sqlmapper/*.xml")
private Resource[] mapperFiles;

@Value("classpath:mybatisConfig.xml")
private Resource myBatisConfig;

/**
 * @return The configured data source.
 */
@Bean
public DataSource dataSource() {
    JndiTemplate jndiTemplate = new JndiTemplate();
    DataSource dataSource = null;
    LOGGER.debug("Configuring datasource creating datasource with jndiname " + jdbcDatasource);
    try {
        // this works for weblogic,  but not for Tomcat
        dataSource = (DataSource) jndiTemplate.lookup(jdbcDatasource);
        LOGGER.debug("Configuring datasource successfully created datasource " + dataSource);
    } catch (NamingException e) {
        LOGGER.error("Configuring datasource error creating datasource NamingException " + jdbcDatasource);

    } catch (Exception e) {
        LOGGER.error("Configuring datasource error creating datasource " + jdbcDatasource);
        e.printStackTrace();
    }
    return dataSource;
}

/**
 * @param dataSource A configured data source.
 * @return The SQL session factory bean for data management.
 */
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
    LOGGER.debug("sqlSessionFactory making SqlSessionFactoryBean with datasource " + dataSource);
    SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
    factoryBean.setDataSource(dataSource);
    factoryBean.setMapperLocations(mapperFiles);
    factoryBean.setConfigLocation(myBatisConfig);
    return factoryBean;
    }
}

Comment: How you are creating dataSource JNDI lookup or create connection pool locally?
Comment: JNDI lookup. The application can be deployed for different "owners". The weblogic server administrator installs the datasource files and the wars.
Comment: hmm...... Then that is the problem, its worth looking once the spring configuration file. Can you post your configuration file and weblogic JNDI name. I had similar issue....... it was miss configuration of JNDI
Comment: If you mean Spring configuration file: we use Java configuration only. Or do you mean a datasource-file?  In the PersistenceConfigurer there is:     @Value("${jdbc.datasource}")
    private String jdbcDatasource;   // in jdbc.properties: jdbc.datasource=jdbc/OurDS. That seems to be found alright, no NamingException or other Exception.
Comment: Yes Java Configuration
Comment: I added the PersistenceConfigurer code above
Comment: For completeness: I temporarily changed the code of the PersistenceConfigurer: no JNDI lookup/datasourcefile but getting data like userid and password from the jdbc.properties file. The effect is the same.
Comment: I don't use MyBatis but it looks like you added the mapper data twice (once with `@MapperScan` and once with `factoryBean.setMapperLocations(mapperFiles)`. Is that a problem?
Comment: No, the two configurations are necessary, one points to the RepositorInterface Java classses, the other to the queries in mapperfiles. Removing the first one makes deployment impossible, removing the second one makes deployment faster, but leads to errors runtime: the queries are not found/performed.
Comment: where are you importing propertysource(properties file) are you importing it other configuration class?
Comment: application.properties (only item is applicationPath), jdbc.properties and 2 message.properties.
All referred to in the `@Configuration` annotated `WebMvcConfigurerAdapter`, the message-files in its `@Bean` annotated `MessageSource`, the other two in its `@Bean` annotated `PropertySourcesPlaceholderConfigurer`.
Comment: You could try injecting Properties to PersistenceConfigurer directly, I believe since webMvc is child context of application context. PersistenceConfigurer might not get these properties
Comment: We tried hardcoding the properties in the PersistenceConfigurer. It had no effect.
Comment: But it had effect once we also changed 'SqlSessionFactoryBean' to 'SqlSessionFactory'. This worked only in combination of hardcoding the properties. We try to get around that too, trying to get the PropertySourcesPlaceholderConfigurer to be made earlier. To be continued...
Answer: A colleague of mine found the main solution: not to return SqlSessionFactoryBean but SqlSessionFactory.
Before this solution the startup-time depended on the number of RepositoryInterfaces:
5 RepositoryInterfaces: 12 seconds, 6: > 80 seconds; 7: 9 minutes ending in memory problems.
After, it is always 9 seconds.
This solution did not work immediately, because thanks to the fix, now the creation is so early, that it precedes the PropertySourcesPlaceholderConfigurer creation declared in the WebMvcConfigurerAdapter.
So we put the resolving of the properties needed directly in the PersistenceConfigurer. Thank you, Karthik for this suggestion.
The changed code in the PersistenceConfigurer:
added imports:
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
3 changed private variables (now all 3 are simple Strings, without @Value annotation) :
private String jdbcDatasource = "jdbc/OurDS";  // moved away from jdbc.properties (was only property left there)

private String mapperFilesLocation = "classpath*:sqlmapper/*.xml";

private String myBatisConfigLocation = "classpath:mybatisConfig.xml";

One changed method, the main change is the returned object. Three lines for the property-resolving are added.
/**
 * @param dataSource A configured data source.
 * @return The SQL session factory (org.apache.ibatis.session.defaults.DefaultSqlSessionFactory).
 * @throws Exception on sqlSessionFactoryBean.getObject(), IOException on resolver.getResources
 */
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) {
    LOGGER.debug("sqlSessionFactory making SqlSessionFactoryBean with datasource " + dataSource);
    SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
    factoryBean.setDataSource(dataSource);
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource[] mapperFiles = resolver.getResources(mapperFilesLocation);
    Resource myBatisConfig = resolver.getResource(myBatisConfigLocation);
    factoryBean.setMapperLocations(mapperFiles);
    factoryBean.setConfigLocation(myBatisConfig);
    return factoryBean.getObject();
}


Power calculation (a posteriori) of a cohort study - R software

Question: Does anyone know if there's any R library to calculate the power of a cohort study with n=9511
Reference: 50 year trends in atrial fibrillation prevalence, incidence, risk
factors, and mortality in the Framingham Heart Study: a cohort study, Lancet 2015
Answer: More details concerning your question would be beneficial.
Anyway, there are many suitable packages in R, just look at the CRAN Task View on Clinical Trials.
For instance, you can peruse the following pacakges: pwr, samplesize, and TrialSize.


Unusual way to define a class of functions?

Question: I am working on a problem and I came to a point where the problem has to be considered within a class of functions. But this class cannot be defined just in terms of the properties of each individual function in this class. It has to be defined in terms of the properties of arbitrary two functions in this class.
Let me give you an example (below $m$ is known fixed integer). Let $\mathcal{F}$ be the class of functions defined on $[0,1]$ with the following properties:

Any $F \in \mathcal{F}$ is non-negative and is (weakly) increasing on $[0,1]$.
Any $F \in \mathcal{F}$ is differentiable on $[0,1]$. Moreover, $F'$ is absolutely continuous on $[0,1]$.
$F'(1) > 0$ for any $F \in \mathcal{F}$.
For any $F_1, F_2 \in \mathcal{F}$, if $F_1$ and $F_2$ are not identical, then for the derivatives of these functions it holds that either a) $F'_1(s) (F'_1(1))^{\frac{1}{m}}> F'_2(s) (F'_2(1))^{\frac{1}{m}}$ in a small right side neighbourhood of $0$, or b) $F'_1(s) (F'_1(1))^{\frac{1}{m}}< F'_2(s) (F'_2(1))^{\frac{1}{m}}$ in a small right side neighbourhood of $0$.
For any $F_1, F_2 \in \mathcal{F}$, it holds that if $F'_1(s) (F'_1(1))^{\frac{1}{m}}> F'_2(s) (F'_2(1))^{\frac{1}{m}}$ in a small right side neighbourhood of $0$, then $\frac{F''_1(s)}{F'_1(1)} < \frac{F''_2(s)}{F'_2(1)}$ a.e. in a small left side neighborhood of 1.

My question is: How unusual is it to define sets or classes by describing the properties of any two components in this set rather than just describing the properties of each individual component in the set. Maybe somebody knows examples from other fields where such definitions can be found?
Answer: To answer your question: in the several decades that I've been reading math papers, I haven't ever seen definitions like this that I can recall. My reading's mostly been in topology, however, so I can't speak to other areas of mathematics.
But there's probably a good reason I haven't seen it:
When you define a class this way, it may well be empty, or there may be two mutually exclusive solution sets.
Let me give an example: Suppose I define $G$ to be "the class of functions from the reals to the nonzero reals with the property that if $f$ and $g$ are in the class, then there's a positive real number $c$ with $f = cg$."
Now that's a silly definition, but consider
(a) the set of all constant functions from $\mathbb R$ to $\mathbb R^{+}$, and
(b) the set of all positive multiples of $f(x) = e^x$.
These classes each satisfy my definition of $G$, but are disjoint.
So: you have a job ahead of you. You need to prove that your characterization in fact describes only one possible class, and (probably) that it's nonempty.
Just using the word "the", as in "the class of functions such that..." is already assuming (or at least suggesting very strongly) that the definition is meant to characterize something unique, and this at the very least requires a proof. If you're thinking to yourself "Most definitions I see aren't usually followed by proofs," you're right. There's a reason for that -- it tends to be a bad expository style.
A better approach might be to say that a class has "Property J" if the following 5 things hold. You can then prove statements like "this class has property J" or "that class does not have property J", and the proofs are then associated to theorems rather than to definitions, and your reader will understand, from the statement of the theorem, all the things that need to be proved (and the possibility that there might be multiple sets with property J).
Comment: Thanks! The problem I am considering is quite difficult and I can reach some conclusions only in a class of functions described above. My class  is definitely not empty but it is true that there are many mutually exclusive classes of functions that satisfy the described conditions. In fact, the set of all functions I can potentially be interested in can be split into mutually exclusive classes that satisfy described conditions.
Comment: I think there is some flavour of pre-order to my definition of class but not sure how to make use of it.
Comment: Well...I'm not sure either. In general, I think that "definitions" should uniquely characterize things. We don't talk about "the span of these three vectors" and mean two different things, after all. When you write "Let F be **the** class of functions ..." you're implicitly already misleading your reader.
Comment: I agree that it is better to describe it as a property rather than a definition, and also use "a class", not "the class".


One sample - why can't $\sigma^2=0$?

Question: The assumption is that
$Y_1,...,Y_n$ are independent and $Y_i \sim N(\mu,\sigma^2)$. The unknown parameters are $(\mu,\sigma^2) \in \mathbb R \times(0,\infty) $.
Question: Why can't variance be 0? meaning: $\sigma^2 =0$.
Kind regards,
Comment: If the variance was 0, then every $Y_i$ would just be equal to $\mu$, so there would be no need to comment on the distribution anyway.
Comment: The 'normal distribution with $\sigma^2 = 0$' sometimes refers to a distribution with point mass $1$ on $\mu$ and is called a 'degenerate normal'. It differs completely from 'real' normal distributions with $\sigma^2 > 0$ as it does not have most of it's 'pretty' properties.
Comment: Look at the PDF of a normal distribution. Do you see any issues with $\sigma=0$, a fraction, perhaps?
Comment: Not sure you've fully grasped the point - the $y_i$ are all equal to the same number, $\mu$.  All you need is an assignment;`y <- rep(mu,n)` in R creates a vector of length `n` with all values equal to `mu`.
Comment: Oh, then it will be just get a histogram with one bar. What will interpretation of this be? A distribution with only one possible value? So a binomial distribution?
Comment: So every number $y_i$ which comes of from $Y_i$ is the same, right? Does this trivial distribution not have a name? Maybe the trivial distribution?
Comment: Alright. Is it possible to simulate in R?
Comment: The degenerate one?
Comment: Alright. Another thing: Just because alle the $y_i$ is the same it does not mean that all the $Y_i$ is the same?
Comment: All $Y_i$ (Random variables) have that same normal distribution, so it doesn't matter what the $y_i$ (realizations of the random variables, so numbers, draws from $N(\mu,\sigma^2)$ if that works for you), are. The $Y_i$ al have the same distribution.
Answer: In normal distribution
$$E(Y_i -\mu)^2=\sigma^2$$
so if $\sigma^2\rightarrow 0^+$ so $$E(Y_i -\mu)^2\rightarrow 0^+$$ in hence
$$P(Y_i=\mu) \rightarrow 1$$ so $Y_i$ are degenerate random variable in $\mu$. When variance equal 0 so the distribution is a degenerate  one.
 R code, simulation
 sigma<-c(.1,.01,.001,.0001,.00001)
 n<-10000
 mat<-matrix(0,ncol=n,nrow=length(sigma))
 for( i in 1:length(sigma)){
 set.seed(i)
 mat[i,]<-rnorm(n,0,sigma[i])
 }

 epsilon<-.01
 > length(which(abs(mat[1,])>epsilon))/n
 [1] 0.9185
 > length(which(abs(mat[2,])>epsilon))/n
 [1] 0.3168
 > length(which(abs(mat[3,])>epsilon))/n
 [1] 0
 > length(which(abs(mat[4,])>epsilon))/n
 [1] 0
 > length(which(abs(mat[5,])>epsilon))/n
 [1] 0

if you look at density of normal, at point $x=\mu$
$$f(\mu)=\frac{1}{\sqrt{2\pi \sigma^2}}$$ by  $\sigma \rightarrow 0^+$
$$f(\mu) \rightarrow \infty$$. on the other hand density at point $x=\mu$ is infinity . Other point be zero
  dnorm(0,0,0)
  [1] Inf
  > dnorm(1,0,0)
  [1] 0

at last note $\sigma^2$ can not be zero!since $f(x)$ is not defined at $\sigma^2=0$. just we can $\sigma^2 \rightarrow 0^+$.   we can calculate limiting distribution when  $\sigma^2 \rightarrow 0^+$. if $\sigma \rightarrow 0^+$ , the limiting distribution is degenerate distribution , and so it is not normal!. normal is continues and degenerate is discrete. So you have not a normal distribution with zero variance.
Comment: What do you achieve by the last line in the last block of R code? dorm(1,0,0)? Why look at x=1?
Comment: How do you calculate: $$E\left(Y_{i}-\mu\right)^{2}=\sigma^{2}$$
Comment: @Xenusi In that case, I used $dnorm(1,0,0)$ $\mu=0$ $\sigma =0$, I want to show density at any point except $0$ is zero. so I choose one point $1$.
Comment: $E\left(Y_{i}-\mu\right)^{2}=\sigma^{2}$, This is definition of variance ,https://en.wikipedia.org/wiki/Variance#Definition, and in normal distribution mean equals $\mu$ and variance equal $\sigma^2$ https://en.wikipedia.org/wiki/Normal_distribution
Answer: You say in your question that the distributional form is an assumption (and therefore so is the allowable set of parameter values), so it is really up to you what assumption you wish to make.  It is possible to extend the family of normal distributions to include the case where $\sigma=0$, and in this case the distribution degenerates to a point-mass distribution on $\mu$.$^\dagger$  In answer to your follow up question in the comments, yes, it is possible to simulate this in R, and the standard commands for the norm distribution accomodate this case.
#Example of simulations from normal distribution with zero variance
mu    <- 10;
sigma <- 0;
rnorm(20, mu, sigma);

[1] 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10

There is no particular reason that you have to exclude the possibility that $\sigma = 0$ from your analysis.  Obviously if you exclude this case by assumption, then by assumption this outcome cannot hold.  However, you can certainly include that case as an allowable distribution in the analysis, in which case you are looking at a broader version of the family of normal distributions that includes this point-mass distribution.

$^\dagger$ It is a matter of convention whether or not the point-mass distribution is considered part of the family of normal distributions.  Most texts exclude it so as to focus on the continuous distributions, and retain certain general properties that don't hold with the inclusion of this case.  Nevertheless, it certainly would not be unreasonable to include it.  Whether or not you consider the point-mass distribution to be part of the "family of normal distributions", it is useful to include it in analysis for practical purposes, to ensure that the parameter space is closed.  Having a closed parameter space is useful for various reasons, including the fact that it ensures that in the case where you have observed data $y_1=\cdots=y_n$, your estimator $\hat{\sigma} = 0$ is in the parameter space.
Comment: Reminds me of the Dilbert 9999 cartoon from 10/25/2001.

One sample - why can't $\sigma^2=0$?


Is it possible to use IIS 7 Application Pool Identities on a 2008 Domain Controller

Question: So, let me put the disclaimer in first: I wouldn't typically piggy-back IIS on a domain controller, but that's what I've got and I can't change that in this instance.
I've got a WCF web service I need to host here. I'd like to be able to use an application pool identity from IIS to grant filesystem permissions as well as Launch and Activation Permissions in component services. I'm not able to find the account when I browse for it by trying to select "IIS AppPool\DefaultAppPool".
Does anyone know if this is even possible on a 2008R2 domain controller?
Answer: Granting permissions to Application Pool Identity's via the UI on Windows 2008R2 can be a bit prone to not working now and again, but can be achieved using a couple of command line tools.
NTFS Permissions:
Use the ICACLS command line tool to set NTFS permissions:
icacls c:\wwwroot /grant "IIS AppPool\DefaultAppPool":(CI)(OI)(M)

The above configures the DefaultAppPool identity to have Modify permissions on c:\wwwroot with File and Folder inheritance. In the UI it looks like:

and under the permissions Advanced UI:

DCOM Launch and Activation and Access Permissions:
Again, the UI can be a bit hinky here when it comes to IIS AppPool\<ident> accounts and there's no built-in command line tool to configure Launch and Activation Permissions and Access Permissions. You could try setting these values in the registry but unless you know how to create a serialised ACL for LaunchPermission and AccessPermission it's going to be hard going.
All is not lost though. There's a tool called dcomperm.exe which is included as a sample project in the Microsoft Windows SDK for Windows 7 and .NET Framework 4.
This chap has written about it here:

Another step closer to the 100% scripted SharePoint installation with DcomPerm.exe

You can try and build it yourself or download a prebuilt binary from his Microsoft Live SkyDrive.
To use dcomperm.exe it you'll need to know the AppID of your DCOM app. You can do this by locating it in the General tab of your application's DCOM configuration properties. For example, I've picked the IIS CertObj library as a working example.:

You can place your cursor in the Application ID field and select the whole field, make sure you include the curly braces as well.
Next open a command line prompt (running as Administrator). To grant your application pool identity Local Launch and Local Activation permissions you would execute:
DComPerm.exe -al {62B8CCBE-5A45-4372-8C4A-6A87DD3EDD60} set "IIS AppPool\DefaultAppPool" permit level:ll,la

Where:

-al = Modify or list the launch and activation permission
{62B8CCBE-5A45-4372-8C4A-6A87DD3EDD60} = the App ID we copied from the DCOMCNFG UI
set "IIS AppPool\DefaultAppPool" = set this identity
permit = set the permit flag
ll = Local Launch
la = Local Activation

This looks like the following in the UI:
Comment: This should've been marked as an answer.
@Kev: Just curious why does `icacls` can do what Windows Explorer can't?
Comment: @c00000fd - sadly won't happen, OP asked his question then never re-appeared to follow up. WRT to ICACLS, I've no idea why the UI sometimes doesn't work. We experienced this on some servers prior to rolling out SP1, after SP1 the GUI seemed to work.
Answer: It seems that if you are running a domain functional level earlier than 2008, the built-in IIS accounts cannot be resolved from the GUI.
Either raise the domain functional level to at least 2008, or try running the JScript provided by Microsoft in KB946139
Also note the running web applications on domain controllers is NOT recommended, here's a few reasons: http://blogs.technet.com/b/abizerh/archive/2009/07/16/should-iis-be-installed-on-domain-controller.aspx
This is concerning issues with IIS 6/Windows 2k3, but some of it still holds true, eg. the DCPROMO issue
Comment: Even at both domain and forest functional levels of "Windows Server 2008 R2" you can't resolve the ApplicationPoolIdentity accounts in the UI i.e. the ones that are synthesised pool identities. The built-in's resolve fine, but not pool identities. I was able to repro this on one of our lab 2008R2 DC's running at "Windows Server 2008 R2" and this server was built as such.
Comment: Just because you can't list them in the GUI doesn't mean you can't resolve them by name. Have you tried it in a 2003 environment?
Comment: There is no such thing as an [Application Pool Identity](http://learn.iis.net/page.aspx/624/application-pool-identities/) on Windows 2003/IIS6. They are not the same as the built-ins such as NETWORK SERVICE. The accounts are named after the IIS7 application pool and to specify the you would prefix with `IIS AppPool\`, they are "virtual" accounts synthesised for the pool.
Comment: Not a 2003 server, a 2003 environment, as in "on a 2008 or 2008r2 DC in a domain with a 2003 functional level"
Comment: I amended my previous comment. What I'm saying is that even at full Windows 2008R2 functional level, these accounts can't be resolved in the GUI. They are a type of account that are particular to IIS7's security architecture and at times Windows 2008R2 is prone to not resolving them in the UI (even on standalone servers not members of AD), hence you need to use ICACLS and command line tools to get around this.
Comment: It's not about "listing" them it's about resolving them i.e. even if you do type in `IIS AppPool\DefaultAppPool` and click Check Names they can't be resolved despite having Windows 2008R2 functional level.
Comment: That still doesn't make my suggestion untrue? Your explanation is likely, that doesn't make KB946139 false
Comment: Perhaps, but Application Pool Identities are not the same as built-in accounts such as NETWORK SERVICE, i.e. they don't really exist, don't have well known SID's etc. You would encounter the same problem regardless of functional level.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/2272/discussion-between-judasiscariot1651-and-kev)


Show that $\inf(\frac{1}{n})=0$.

Question:
We are given the following definition:
If a sequence $(a_n)$ is bounded from below then there is a greatest lower bound for the sequence called the infimum.
$m=\inf(a_n)$ if
i) $(a_n) \geq m \ \forall n \in \mathbb{N}$.
ii) For each $\epsilon >0 \ \exists \ n_\epsilon \ \in \mathbb{N}$ such that $a_{n_\epsilon} < m + \epsilon $.

Show using the definition that, if $a_n=\frac{1}{n}$ then $\inf(a_n)=0$.

Here is what I have:
i) RTP: $\frac{1}{n} \geq 0 \ \forall n\in \mathbb{N}$.
Assume that $\frac{1}{n} < 0$ for some $n \in \mathbb{N}$.
$\implies n < 0$.
But we know that $n \in \mathbb{N}, n \geq 1$, and thus we can say that$\frac{1}{n} > 0\ \forall n \in \mathbb{N}$.
ii) Let $ \epsilon > 0$ be given.
RTP: $\exists n_\epsilon \in \mathbb{N}$ such that $\frac{1}{n_\epsilon}<0+\epsilon = \epsilon$.
Proof:
$\frac{1}{n_\epsilon} < \epsilon \implies n_\epsilon > \frac{1}{\epsilon}$, since both values are positive.
For the given $\epsilon > 0$, choose $n_\epsilon > \frac{1}{\epsilon} \in \mathbb{N}$.
Now from the Archimedes Postulate, we know $\exists n \in \mathbb{N}$ such that $n \geq n_\epsilon$.
$\implies n \geq n_\epsilon > \frac{1}{\epsilon}$
$\implies \frac{1}{n} \leq \frac{1}{n_\epsilon} < \epsilon$, since all values are positive.
Answer: It's correct but can be written in fewer words:

$n>0$ implies $\frac{1}{n}>0$ so $a_n>0$ for all $n>0$;
given $\epsilon>0$, just pick any integer $n>\frac{1}{\epsilon}$, then $a_n=\frac{1}{n}<\frac{1}{1/\epsilon}=\epsilon$.
Answer: By pure substitution,
$0=\inf\left(\frac1n\right)$ if
i) $\left(\frac1n\right) \geq 0 \ \forall n \in \mathbb{N}$.
ii) For each $\epsilon >0 \ \exists \ n_\epsilon \ \in \mathbb{N}$ such that $\frac1{n_\epsilon} < \epsilon $.
Then
i) is obvious.
ii) holds by taking $n_\epsilon=\lceil\frac1\epsilon\rceil$.

Show that $\inf(\frac{1}{n})=0$.


Is the given function convex? Does the point satisfy the FONC?

Question: minimize $2x_1^2+x_2^2-2x_1x_2-4x_2$
subject to $x_1x_2\leq 4$

Is the objective function convex?
Does the point $(1,4)$ satisfy the FONC for a local minimizer?
Do optimal solutions of this given problem change if the constraint is replaced by the new constraint $x_1x_2\geq 4$?

I have done the following:
This is a quadratic function, rewriting it gives the Hessian to be

$\begin{bmatrix} 4&-2\\-2&2 \end{bmatrix}$ which has eigenvalues 5.2 and 0.76 so the function is convex.

The Lagrangian can be written as

$L(x,\mu)=2x_1^2+x_2^2-2x_1x_2-4x_2 -\mu(x_1x_2 -4)$
The KKT conditions are therefore:
$\nabla x L(x,\mu)=[4x_1-2x_2-\mu x_2=0,2x_2-2x_1-4-\mu x_1=0]$
$\mu(x_1x_2-4)=0$
Filling in $(1,4)$ in the first equation of $\nabla xL(x,\mu)$ gives
$4*1-2*4-4\mu =0$ so $\mu = -1$
Now using the value found for $\mu$ we fill in $(1,4)$ in the second equation of $\nabla xL(x,\mu)$. This gives
$8-2-4-(-1)1= 3 \neq 0$
Thus the point $(1,4)$ does not satisfy the FONC for a local minimizer.

I think the answer is yes, since the constraints are then changed.

Can someone please tell me if the answers I've given are correct or not? If not please explain why and what the right answer should be. Thanks a lot !
Answer: hint
i agree with (1) and (2), but (3) is non-trivial. You are optimizing a convex function over a convex interval. If the extreme values lie on the boundary, they satisfy $x_1x_2 = 4$, so that point will satisfy both sets of constraints.


Change string value using putBoolean return a numeric value in android?

Question: I have string field <string name="categegoriesStatus">true</string>
Now inside settingsActivity I am changing its value on preference click.
final SharedPreferences sharedpreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedpreferences.edit();
                        editor.putBoolean(getResources().getString(R.string.categegoriesStatus), false );
                        editor.apply();

But it is not changing it to false, but change it to some numeric value. And I don't get my desired result.
Comment: what's the numeric value your call returns?
Comment: @ChampS it returns value = 2131238702
Answer: You have a string, but you want to save a boolean. Then, you should be this:
  boolean result = getResources().getString(R.string.categegoriesStatus).equals("true");
  editor.putBoolean(result, false );

Good luck!
Comment: I got 'Wrong first argument type. Boolean required'
in the 'result' variable.

I did this : editor.putBoolean(String.valueOf(result), false);
But it won't work.
Comment: You can try cast result to Boolean object. Maybe `(Boolean) result`? or `Boolean result = getResources().getString(R.string.categegoriesStatus).equals("true");`
Answer: You are using Sharedpreferences wrongly.
in the statement editor.putBoolean(getResources().getString(R.string.categegoriesStatus), false );
you are inserting editor.putBoolean("true", false); which is not what you are expecting it to do.
Information stored in shared preferences should be in key value format.
Read the android documentation from this link: http://developer.android.com/reference/android/content/SharedPreferences.Editor.html
Answer: Shared Preferences only saves/retrieve key value pairs. It does not change your string resource values. Once you have declared a string resource field, you cannot change it's value at runtime. Please refer to this answer.


How to migrate products display nodes with multiple product references?

Question: I have a site being migrated from Drupal 6 to 7. The old site had a home grown system for adding payments to signups for event nodes. We plan to use commerce module to selling the registrations for events going forward.
In the new site, we are planning to import the preexisting SKUs from the old site with feeds but I want to include the product references with the event migration we have written. This migration is already working and just needs to have the product references added to it.
My question is about how to prepare the source data to be mapped when it looks something like this:
nid | sku
---------
1   | a
1   | b
1   | c
2   | a
2   | d

When it seems like it would be better if the data was like this:
nid | sku
---------
1   | a,b,c
2   | a,d

I think if I had the like the second table, I could join the source table
// Join payment_options_skus table
$query->join('payment_options_skus', 'pos', 'pos.nid = n.nid');
$query->fields('pos', array('sku'));

and then map like so:
$this->addFieldMapping('field_registration', 'sku')
     ->separator(',');

Is there a better way to do it using the existing data in the first example table? I would like to limit the number of manual massaging steps needed. Thanks.
Answer: I'm in a similar boat, but doing an import for a content type. If data is prepared with multi-value fields as in your second table, I can import the data using Feeds and the plugin 'Feeds Tamper'. So I'm also looking at repeatable and efficient ways to arrange data with multi-fields in CSV format. Saw a post about using Drupal 7 'Feeds Tamper PHP' to do create the multi-valued fields here, https://www.reddit.com/r/drupal/comments/2tumv9/drupal_7x_feeds_tamper_column_values_to_single/co2hesj. <-- Untested, just a reference. HTH.
Comment: Well, I need to move this project forward so this morning I set up a spreadsheet with the data and concatenated the skus together with a "|" character as a separator. I didn't want to use Feeds as I have already written a migration for the content type. I got it to work and will document my solution later today.
Answer: I was unable to find a way to import the product references as they were in the original data structure. Instead, using Libreoffice Calc, I wrote some concatenate functions to merge the rows so that I had one rows per event node. Also, I found that I needed the "product_id" of the product, not its SKU. For that, I imported the commerce_products table into my spreadsheet and then did a VLOOKUP to find the product_id for each SKU. I then exported the worksheet to a CSV file with this structure:
|nid|product_ids
----------------
|1  |100,101,102
|2  |100,105

Then my mapping looked like so:
$this->addFieldMapping('field_registration', 'product_id')
     ->separator('|');

And may source looked like:
// Join payment_options_skus table
$query->leftJoin('payment_options_skus', 'pos', 'pos.nid = n.nid');
$query->fields('pos', array('product_ids'));


How to join a Lync 2013 / Skype for Business meeting as a guest when the application is installed but you don't have an account?

Question: I've stumbled upon a bizarre problem with Skype for Business 2015 (the client application, previously known as Lync 2013 but automatically upgraded to SfB 2015 by some Office update); maybe I'm missing something, but I'm unable to find a solution, hence this question.
The issue: someone invites you to a meeting, but you don't have a Lync/SfB account, thus you need to join the meeting as an external guest by clicking on the meeting link you received; however, the application is actually installed on your computer, as part of the Office 2013 package; in this scenario, clicking the meeting link will automatically launch the application, but then it will get stuck on asking you for sign in information, which you don't have. It looks like there is no way to avoid launching the application if it's actually installed, or to sign in as a guest.
How can you join a Lync 2013 / Skype for Business meeting as a guest when the application is installed on your computer but you don't have any account you can use?
Answer: It is a little hackish, but if you right click > copy the Join Skype Meeting url from the invite, paste it in your browser and add "?SL=1" (without the quotes, so it would look something like https://meet.yourdomain.com/user/98daf9w?SL=1) on the end, it will force to join in via the web app (where you can join as guest) instead of automatically opening Lync/S4B client that requires a login.
Hope this helps!
Comment: This actually works. I'll wait to see if there is a simpler way to manage this before accepting your answer, but it indeed works.
Comment: Yeah, I've tried to find a cleaner solution to this myself as well but so far haven't. Would love to hear if anyone else knows of a better way :)
Comment: added a better option which might be more user friendly ;-).
Answer: A better option (as the user might not remember to add the "?SL=1" after some weeks) would be to disable the IE "MeetingJoinHelper" add-on. To Do that perform the following steps:

Open the Internet Explorer
click on the tools icon
then open the "Manage Add-ons" section
Select "All add-ons" than select the the "MeetingJoinHelper Class" add-on
click on disable

P.S. If you need some pictures and a longer howto check the source here.


ArrayList em JAVA

Question: Tenho uma pergunta sobre ArrayList
Exemplo:  Fiz uma interface gráfica em Java para cadastrar jogadores em um ArrayList. após o cadastro, o jogador vai para um Jlist, ai que vem minha dúvida. Quero comprar esse jogador para o meu time, eu seleciono ele e clico em comprar e no caso esse método comprar eu só usei um remove. Queria remover ele da lista dos jogadores que estão à venda e colocar ele no meu Time?
Comment: poderia mostrar seu código até o momento?
Comment: Cola o código no post para poder entender melhor
Comment: Se você colocar o código que você fez até o momento a gente consegue colocar seguindo a sua lógica. Fornece, por favor o código.
Comment: Gostaria de adiciona um adendo sobre ArrayList: [aqui](http://pt.stackoverflow.com/a/195006/6789)
Answer: Por lógica, do mesmo jeito que você tem um ArrayList de jogadores "livres", cada objeto Time tem que ter o seu ArrayList de jogadores.
Analise melhor isto... pense num histórico do jogador, coloque um objeto Contrato aí no meio, onde tem o id do jogador e o id do time, além das datas de inicio e fim do contrato.
Answer: Você tem algumas alternativas, entre elas:

Adicionar o jogador que você selecionou no ArrayList Time antes de tê-lo removido do ArrayList de jogadores à venda:
public class Time {
    private ArrayList<Jogador> time; //ArrayList do seu time.
    public Time() {
        time = new ArrayList<>();
    } public adicionarJogador(Jogador a) {
        time.add(a);
    }
}
//
public class Vendedor {
    private ArrayList<Jogador> vendavel; //ArrayList de jogadores à venda, supondo que já existem jogadores nesse ArrayList.
    Time a = new Time();
    public venderJogador() {
        a.adicionarJogador(/*Índice do jogador que você selecionar através da interface.*/);
        vendavel.remove(/*Índice do jogador que você selecionar através da interface.*/);
    }

...

ArrayList em JAVA


Feasible to do hierarchical CFA with only two first-order factors?

Question: Kline (2011) p249 writes:

To identify a hierarchical CFA model, there must be at least three
  first-order factors. Otherwise, the direct effects of the second-order
  factor on the first-order factors or the disturbance variances may be
  underidentified. Each first-order factor should have at least two
  indicators.

Kline presents this as a hard and fast rule. Are there any exceptions to this rule that could apply in a practical scenario (even if those exceptions are a bit farfetched)?
Why are 3+ first-order factors required? If we forget about hierarchical factor analysis for a moment, I know that in a regular factor analysis having two indicators per factor and two factors is a technical minimum. That is, with two indicators per factor and two factors we might have with empirical underidentification or nonconvergence of iterative estimation, but usually it more or less works. I figured that since the second-order factor has no indicators, the first-order factors were in a way acting like indicators for the second-order factor. So maybe a model with one second-order factor and two first-order factors was kinda like a factor analysis model with two indicators and only one factor, which doesn't work. Is that an appropriate analogy for why it doesn't work?
What should I do in a situation in which I 'want' to test a hierarchical factor model with a single second-order factor only two first-order factors? Are such models inherently untestable, or is there some way around this?

Kline, R. B. (2011). Principles and practice of structural equation modeling. Guilford publications.
Answer: It's not really a hard and fast rule, it's just that if you only have two first order factors, your model will be equivalent to a model where they are correlated. Your point 2 is correct.
It's just like if you have two measured variables, and want to fit a single factor model. If you have two variables (latent or measured), you have one covariance / correlation to account for - so you have only got 1 degree of freedom.
Say that these two variables are correlated 0.64. You want to estimate two loadings, but you only have 1 df, so you can only estimate one parameter. The way to fix that is to constrain the two loadings to be equal. If you do that, the loadings will be sqrt(0.64) = 0.8.
So (to address point 3) you can fit the model, but it won't tell you anything you didn't already know, and you won't learn anything from it.
(I'd argue that three first order factors doesn't tell you something - the factor loadings are a transformation of the factor covariance matrix, and are completely determined - you need four factors to over-identify the second order factor).


I want to put values from additional database in drupal 7. How can I do it?

Question: I wanted to include additional values to the drupal site. Since it has around 3000 records and it is divided into categories ( a:1, a:2, a:3, b:1, b:2, c:1, c:2, c:3), I had set additional database and connected to drupal.
My question is:
How can I get those values into drupal? views? They have to be included in two forms as a checkboxes and value lists on other form to choose.
Thank you.
Comment: Why are you using a different database, you should be able to create a table in your Drupal DB and add them there. Which Drupal version are you using?
Comment: I would like to keep data on different database as I thought this may help me to maintain it when i had to upgrade or update Drupal. Value of this lists are taken to the form and they are integral part of the system. I even think that a module that includes this values will be a good option to keep data clean, maintain, re-install then needed, and so forth.... There are 2 value lists. First contains more than 3000 records, second around 400 records. Both are 2 levels lists. Am I correct in my thinking?.. or there may be a better solution?
Answer: This thread: https://drupal.stackexchange.com/questions/3275/how-do-i-display-an-external-database-data discusses this issue quite thoroughly.
Answer: If you were using Drupal 6, I would suggest using the Data module, however in Drupal 7 there isn't an equivalent. The Data module would have connected data in two different databases in Drupal if they were described in settings.php.
If you know a little PHP and basics of the Drupal API you can use the new Field API. It's pretty straight forward using the hook_field_scheme() to define the database table and the standard Field API hooks to create fields that can be attached to entities in the Drupal Admin UI.
You can use hook_theme() to define different templates that renders the data in different ways and hook_field_formatter_view() to call different theme functions and templates that you create. Views integration is wonderful because if you create several different formatters when you select the field in the Field section of Views UI it will give you a drop down choice of what formatter to use.
In this case if you're importing the data you don't need to attach the field to a content type, nevertheless, if the data at some point needs to be updated, added to, or deleted dynamically it is already to go with only using four or five different functions.
I have a case where I have a single address field defined but it includes city, state, country, zip, lat, lng, ect. in each row of the database table. However, I have 5 different formatters, one with only lat and lng converted to degrees, another with only the city and state, and one with the entire address as a vcard with a call to google to return a static map with a marker. In views I just choose which formatter to use with the information.
Comment: Thank you, I have installed Data Module. I think it helps a lot, actually it will help if I can figure out how to work out this error message: user warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'maxvalue) VALUES (5, 'id_model', 0, 1, 1, 0, 0, 0, 'int', 1, 4122)' at line 1 query: INSERT INTO tw_columns (twtid, colname, weight, primarykey, availablefk, secure, ignorecol, isempty, coltype, minvalue, maxvalue) VALUES (5, 'id_model', 0, 1, 1, 0, 0, 0, 'int', 1, 4122) in /Applications/MAMP/htdocs/autocze


IntelliJ Idea + JavaFX = class.getResource() returns null

Question: I know, there are lots of similar question around here with similar problems, but after reading tons of posts, I cannot simply solve this issue.
Under Compiler > Resource Patterns, I've already put this string "*.fxml". Moreover, I've marked the resources folder as the Resources Root.
Here you can see my project structure:

This is my MainView.java class.
package dataParser.View;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class MainView extends Application {
    private Stage primaryStage;

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

    @Override
    public void start(Stage primaryStage) throws Exception {
        this.primaryStage = primaryStage;

        FXMLLoader loader = new FXMLLoader();
        System.out.println(this.getClass().getResource("/MainView.fxml"));
        loader.setLocation(getClass().getResource("/MainView.fxml"));

        MainViewController mainViewController = new MainViewController();
        mainViewController.setMainApp(this);

        loader.setController(mainViewController);
        Parent layout = loader.load();

        Scene scene = new Scene(layout);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    Stage getPrimaryStage() {
        return primaryStage;
    }

}

Still, I'm just getting back a null resource. Any hints?
Thank you!
EDIT
This is the complete stack-trace. I've also noticed that I've issues linking all my resource files.
    Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:973)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:198)
    at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: java.lang.IllegalStateException: Location is not set.
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2459)
    at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:2435)
    at dataParser.View.MainView.start(MainView.java:29)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:919)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$11(PlatformImpl.java:449)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$9(PlatformImpl.java:418)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:417)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:175)
    ... 1 more

Comment: Print out URL returned by this.getClass().getResource("./) then check if your *.fxml fiels end up in same directory.
Comment: Compile to a jar, open it, and look whether the MainView.fxml is there. On principle (will not help) use `MainView.class.getResource` instead of `getClass().getResource`. Use a **maven** build infrastructure for your project, will have correct settings out of the box: src/main/resources and such.
Comment: Hi. I'm using Gradle and it set up everything for me.
Moreover the .fxml file is into the generated .jar file.
Comment: Gradle provides a standard too. Starting the jar on command line? I had the hope there would be a `/MainView.fxml.xml`, `/resources/MainView.fxml` or such but alas. One time I had a `í` instead of an `i` in the file name. Reenter the string `"/MainView.fxml"` maybe there is some invisible garbage. Because actually there cannot be much wrong.
Comment: At the moment I'm simply building and running the program through IntelliJ Idea. I cannot simply understand what the problem can be.
I tried to rewrite the string and also to follow the hint in this post (https://stackoverflow.com/questions/20507591/javafx-location-is-required-even-though-it-is-in-the-same-package) where they said to put the .fxml files inside a custom /fxml folder. This issue is driving me nuts.
Comment: It prints out the absolute path to get to the directory containing the class.
Comment: Post the complete stack trace
Comment: Ok, I'll do it next morning. I've found out I'm having issues linking every kind of resource file. I've tried lot of methods, like class.getResource() or getResourceAsStream(), with no avail. See you tomorrow and thank you.
Comment: Question updated with the stack trace log.
Answer: After some time I found a solution to this nasty issue and I'll try my best to explain it here.
First of all I've set up my Project Structure (File > Project Structure...) in a proper way, defining both the Source and Resource folders, so that IntelliJ Idea would be able to find them. Moreover I've checked that my resources files had been properly put in the "build" and "out" folders (they're used by Gradle and IntelliJ during the building process): I've also achieved it by setting my "File|Settings|Compiler" settings as nicely pinpointed in many Stack Overflow answers.
At last I've used this structure while calling for my resources files:
FXMLLoader loader = new FXMLLoader();
System.out.println(MainView.class.getResource("/fxml/MainView.fxml"));
loader.setLocation(MainView.class.getResource("/fxml/MainView.fxml"));

I want to pinpoint that my fxml folder has the Resources one as root folder.
Comment: Thanks! I want to add that the first slash in the path is very important!
Answer: The problem may be that IntelliJ does not know that it needs to copy the .fxml file into the output directory. You may need to add something like ";?.fxml;?.css" to your File|Settings|Compiler settings to tell it to copy the files during a build. See How to convert a normal java project in intellij into a JavaFx project for more information.
Comment: Hi, @Davide3i. Congrats for figuring out the problem. I encourage you to update this bug with the solutions that you found so that anybody else who has the same problem can find the solution here. (It can be [Very Frustrating](https://xkcd.com/979/) when searching for a solution to find a statement that a question has been answered, with no answer given.)
Comment: Hi! At last, a couple of months ago, I've solved my problem fiddling with the IntelliJ Idea project settings and looking around Stack Overflow for the proper way to call up the path to a file.


Json deserialization Mvc 4 Knockout js

Question: I'm having problems when I try to deserialize json into a object in MVC4.
I have a Viewmodel:
 public class TestViewModel
{
    public string Code { get; set; }

}

On the view I get the model and serialize the object using Json.net
var Vm = function(data) {
        var self = this;

        ko.mapping.fromJS(data, {}, self);

        self.GetResults = function() {
            $.ajax({
                type: "POST",
                url: '@Url.Action("Action", "Controller")',
                data: ko.mapping.toJSON(self),
                success: function(data) {
                    alert('OK');
                }
            });
        };
    };

    var viewModel = new Vm(@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)));
    ko.applyBindings(viewModel);

My problem is when I call GetResults the action in the controller, all properties are null.
My Json is:
{"Code":"TestCode"}

I have the same structure in a MVC3 project and works fine. I'm missing something in MVC4?
Cheers!
Comment: Have you tried using Fiddler to see what the request and response look like?
Comment: Yes, the request looks fine, it has Content-Type: application/json
Accept: application/json, text/javascript, */*; q=0.01, and the json in the question {"Code":"TestCode"}
Answer: We've noticed that in some scenarios jQuery will embed the data in a Form in the Request. When this happens, the values are not automatically mapped to the object type in the Controller method.
To get around this, you need to do two things:
1) Check to see if the data is serialized. I found an easy way to do this and dumped it in an extension method:
public static class WebContextExtensions
{
    public static bool IsDataSerialized(this HttpContext context)
    {
        return context.Request.Params.AllKeys[0] == null;
    }
}

2) IF IsDataSerialized returns true, you need to deserialize the data into your object type.  We wrote a GenericDeserializer method to do that as well:
public class GenericContextDeserializer<T> where T : new()
{
    public T DeserializeToType(HttpContext context)
    {
        T result = new T();
        if (context != null)
        {
            try
            {
                string jsonString = context.Request.Form.GetValues(0)[0].ToString();
                Newtonsoft.Json.JsonSerializer js = new Newtonsoft.Json.JsonSerializer();
                result = js.Deserialize<T>(new Newtonsoft.Json.JsonTextReader(
                               new System.IO.StringReader(jsonString)));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        else
            throw new NullReferenceException();
        return result;
    }
}

Now put it all together in your Controller method:
[HttpPost]
[HttpOptions]
public HttpResponseMessage MyAction(JsonData data)
{
    var results = Request.CreateResponse();
    try
    {
        data = new GenericContextDeserializer<JsonData>().DeserializeToType(HttpContext.Current);
        // do stuff with data
        results.StatusCode = HttpStatusCode.OK;
    }
    catch (Exception ex)
    {
        results.StatusCode = HttpStatusCode.InternalServerError;
    }
    return results;
}

If you want more detail, it's in the second half of a blog post I wrote.

Json deserialization Mvc 4 Knockout js


NetBeans + GitHub = git-receive-pack not permitted

Question: Estou utilizado o git para fazer o controle de um projeto da faculdade, estamos utilizando o netbeans+eclipse e um amigo que participa do projeto me enviou o link do git, fiz o clone do projeto, porem não consigo fazer fazer o push no netbeans. é exibida a mensagem de erro git-receive-pack not permitted
Answer: Verifique se o seu usuário esta adicionado como colaborador nas configurações do repositório no GitHub.
Peça para o dono do repositório acessar as configurações e na segunda opção, "Collaborators" ele poderá incluir seu usuário do git ou email.
Abraço.


Erro declaração Android-Studio

Question: Queria saber porque meu android studio esta dando esses erros nas declarações, essa print ai é de um projeto novo, declaração feita pelo próprio android studio esta dando erro.
Comment: Não apareceu o print na pergunta
Comment: acabei de editar... tinha esquecido de colocar a imagen
Answer: Por favor tente os seguintes passos:
1 opção Vá até o Menu > File > "Invalidade Caches / Restart"
Caso não dê certo.
2 opção Vá até o Menu > Build > clean Project. Depois que finalizar o processo vá novamente em Build > Rebuild Project
Comment: desculpe não deu certo, ainda continua.
Comment: Qual erro ele mostra quando voce sobrepoe o mouse nas palavras em vermelho?
Comment: https://imagizer.imageshack.com/img923/7901/QAQLCC.png
Comment: Certo. Como o Invalidade não deu certo. Faça o seguinte: Feche o projeto. Vá até o diretório do projeto e apague a pasta .gradle e .idea
Comment: Depois abra novamente o projeto aguarde rebuildar e comente aqui se deu certo ou não.
Comment: deu o seguinte erro:ERROR: Failed to resolve: com.facebook.android:facebook-login:100.1.1
Show in Project Structure dialog
Affected Modules: app
Comment: Veja se o topico no link te ajuda: https://stackoverflow.com/questions/46670842/failed-to-resolve-com-facebook-androidfacebook-login4-5/46671052

Erro declaração Android-Studio


Android filewriting, reading

Question: I have a dialog with spinners and an OK button. I also have an arraylist that is populated by the user selecting items in the spinners. I want the app to save the arraylist to a file and load it at every launch (because without saving the arraylist is always empty at launch).
So here is the code i am using. The saving should be okay, at least i get the Toast message saying Saving OK. This code is the OKbtn listener so when user clicks ok, an item is added to the arraylist and there comes this code:
if (assignArr.size() > 0)
                      {
                        String filename = "file.txt";
                        ArrayList<String> report = new ArrayList<String>();

                        for (int i=0; i<assignArr.size(); i++)
                        {
                            report.add(assignArr.get(i));
                        }

                                FileOutputStream fos;
                                                try {
                                                        fos = openFileOutput(filename,Context.MODE_PRIVATE);
                                        ObjectOutputStream out = new ObjectOutputStream(fos);
                                        out.writeObject(report);
                                        out.close();
                                        Toast.makeText(MainActivity.this, "Saving OK", Toast.LENGTH_LONG).show();
                                                } catch (FileNotFoundException e) {
                                                        // TODO Auto-generated catch block
                                                        e.printStackTrace();
                                                } catch (IOException e) {
                                                        // TODO Auto-generated catch block
                                                        e.printStackTrace();
                                                }
                      }

I put the loading part to the beginning of the code, but i don't think it matters:
words = new ArrayList<String>(50);
        try {
        InputStream is = getResources().getAssets().open("file.txt");

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line;

        while((line = br.readLine()) != null)
        {
              words.add(line);
        }
        is.close();
        }
        catch (IOException e)
        {
          e.printStackTrace();
        }

        if (words.size() > 0)
        {
            for (int i=0; i<words.size(); i++)
            {
                assignArr.add(words.get(i));
                Toast.makeText(MainActivity.this, "Loading OK", Toast.LENGTH_LONG).show();
            }
        }

In this case i never get the toast message.
One problem can be that where is the file created? Where in the emulator and where on the phone? And regarding the phone, is it created on the sd card or the phone memory?
I hope this is the right code to save and load an arraylist.
What is wrong with the code?
Update:
I replaced InputStream is = getResources().getAssets().open("file.txt"); withInputStream is = openFileInput("file.txt");
Now something happens. I write out the result of the saving and the loading into a toast message, which is weird:
  Toast.makeText(MainActivity.this, "Saving OK + " + report, Toast.LENGTH_LONG).show();

Please take a look at it. The words on the bottom are partly hungarian names. So maybe the saving an arraylist to a file is the problem.
Comment: go to Here and look this

http://stackoverflow.com/questions/17650522/write-in-file-and-read-it-and-put-on-in-a-spinner-in-android

good luck
Answer: The file you create via openFileOutput is written into your app's private directory, which you can get using Context#getFilesDir() (usually it's /data/data/<your-app-package>/).
This directory has nothing to do with the assets folder.

Android filewriting, reading


What is the number of solutions of $2a+2b+2c+d=n$

Question: I have a equation and I need to find the number of possible integer solutions for it. The equation is of the form
$$2a+2b+2c+d=n, (a,b,c,d > 0)$$
Comment: Have you tried searching. This question or one closely similar has come up several times in the last week.
Comment: Yes, I tried but I couldn't get a solution except for the general case with no restrictions
Comment: See also http://math.stackexchange.com/questions/602547/how-many-positive-integer-solutions-does-the-equation-x-y-z-w-15-have?rq=1, or http://math.stackexchange.com/questions/657515/how-many-solution-of-a-equations?rq=1.
Comment: It boils down to $\sum_k\binom{2k+2}{2}$ which should give a cubic. It's pretty straightforward but perhaps there are more clever solutions.
Comment: @VivekMaskara The restriction to positive integers is trivially dealt with. Anyway the idea is to help you solve things yourself, not provide solution service! :)
Comment: yep positive integers is no longer a problem. @Burde's link helped
Comment: Is there any restriction on $n$?
Answer: Use the generating function of the LHS:
$$f(x) = (x^2+x^4+x^6+...)^3(x+x^2+x^3+...)$$
and the answer for the equation is the coefficient of $x^n$ in the generating function.
To get the cofficient, we split to disjoint events, by the size of $d$, obviously that if $n$ is even/odd then $d$ is even/odd, and then divide $n-d$ by $2$ and split it to $3$ different cells with repetitions $$CC_3^{\frac{n-d}{2}}$$
Then sum over all those events.
Comment: Finding that coefficient is exactly the point of the question.
Answer: Idea:

Let $a+b+c=k$, then we have $2k+d=n$. Now for any given value of $d$  there is corresponds $3$ values of $k$. So for $m$ values of $d$ we have $3m$ values of $k$
So that we are going to have ... solutions.


Como inserir dados de um textarea no banco de dados?

Question: Tenho um form com um textarea e não estou conseguindo mandar os dados digitados nele para o banco MySQL. Como faço?
formulario.php
<form id="cadastro" name="cadastro" method="post" action = cadastro.php>

<textarea id="text_descricao" name="text_descricao" maxlength="800" cols="60" rows="15"; style="resize: none"></textarea>

<input name="cadastrar" type="submit" id="cadastrar" value="Cadastrar"/>

cadastro.php
<?php

    $descricao = $_POST['text_descricao'];

    $sql = "INSERT INTO mensagens VALUES ";

    $sql .= "('$descricao')";

    mysqli_query($conexao,$sql) or die("Erro ao tentar cadastrar registro");

    mysqli_close($conexao);

?>

Comment: Qual o erro? Qual a estrutura da sua tabela?
Answer: Meu caro tente fazer dessa forma
<?php
    //Seta os campos e valores seguindo a ordem que existe na tabela

    $sql = "INSERT INTO mensagens (descricao) VALUES ";
    $sql .= "('$descricao')";

    //ou então dessa forma
    //ASSIM VOCÊ PASSA PARA CONSULTA SOMENTE OS CAMPOS DESEJADOS OU SEJA
    //SE HOUVER
    //MAIS CAMPOS EM SUA TABELA MAS NÃO TERA INFORMAÇÕES PARA ELE NO
    //MOMENTO EM  QUE SALVAR A MENSAGEM PODE FAZER ASSIM.
    $sql = "INSERT INTO mensagens SET ";
    $sql .= "descricao = '$descricao' ";
?>


Difference between APC & Memcached and how both can be used for cache bins

Question: I'm trying to understand the difference between Memcached and APC and why people talk about using one or the other or both. I can't understand why you wouldn't use both because I thought they had completely different roles. Here's my understanding:
APC
This caches chunks of PHP code and stores it in RAM. Then when you need to run that same piece of code again it's already cached and runs from memory lightning fast.
In my particular case of running PHP-FPM, this would reduce the load on that.
Memcached
(I'll ignore the difference between the two php modules and treat them as the same thing for this purpose)
This caches DB objects and stores them in RAM. Then when drupal needs to call the same database object all the information is sitting there and it doesn't need to go to the database.
In my particular case of running MySQL, this would reduce the load on that.
Drupal Cache Bins
There are a bunch of questions on Drupal Stack Exchange about caching and cache bins both which mention APC & memcached:

In Where is the best place for cache bins, Memcache is
recommended because of stability issues with APC.
In Is there any gain using Memcached module when APC is running good..., it's said the choice comes down to personal preference.
In Using Drupal 7 with APC, Varnish and Memcache... it talks about combining both of them.

So several of the really informative questions in this area recommend just using Memcached and a couple other ones say there's not a huge difference to introducing both.
But I don't understand how this works. Aren't they caching completely different things?
Suppose I have a view which is used a lot. Isn't memcached caching the DB objects that are shown in the view and APC is caching the module code which calls them?
Is the difference that you can only use one cache for each Drupal cache bin, so you can either choose to cache DB objects or PHP code and in practice most Drupal cache bins have either little performance difference between the two or are too large to cache all the PHP so caching DB objects is the only reasonable option?
(And thus why most people suggest memcache as the default cache bin option i.e. <code>$conf['cache_default_class'] = 'MemCacheDrupal';</code>)
Comment: BTW the previous comment is grossly over-simplified (APC _can_ be used as a data-store cache for example, it just generally isn't). I'd recommend reading as much as you can about both types of cache to understand if they're useful for you
Comment: @DominicWoodman The APC module for Drupal doesn't do the op-code caching.  It is an alternate cache-back end that uses the APC user-cache.
Comment: They're not comparable - APC is an opcode cache (caches results of function calls to speed your code execution up). Memcache, or redis, or whatever in-memory data-store you want to substitute in here, is used as a cache for your site's data. Apples and oranges really. As with any technology, "which should I use?" can only be answered by you, after you've benchmarked their usage on your server with your app and your expected load. See http://stackoverflow.com/questions/815041/memcached-vs-apc-which-one-should-i-choose for general advice on these two
Comment: I was just trying to understand why in a lot of the questions people talk about the decision between APC & memcached. If they're both completely different why wouldn't they both have a place on the same Drupal project to cover their different strengths. Presumably if you set the same cache bin to be covered by APC as opposed to memcached you're getting a completely different cache? (And depending on your site usage and structure one will be better for you)
Comment: I also think this is a dup.
Comment: @MPD Ah that would explain the choice. I somehow managed to completely miss that. So running APC in php normally is an opcode. Then by enabling the module you use it as a user-cache in a similar way to memcached, which is why people end up choosing between the two, because at that point the APC module uses APC to do the same thing as memcached. That should be answer for this, if you don't want to close it as a dupe.
Answer: APCu
Does not share the cache with other servers but is faster.
Memcached
Can be shared with other servers and is slower.
If you have 2 or more web servers (apache/nginx) for the same Drupal site you'll want Memcached. If you are running on a single machine then APCu will be the quickest. You'll want OPcache turned on no matter what.
LCache is a module designed to fix the issues with using APCu in a 2 or more web server environment.


Differentiating both sides of a non-differential equation

Question: I'm working on solving for $t$ in the expression $$\ln t=3\left(1-\frac{1}{t}\right)$$ and although I can easily tell by inspection and by graphing that $t=1$, I'd like to prove it more rigorously.
I got stuck trying to solve this algebraically, so I tried to take the derivative of each side with respect to $t$ to get
$$\frac{1}{t}=3\left(\frac{1}{t^{2}}\right).$$
However, this implies that $t=3$, which is incorrect.
Why can't I take the derivative of each side like this? What am I doing wrong or misunderstanding?
Comment: You have your answer to the question you asked, I have also done some analysis of how you would find the values for $t$ in this equation.  Note that there is more than one solution for $t$.
Answer: To answer the general question of "Why can't [one] differentiate each side [of an equation]?": Your original equation, of the form $f(t) = g(t)$, acts as a condition (i.e., is only true for some real $t$, in this case finitely many), not as an identity (true for all $t$ in some open interval).
When you differentiate a function $f$ at one point $a$, you implicitly use the values of $f$ in some neighborhood of $a$. Since your $f$ and $g$ are not equal in any open neighborhood, you can't expect differentiating to yield a new true condition.
In case an example clarifies, take $f(t) = t$ and $g(t) = 0$. The equation $t = 0$ certainly has a solution, but differentiating both sides gives $1 = 0$.
By contrast, it's safe to differentiate both sides of, e.g., $\cos(2t) = \cos^2 t - \sin^2 t$, since this equation is true for all real $t$.
Comment: Thanks! That's the kind of explanation I was looking for.
Comment: @1110101001: By "some real $t$", I meant _at isolated points_. If you treat the _two-variable_ equation $x^{2} + y^{2} = 4$ as a condition defining $y$ as a function of $x$ with no further qualification, you're effectively assuming $y = f(x)$ for some differentiable function $f$ defined in the open interval $(-2, 2)$.
Comment: What about doing differentiation on something like $x^2 + y^2 = 4$. Doesn't that act as an implicit condition since it only works for certain values of x,y
Comment: For those who want to know the definition of identity equations and conditional equations, see [this](https://www.papertrell.com/apps/preview/The-Handy-Math-Answer-Book/Handy%20Answer%20book/What-are-identity-and-conditional-equations/001137022/content/SC/52cb001a82fad14abfa5c2e0_default.html#:~:text=Identity%20and%20conditional%20equations%20are,is%20called%20an%20identity%20equation.&text=For%20example%2C%203x%20%3D%203x%20is,always%20be%20the%20same%20number.).
Answer: Let $f(t) = \ln t - 3 (1 - 1/t)$. You're saying that $f(1)= 0$ and $f'(3) = 0$; there is no problem here. The point is that when you try to find a value of $t$ that satisfies the first equation, you're looking for a root of $f$, while looking for a value of $t$ that satisfies the second equation is the same as finding a root of $f'$. In general, these are not the same and you have no reason to expect that they'll give you the same answer.
I'm not sure that there are easier ways to solve this than by inspection, though.
Comment: $t$ is a variable, and finding a $t$ so that $f(t) = g(t)$ and finding a $t$ so that $f'(t) = g'(t)$ are different, and generally unrelated problems.
Comment: So the $t$s are not the same, in other words?
Answer: The derivative of a function measures the gradient of the function at various points, and this does not give you the solution for $t$ of the original.  We can use the method of differentiation to analyze the equation, however:
$$\text{Let }f(t)=\ln t-3+\frac 3t$$
$$\text{Then }f'(t)=\frac 1t-\frac 3{t^2}$$
We can see that $f'(3)=0,\forall t\in (0,3),f(t)$ is decreasing, and $\forall t\in (3,+\infty),f(t)$ is increasing, so $t=3$ is a global minimum for the valid range of $t\in \mathbb R^+.$
Continuing the analysis:
$$\ln t=3\left(1-\frac 1t\right)\implies t={e^3\over e^{\frac 3t}}\implies e^{\frac 3t}={e^3\over t}$$
which is a nice near-symmetric equation.  Observation now immediately shows that $t=1$ is a solution, but the other solution starts at the beginning again:
$$\ln t=3\left(1-\frac 1t\right)\implies \ln t^{\frac 13}=1-\frac 1t\le \ln e$$
$$\implies t^{\frac 13}\le e\implies t\le e^3\text{ and } \ln e^3\gt 3\left(1-\frac 1{e^3}\right)$$
$$\text{Also, }\ln (e^3-e^2)=2+\ln (e-1)\lt 3-\frac 3{e^3-e^2}$$
With this, we know that the other solution is for some $t\in (e^3-e^2,e^3).$  Graphing shows the actual value at $t\approx 16.8,$ and it is likely that further analysis could come up with a decent closed expression for this value.
Comment: There is a [Lambert W](https://www.wolframalpha.com/input?i=ln%28x%29%3D3%281-1%2Fx%29) closed form for the $16.8…$ root.
Comment: Yes, I tried that method but to no avail.
Comment: Are you allowed to use Newton's method ? If yes, you have all required elements (initial value : 16.8, function and derivative definitions). So,j you will solve in few iterations to very hich accuracy.
Comment: @ClaudeLeibovici:  Newton's method is a good suggestion for arriving at a good approximation.  Since I'm doing this by hand for the benefit of the OP (and since my graphing program can give me lots of significant digits very quickly as well), I'm not so concerned about getting a high-accuracy value as I am about offering some avenues to narrow down where the solution might be.


Fit odd number of triplets in a measure?

Question: I'm trying to pass a melody from my head to the sheet and it consists of 29 eighth-note-triplets but I can't figure out how to break them into measures.
If I start with 4/4, I can fit 2 measures of 12 triplets each and ill have 5 leftover, but I can't find a time signature for these leftovers.
Comment: How do you know they're triplets? Is there an underlying pulse? If so, THAT will tell you where the barlines come.
Answer: First thing to do is to listen very carefully, and establish wher in the bar any of the main notes come - the emphasised ones that in a standard 4/4 bar would arrive on beats 1 and 3, and then work out what happens on beats 2 and 4. That will give a fair idea of placement of some of the notes.
29 seems odd (it usually is) so is there a possibility that the 30th note is at the end of a bar, rather than being the 1st note in a new bar?
Comment: Can the 30th note just be a rest?
Comment: @trolley813 - certainly. But *something* that takesit up to a count of 30 seems reasonable. However, that would account for 10 crotchets that would need to fit into X bars.
Answer: I think the first thing you should ask yourself is whether notating this rhythm as eighth-note triplets is actually necessary. Could this just as easily be done with two measures of 12/8 followed by a (only slightly unusual) 5/8 measure? Only if there's another instrument playing straight eighth notes, or something else about the context that makes eighth-note triplets vastly more natural would I even consider notating this idea as triplets. Seriously consider it, because the full solution is extremely unusual, and most musicians won't even recognize it.
Here it is: if you really need for these notes to be triplets the whole way instead of (the identical sounding) eighths of compound time, then you could notate this idea as two measures of 4/4 followed by a measure of 5/12. Such time signatures are often called "irrational" time signatures, although that's a terrible name. Just as one fourth of a whole note is a quarter note—hence 4 in the signature—and one eighth of a whole note is an eight note—hence 8 in the signature—an eighth-note triplet is one twelfth of a whole note. These time signatures are deeply unfamiliar to most people, and many performers take offense at them. Be warned.
Comment: Are you sure you don't mean 'irritational'..?
Answer: I agree with @Tim that figuring out where the emphasis falls is definitely key. The other key question is what is supposed to come after those 29 notes — maybe there is a plausible remainder of the 3rd measure. Or maybe the first 5 triplets were an anacrusis to the first measure?
The kind of music I can think of where 29 triplets could constitute a complete section of a song would be Eastern European or Middle Eastern folk dances, where people settle for odd meters as a rough approximation of the true underlying pulse.
So if you are e.g. an Armenian Jazz composer, feel free to write a measure in 29/12th time. If you see yourself in more of a traditional Western European tradition, odds are that your melody in reality has a more conventional rhythmic arrangement, and just just have not quite found the right groove for it yet.
Answer: I don't know if that can help:

30 notes, here, in this Nocturne op. 15 n°2 by Chopin
Comment: The number 30 seems more feasible than 29, considering triplets.


Using parses Facebook login api, results in current user null

Question: I am using parse to crate a simple demo site that allows users to login/signup using their Facebook account.
the login returns success, i also get correct user name
i also see the database get populated with the facebook acount data
but back at app.js: Parse.User.current() is null
Jvascript on client side (index.html)

Comment: I encounter the same issue with [Parse platform](http://blog.parse.com/announcements/javascript-sdk-now-supports-facebook-login/).. please help
Comment: I found related question, tell me if it helps [Facebook user to Parse.com](http://stackoverflow.com/questions/30881347/facebook-user-to-parse-com)
Comment: Or you can try use [parse-facebook-user-session](https://github.com/ParsePlatform/parse-facebook-user-session) as a middleware
Comment: As @NaBr metioned [parse-facebook-user-session](https://github.com/ParsePlatform/parse-facebook-user-session), there is an example [Parse-Facebook-OAuth-login-example](https://github.com/ssk7833/Parse-Facebook-OAuth-login-example) to check.
Answer: There seems to be a bug with Parses session handling with facebook.
It might not be a solution, but it is a workaround for the meantime,
you can use session become with the facebook token you acquired should do
the trick


Output more than one excel/csv file from a class. OOP. Class Inheritance

Question: I am getting a AttributeError as follows:
self.filtered_df.to_excel(self.output_filepath, index=False)
AttributeError: 'tuple' object has no attribute 'to_excel'

I am inheriting a class for another class I am developing, currently the inheritance allows me to output one excel file, can I change the method in this class to allow me to output more than one excel file in the new class I am developing?
Here is the class, inherited:
class ReportQueryCommand(LogCommand):
    """Performs reports through a ReportQueryStrategy instance.

    It is possible to overwrite existing queries; this means that it is possible
    to perform subsequent filters by launching multiple commands having
    key_input = strategy.name.

    Attributes:
        state: DatasetState containing so-far computed DataFrames.
        strategy: defines how to perform the query.
        filepath: optional. Defines where to save the queried DataFrame.
        key_input: optional (None if df_to_filter is not None).
            Defines a key that allows to access a DataFrame in the State.
        df_to_filter: optional (None if key is not None).
            DataFrame to apply the query on.
    """

    def __init__(self,
                 strategy: ReportQueryStrategy,
                 base_path: Optional[str] = None,
                 key_input: Optional[str] = None,
                 key_output: Optional[str] = None,
                 df_to_filter: Optional[pd.DataFrame] = None,
                 filepath: Optional[str] = None,
                 directory_path: Optional[str] = None,
                 write_output: bool = True):
        super().__init__(base_path=base_path,
                         directory_path=directory_path,
                         copy_before_update=False,
                         write_output=write_output)
        self.state = DatasetState()
        self.strategy = strategy
        self.filepath = filepath

        self.key_input = key_input
        self._key_output = key_output
        self.df_to_filter = df_to_filter
        self.filtered_df = None

    @property
    def _output_file(self) -> str:
        return self.strategy.output_filename

    def write_to_file(self):
        if self.filtered_df is None:
            raise ValueError("Missing computed dataframe")
        self.filtered_df.to_excel(self.output_filepath, index=False)

    @property
    def key_output(self) -> str:
        # first scenario: key was defined
        if self._key_output is not None:
            return self._key_output
        # second scenario: key was not defined, by default,
        # concatenate key_input and strategy
        strategy_output_name = self.strategy.output_name
        if self.key_input is not None:
            return f"{self.key_input}-{strategy_output_name}"
        # WCS: no key defined, just assign the strategy key
        return strategy_output_name

    def execute(self, output_from_previous: Any = None, **kwargs) -> Any:
        self.filtered_df = self.strategy.transform(key=self.key_input,
                                                   df=self.df_to_filter)
        self.state.query_reports[self.key_output] = self.filtered_df
        super().execute(output_from_previous=output_from_previous, **kwargs)

As you can see here the method I need to update is 'def write_to_file(self):'
Here is snippets of the relevant code in development to show where this problems 'could be occuring'. The following bits of code below are relevant, this might need to be updated to allow me to output two excel files or more:
class TtestStrategy(ReportQueryStrategy):
    """
    """

    @staticmethod
    def _strategy_key():
        return 't-test', 'fisher-test'

    def __init__(self,
                 query_name: Optional[str] = None,
                 reference_query: str = None,
                 sample_query: str = None,
                 alpha: float = 0.05,
                 chemical_key: str = 'chemical',
                 plate_key: str = 'plate',
                 value_key: str = 'processed_relative_fp',
                 group_column: str = 'Lot',
                 return_pivoted: bool = True):
        super().__init__(query_name=query_name)
        self.pvalues = []
        self.alpha = alpha

        self.chemical_key, self.plate_key, self.value_key, self.reference_query, self.sample_query = (chemical_key,
                                                                                plate_key,
                                                                                value_key,
                                                                                reference_query,
                                                                                sample_query)
        self.group_column = group_column
        self.return_pivoted = return_pivoted

    def fishers_method(self, pvalues) -> tuple[bool, float, float, float]:
        pvalues = [item for item in pvalues if not pd.isnull(item)]
        comb_z, comb_pval = stats.combine_pvalues(pvalues, method="fisher")

        k = len(pvalues)
        mean_FDR = (self.alpha * (k + 1)) / (2 * k)

        if comb_pval > mean_FDR:
            decision = False
        else:
            decision = True

        return decision, comb_z, comb_pval, mean_FDR

    def transform(self,
                  key: Optional[str] = None,
                  df: Optional[pd.DataFrame] = None) -> tuple[Any, DataFrame]:
        counter_nosig = 0
        counter_sig_st_t = 0
        pval_store_st_t = {}
        pval_store_st_t_dec = {}
        pval_store_st_t_val = {}
        pval_store_st_t_val_adj = {}
        pval_store_norm_A = {}
        pval_store_norm_B = {}
        var_store_A = {}
        var_store_B = {}
        pval_store_lev_bart = {}
        decisions = []
        st_pval_arr = []

        df = super().transform(key=key, df=df)

        df = df.loc[(df[self.group_column] == self.reference_query) | (df[self.group_column] == self.sample_query)]
        df_i = df.filter(['plate', 'chemical', 'processed_relative_fp'], axis=1)
        df_i = df.pivot(columns='plate', values='processed_relative_fp', index='chemical')
        df_i.index.name = None
        df_i.columns.name = ''

        plates = {exps: {"processed_relative_fp": series}
                  for exps, series in df_i.to_dict("series").items()}
        chem_order = list(df['chemical'].unique())
        for chem in chem_order:
            if chem != 'empty':
                pool = []
                sample_l = []

                for q in [self.reference_query, self.sample_query]:
                    sample = pd.Series([sample for sample in plates])
                    sample = sample[sample.str.contains(q)]

                    for s in sample:
                        sample_l.append(s)

                        record = plates[s]

                        if record['processed_relative_fp'] is not None:
                            rel_fp = record['processed_relative_fp']

                            lot = s.split("_")[1]
                            cell = s.split('_')[2]
                            rep = s.split("_")[4]

                            val = rel_fp[chem]

                            pool.append({"chems": chem, "lot": lot, "cell": cell, "replicate": rep,
                                         "key": chem + "::" + lot + "::" + rep + "::" + cell, "value": val})

                pool = pd.DataFrame(pool)

                massage = []
                averages = []
                sort_lots = list(pool['lot'].unique())
                for lot in sort_lots:
                    value = list(pool[pool.lot.eq(lot)]['value'].dropna())
                    averages.append(np.mean(np.array(value)))
                    massage.append(value)

                averages = np.array(averages)
                min_ = np.nanmin(averages)
                max_ = np.nanmax(averages)
                pos_min_ = np.where(averages == min_)[0][0]
                pos_max_ = np.where(averages == max_)[0][0]
                perc_diff = (max_ - min_) * 100

                fvalue_st_t, pvalue_st_t = stats.ttest_ind(*massage, equal_var=False)

                st_pval_arr.append(pvalue_st_t)
                st_pval_array = np.asarray(st_pval_arr)
                mask = np.isfinite(st_pval_array)
                st_t_t_pval_adj = np.empty(st_pval_array.shape)
                st_t_t_pval_adj.fill(np.nan)
                rej_st_t, st_t_t_pval_adj[mask], _, _ = sm.stats.multipletests(st_pval_array[mask], method='fdr_bh')

                for v in st_t_t_pval_adj:
                    float(v)
                    pval_store_st_t_val_adj[chem] = v

                for z in rej_st_t:
                    float(z)

                if len(massage[0]) >= 3:
                    test_stat_norm_A, pvalue_norm_A = stats.shapiro(np.array(massage[0]))
                    if pvalue_norm_A < 0.05:
                        pval_store_norm_A[chem] = 'No'
                    else:
                        pval_store_norm_A[chem] = 'Yes'
                else:
                    pval_store_norm_A[chem] = 'Not enough data'

                if len(massage[1]) >= 3:
                    test_stat_norm_B, pvalue_norm_B = stats.shapiro(np.array(massage[1]))
                    if pvalue_norm_B < 0.05:
                        pval_store_norm_B[chem] = 'No'
                    else:
                        pval_store_norm_B[chem] = 'Yes'
                else:
                    pval_store_norm_B[chem] = 'not enough data'

                var_stat_A = stats.variation(np.array(massage[0]))
                var_stat_B = stats.variation(np.array(massage[1]))

                stat_lev_bart, pvalue_lev_bart = stats.levene(*massage, center='mean')

                pval_store_st_t[chem] = pvalue_st_t

                pval_store_st_t_val[chem] = pvalue_st_t

                var_store_A[chem] = var_stat_A
                var_store_B[chem] = var_stat_B

                pval_store_lev_bart[chem] = pvalue_lev_bart

                if pvalue_st_t < 0.05:
                    pval_store_st_t[chem] = 'diff'
                else:
                    pval_store_st_t[chem] = 'same'

                if v > 0.05:
                    pval_store_st_t_dec[chem] = 'same'

                if v < 0.05 and perc_diff > 0.0:
                    pval_store_st_t_dec[chem] = 'diff'
                    counter_sig_st_t += 1

                else:
                    counter_nosig += 1

        decisions.append(pval_store_st_t)
        decisions.append(pval_store_st_t_dec)
        decisions.append(pval_store_st_t_val)
        decisions.append(pval_store_st_t_val_adj)
        decisions.append(pval_store_norm_A)
        decisions.append(pval_store_norm_B)
        decisions.append(var_store_A)
        decisions.append(var_store_B)
        decisions.append(pval_store_lev_bart)
        decisions = pd.DataFrame(decisions)
        decisions = decisions.T
        decisions.columns = [
            f'Welchs t-test result for lot {self.reference_query} v lot {self.sample_query}',
            'Welchs t-test considering Multi-test Correction',
            'Welchs t-test pvalue unadjusted',
            'Welchs t-test pvalue adjusted',
            f'are lot {self.reference_query} chemicals normally distributed?',
            f'are lot {self.sample_query} chemicals normally distributed?',
            f'lot {self.reference_query} variance',
            f'lot {self.sample_query} variance',
            'levenes statistic']
        decisions_before_filter = decisions.copy()
        decisions_before_filter.reset_index(inplace=True)
        decisions_before_filter.rename(columns={'index': 'chemicals'}, inplace=True)
        decisions = decisions.loc[(decisions['Welchs t-test pvalue adjusted'] < self.alpha)]

        decisions.reset_index(inplace=True)
        decisions.rename(columns={'index': 'chemicals'}, inplace=True)
        decisions.sort_values(by=['Welchs t-test pvalue adjusted'], inplace=True)

        decisions_before_filter = decisions_before_filter.filter(items=['chemicals', 'Welchs t-test pvalue adjusted'])
        decisions_before_filter = decisions_before_filter.sort_values(by=['Welchs t-test pvalue adjusted'])

        results_fishers = self.fishers_method(decisions_before_filter['Welchs t-test pvalue adjusted'].tolist())
        results_fishers_df = pd.DataFrame(results_fishers,
                                          index=['decision',
                                                 'combined z-score',
                                                 'combined p-value',
                                                 'meanFDR'])
        results_fishers_df = results_fishers_df.T
        results_fishers_df['k'] = len(decisions_before_filter.dropna())
        results_fishers_df.insert(loc=0, column='comparison', value=(str(self.reference_query + '-' + 'vs'
                                                                         + '-' + self.sample_query)))

        return decisions, results_fishers_df

See all the information above
Answer: The error is telling you that filtered_df is NOT a pandas.DataFrame.
It's a tuple. In fact your TtestStrategy's transform method returns the tuple:
    return decisions, results_fishers_df

If you change your code to:
def execute(self, output_from_previous: Any = None, **kwargs) -> Any:
    _ignored, self.filtered_df = self.strategy.transform(key=self.key_input,
                                               df=self.df_to_filter)
    self.state.query_reports[self.key_output] = self.filtered_df
    super().execute(output_from_previous=output_from_previous, **kwargs)

then you shouldn't see that AttributeError anymore.
Comment: @Bakuiru, this wasn't the error. The error was
'''
AttributeError: 'tuple' object has no attribute 'to_excel'
'''

I traced it back to the method 'def wrtie_to_file(self)' in the ReportQueryCommand class
Comment: @Paddy_1916 The problem is the same. You are setting `filtered_df` to a tuple and then you are trying to call `pandas.DataFrame` methods on it. If you try my suggestion you will see that error disappear (assuming that's the only place where `filtered_df` is set).


Como achar a acurácia entre duas colunas de um data frame?

Question: Tenho duas colunas do mesmo aquivo csv, uma aquilo que foi escrito e a segunda aquilo que deveria ter sido escrito. Ai tenho três dúvidas 1º Como encontro a Acurácia entre elas (ou seja quanto mais as linhas da coluna 1 for parecida com a mesma linha da coluna 2 melhor é a taxa de acerto acurácia), 2º como acho a linha com maior precisão e a com menor precisão, 3º como remover as linhas com menor taxa de acerto ?
import pandas as pd
relat_int = pd.read_csv
relat_int.head()

quando eu teno usar .score() aprece esse erro:
AttributeError                            Traceback (most recent call last)
<ipython-input-13-d63a2ac83383> in <module>
      4 e = relat_int['Intenções Reais/Esperadas']
      5
----> 6 relat_int.score(r, e)

~\anaconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
   5272             if self._info_axis._can_hold_identifiers_and_holds_name(name):
   5273                 return self[name]
-> 5274             return object.__getattribute__(self, name)
   5275
   5276     def __setattr__(self, name: str, value) -> None:

AttributeError: 'DataFrame' object has no attribute 'score'

Comment: Coloque um trecho do csv para facilitar o entendimento. O que você considera a acurácia entre duas colunas? Qual método `score` você quer usar, o DataFrame não possui esse método, por isso está recebendo esse erro.
Comment: Obrigado Damião.

Seria assim:

Coluna A   //    Coluna B
===========
Linha 1 da Coluna A = Bola     ///
Linha 1 da Coluna B = Sola    ///

Linha 2 da Coluna A = Rua    ///
Linha 2  da Coluna B = Rua  ///

Nesse caso o programa deveria perceber que a linha um está com resultado diferente e linha dois com resultado igual, ou seja a taxa de acerto(acurácia) é de 50%.

Expliquei melhor ? É que eu sou novo na programação....
Answer: Considerando um dataframe no formato a seguir, conforme seu exemplo:
>>> df
   ColA  ColB
0  Bola  Sola
1   Rua   Rua

E você queira contar quantas linhas tem os valores das colunas A e B iguais, você poderia usar o numpy:
import numpy

total_iguais = numpy.sum(df['ColA'] == df['ColB'])
total = len(df)
acuracia = total_iguais / total

print(f'Acuracia: {acuracia}')

Agora caso queira saber quão próximas as duas palavras são (Bola e Sola são diferentes por apenas uma letra), você teria que adicionar alguma lógica de comparar cada caracter ou então usar algum algoritmo de similaridade, como o SequenceMatcher:
import difflib
s = difflib.SequenceMatcher(None, 'Bola', 'Sola')
print(s.ratio()) # 0.75


What is "musicality" in the context of dancing?

Question: This question made me remember a question of my own.
I was told several times (even by girls who claimed they were musicians) that my dancing is very musical.
Now, I am not a specialist about music, or a dedicated dancer or anything. I am just a regular guy doing my best - as an occasional hobby. I am sure that just being on the beat is not musicality - but maybe just the first stone in the foundation of musicality.
So, long story short, what is musicality when evaluating a person's dancing?
Note: the way I understand it, musicality is different from playfulness, being unexpected, creative... But maybe it intersects with them?
Comment: Meanwhile, I'm voting to close this question because it isn't really about [the topics covered here](https://music.stackexchange.com/help/on-topic). Feel free to read up on them, stick around, and ask other questions!
Comment: Not sure we can answer questions about dancing here. To me musicality in music is putting expression into every note, as opposed to just playing the right note at the right time at the right volume.
Comment: To paraphrase [somebody](https://en.wikipedia.org/wiki/Writing_about_music_is_like_dancing_about_architecture), the "musicality" of dancing is like the "danceability" of architecture. ;-) You might have to ask the commenters to explain, since they *could* be using "musicality" as a sort of metaphor, to mean that your dancing is very expressive. But more likely they simply mean that you show a good awareness of, or even aesthetically pleasing interpretation of, the music.
Comment: @AndyBonner: I knew that quote, but I did not associate it with my question until you made it obvious :)) Very good one. The problem is that I asked what they meant, but none of them was able to explain :(
Comment: @AndyBonner: The topic is definitely NOT on the forbidden topics. It is still about music (and feeling the music), even if at the edge of the subject.
Comment: I respectfully disagree; it's not so much that it's one of the "if-it's-not-about" topics (which isn't an exhaustive list); it's that it isn't one of the "if-it-is-about" topics. This is ultimately a question about language. (Though even if you asked it on the "English" SE, or the more lenient "English Language Learners" one, the response would probably be "that's not a standard usage; you'd have to ask them what they meant." The fact that they can't explain themselves says something about the ineffability of this whole concept...
Answer: Musicality may refer both to the ability to express music as well as the ability to understand and feel music (measured by some aesthetic metric). In terms of dancing of course the first meaning is void, but less so the other two: Musicality in dancing refers to the ability to understand and feel music and to translate or express that understanding and feeling into and through body motion. It is very much a vague term, linked to many social assumptions and aesthetics. If you want to get more involved, this is a topic in music and music psychological research, so you can familiarize yourself with common models and theories. But there is no simple true answer to that question.
Comment: Thank you for your answer. I am not looking for an absolute truth, I just want to understand better the feedback that I occasionally receive.