Invocar método da classe filha em C++

Question: Tenho uma classe/estrutura pai e uma classe/estrutura filha em C++. A classe pai define um método, e a classe filha sobrecarrega esse método.
Exemplo trivial:
struct Pai {

    void imprimir() {
        std::cout << "Classe pai" << "\n";
    }

};

struct Filha : Pai {

    void imprimir() {
        std::cout << "Classe filha" << "\n";
    }

};

Quero declarar uma variável do tipo Pai, essa variável pode ser inicializada com uma instãncia de Pai, ou de qualquer outra classe que herda a mesma:
Pai obj = Filha{};

Meu problema ocorre ao invocar o método dessa instancia. Em linguagens como Java ou C#, é de se esperar que o método invocado seja o pertencente a instancia da classe armazenada na variável "obj", ou seja, deveria imprimir "Classe filha".
Mas em C++ o que ocorre é que o programa invoca o método da mesma classe que a variável é declarada, invoca o método da classe Pai, imprimindo "Classe pai".
Há algo que eu possa fazer para que ao invocar o método "imprimir", seja invocado o método declarado na classe filha?
Aqui tem o código rodando para melhor visualização.
Answer:
Há algo que eu possa fazer para que ao invocar o método "imprimir", seja invocado o método declarado na classe filha?
Pai obj = Filha{};

Sim, mas é complicado.
Quando vc cria um objeto Filho e guarda ele em uma variável Pai, toda informação inerente de Filho é perdida. Às vezes, quando isso é desejável, pode-se usar classes abstratas ou funções virtuais em Pai, selecionando pontos de sobrecarga, para que então Pai seja composto por membros de Filho:
struct Pai {
    virtual void imprimir()=0;
};

struct Filha : Pai {
    void imprimir() override {
        std::cout << "Classe filha" << "\n";
    }
};

//...

Pai* obj = new Filha{};
obj->imprimir();

Essa técnica é conhecida como type erasure e é parte fundamental de alguns componentes da STL, como std::function. Funções virtuais vem com uma penalidade de performance considerável e não são sempre a melhor solução para toda situação, por isso que essa funcionalidade não ocorre automaticamente como em línguas puramente orientadas a objetos (Java, C#, etc).
Através de templates é possível que Pai tenha informações sobre Filho sem recorrer a funções virtuais com uma técnica chamada CRTP (Curiously Recurring Template Pattern).
template <typename TipoFilho>
struct PaiCRTP {
    void imprimir() {
        auto filho = static_cast<TipoFilho*>(this);
        filho->imp();
    }
};
struct FilhaCRTP : PaiCRTP<FilhaCRTP> {
    void imp() {
        std::cout << "Classe filha" << "\n";
    }
};
template <typename TipoFilho>
void imprime(PaiCRTP<TipoFilho>& pai) {
    pai.imprimir();
}

int main()
{
    FilhaCRTP filha;
    imprime(filha);
}

Nessa implementação, Pai tem a informação sobre Filho e pode invocar métodos de Filho. Filho herda Pai usando Filho como template. A função imprime é necessária para que exista um template genérico para todas combinações de Pai e Filho.
Answer: Você está tentando fazer herança em um tipo por valor, isso não acontece como espera. Para fazer polimorfismo em tipo por valor precisa usar um mecanismo de template ou algo mais complexo, mas nem tente sem dominar muito todos aspectos da programação em C++, como a memória se comporta nessas situações. Quase sempre esse tipo de polimorfismo é um erro, e só parece ser certo em um exemplo tão artificial onde os nomes dos tipos nem possuem significado.
Programar orientado a objeto é dar significado para as coisas, quando não se dá nomes, não tem significado e não se usa OOP do jeito certo, nunca.
Então para fazer igual Java ou C# precisa fazer isso com um objeto por referência, porque é assim que essas linguagens fazem.
E precisa dizer que o método é virtual porque sem isso ele o polimorfismo não é ativado, igual ao C# (não é igual ao Java porque ele é ativado sempre, o que é um erro da linguagem).
Então teria que fazer algo assim:
#include <iostream>
using namespace std;

struct Pai {
    virtual void imprimir() {
        cout << "Classe pai\n";
    }
};

struct Filha : Pai {
    void imprimir() override {
        cout << "Classe filha\n";
    }
};

int main() {
    Pai *obj = new Filha{};
    obj->imprimir();
    delete obj;
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Mas não estou recomendando criar algo real dessa forma, estou apenas demonstrando como o mecanismo funcionaria se ele fosse o adequado. Nem é a melhor forma de escrever esse código.
Comment: Eu estou particularmente preocupado com o método destrutor, é possível declarar esse "override" no destrutor da classe Filha também?
Comment: Isso é outra questão, mas pode sim, e em muitos casos deve se ele é necessário. Só tenho medo de um destrutor em um tipo por valor.
Comment: Bom, "smart pointers" implementam destrutores apesar de serem um tipo por valor, não? O exemplo que eu dei foi utilizado apenas para não poluir a pergunta.
Comment: Por isso que eu tenho medo e não que seja proibido. É muito raro ser útil, quase sempre será uma invenção sem a pessoa entender porque está fazendo aquilo. Os *smart pointer*, não devem ser herdados. O problema da programação é que tudo pode ser composto, o que é lindo sozinho não funciona com outras coisas. Junte polimorfismo em destrutor em tipo que deveria ser por valor mas o objeto foi criado com referência para funcionar...

Invocar método da classe filha em C++


localhost not showing /import

Question: If I navigate to http://localhost:8080/import I am taken back to the index page.
If I navigate to http://localhost:8080/?q=import I am take to the import page.
If I navigate to http://localhost:8080/admin I am taken to the list of admin options.
The webserver for localhost is the default one that comes with Phpstorm (in ubuntu 14.04), which is the built in webserver that comes with php5.4 and above.
When deployed to a remote server /import works.
What might cause this issue?
Comment: What happens if you visit `http://localhost:8080/admin/config/search/clean-urls`, there may be some errors present, etc.
Comment: No errors that I can see, http 200 everywhere. I just get the page.
Comment: Anything point the way on the status report page? Any errors in watchdog or the server log?
Comment: nothing on the status report page. nothing in the watchdog log. I'm running through Phpstorm, and that isn't reporting any errors.
Comment: Have you modified your .htaccess file? Try loading fresh one from Drupal just to test.
Answer: Just to eliminate a possible cause of your problem, and assuming your web server is Apache: make sure the mod_rewrite module is enabled. If it is not, then enable it and restart Apache.
To verify this, open the file httpd.conf inside your Apache installation folder and find the line starting with AllowOverride:
If that line looks like AllowOverride None
Then:

edit it to look like so: AllowOverride All
and afterwards restart Apache.

If you're using PHP Storm (as mentioned now in the further edited question), it might help to try what is documented in Disabling clean URLs. Here is a quote about that page:

It's possible that a Drupal site that was once configured to run with clean URLs later on stops doing so. After that, almost all content is inaccessible, because the paths being generated are not supported by the hosting platform.
Comment: My webserver is the one that comes with phpstorm. This is the built in webserver that comes with php5.4 and above.
Comment: Thx for extending your question! Refer to my updated answer now also. Does that help?
Comment: Great! Would you mind adding a small extra comment please with a few more details about your specific case?

localhost not showing /import


Unable to convert Javascript object to Java Model

Question: My Spring controller and client side Javascript code are as follows and for some reason the Javascript object is unable to reach the Spring controller in the Object form. My Controller code is as follows:
@RequestMapping(value = "/addRating", method = RequestMethod.POST, headers = "Accept=application/json")
public EmployeeRating addRating(@ModelAttribute("employeeRating") EmployeeRating employeeRating) {
    if(employeeRating.getId()==0)
    {
        employeeRatingService.addRating(employeeRating);
    }
    else
    {
        employeeRatingService.updateRating(employeeRating);
    }

    return employeeRating;
}

My Javascript code below:
$.ajax({
          url: 'https://myrestURL/addRating',
          type: 'POST',
          dataType: 'json',
          data: {
              'id':5,
              'name': 'Name',
              'rating': '1'
          },
          contentType: 'application/json; charset=utf-8',
          success: function (result) {
             // CallBack(result);
             window.alert("Result: " + result);
          },
          error: function (error) {
              window.alert("Error: " + error);
          }
      });

The EmployeeRating object in Java has id, name and rating fields so there's no mismatch.

Updating the model class
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/*
 * This is our model class and it corresponds to Country table in database
 */
@Entity
@Table(name="EMPLOYEERATING")
public class EmployeeRating {

@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
int id;

@Column(name="name")
String name;

@Column(name="rating")
long rating;

public EmployeeRating() {
    super();
}
public EmployeeRating(int i, String name,long rating) {
    super();
    this.id = i;
    this.name = name;
    this.rating=rating;
}
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public long getRating() {
    return rating;
}
public void setRating(long rating) {
    this.rating = rating;
}

}

Comment: Show the `EmployeeRating` class.
Comment: Note that in Spring, it's clearer to use the `consumes` attribute on the annotation rather than manually specifying the header value.
Comment: added the EmployeeRating class
Answer: contentType is the type of data you're sending, so application/json; The default is application/x-www-form-urlencoded; charset=UTF-8.
If you use application/json, you have to use JSON.stringify() in order to send JSON object.
JSON.stringify() turns a javascript object to json text and stores it in a string.
$.ajax({
      url: 'https://myrestURL/addRating',
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify({
          'id':5,
          'name': 'Name',
          'rating': '1'
      }),
      contentType: 'application/json; charset=utf-8',
      success: function (result) {
         // CallBack(result);
         window.alert("Result: " + result);
      },
      error: function (error) {
          window.alert("Error: " + error);
      }
  });


Integração entre Spring e JPA

Question: Recentemente comecei a estudar um dos frameworks mais fantásticos que já conheci, o Spring.
Sempre costumo avançar bem nos meus estudos, já estou estudando a integração do Spring com ferramentas de acesso a dados. Estou tentando integrar o Spring com o Hibernate e JPA.
A configuração foi realizada com sucesso, está conseguindo instanciar o EtityManagerFactory e o EntityManager normalmente. O problema é que não estou conseguindo salvar as informações no banco de dados e estou com problemas nas transações que devem ser realizadas pelo Spring.
O maior problema é o seguinte: Quando anoto os métodos dos meus DAOs com @Transactional uma exceção é lançada. Segue a exceção lançada:

Ago 12, 2014 3:43:41 PM
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry
  destroySingletons Informações: Destroying singletons in
  org.springframework.beans.factory.support.DefaultListableBeanFactory@779cbd8d:
  defining beans
  [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,personDAO,personService,entityManagerFactory,dataSource,jpaVendorAdapter,jpaDialect,dbUtil,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0];
  root of factory hierarchy Ago 12, 2014 3:43:41 PM
  org.springframework.orm.jpa.AbstractEntityManagerFactoryBean destroy
  Informações: Closing JPA EntityManagerFactory for persistence unit
  'springJpa' Exception in thread "main"
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'personDAO' defined in file
  [/home/arkson/workspace/web/Spring_Jpa/build/classes/br/com/springjpa/PersonDAO.class]:
  Initialization of bean failed; nested exception is
  java.lang.IllegalAccessError  at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
    at
  org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
    at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
    at
  org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
    at
  org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
    at
  br.com.springjpa.TestSpringHibernateJpa.main(TestSpringHibernateJpa.java:9)
  Caused by: java.lang.IllegalAccessError   at
  net.sf.cglib.core.ClassEmitter.setTarget(ClassEmitter.java:45)    at
  net.sf.cglib.core.ClassEmitter.(ClassEmitter.java:37)   at
  net.sf.cglib.core.KeyFactory$Generator.generateClass(KeyFactory.java:165)
    at
  net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
    at
  net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
    at net.sf.cglib.core.KeyFactory$Generator.create(KeyFactory.java:145)
    at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:117)     at
  net.sf.cglib.core.KeyFactory.create(KeyFactory.java:108)  at
  net.sf.cglib.core.KeyFactory.create(KeyFactory.java:104)  at
  net.sf.cglib.proxy.Enhancer.(Enhancer.java:69)    at
  org.springframework.aop.framework.Cglib2AopProxy.createEnhancer(Cglib2AopProxy.java:228)
    at
  org.springframework.aop.framework.Cglib2AopProxy.getProxy(Cglib2AopProxy.java:170)
    at
  org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:112)
    at
  org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:476)
    at
  org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:362)
    at
  org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:407)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1461)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    ... 11 more

Detalhe: Os meus DAOs estão anotados com @Repository com segue:
@Repository
public class PersonDAO {

    @PersistenceContext
    private EntityManager entityManager;

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public EntityManager getEntityManager() {
        return entityManager;
    }

    @Transactional
    public void save(Person person) {
        System.out.println("saving...");
        this.entityManager.persist(person);
        System.out.println("saved...");
    }

}

E segue também o xml do spring:
<?xml version="1.0" encoding="UTF-8"?>
<beans ...>

    <context:annotation-config />
    <context:component-scan base-package="br.com.springjpa" />

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
        <property name="persistenceUnitName" value="springJpa" />
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
        <property name="jpaDialect" ref="jpaDialect" />
    </bean>

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/springbase" />
        <property name="username" value="root" />
        <property name="password" value="rooot" />
    </bean>

    <bean id="jpaVendorAdapter"
        class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <property name="database" value="MYSQL" />
        <property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
    </bean>

    <bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />

    <bean id="dbUtil" class="br.com.springjpa.DbUtil">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
        <property name="dataSource" ref="dataSource" />
        <property name="jpaDialect" ref="jpaDialect" />
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager" />

</beans>

Comment: Cara, `Caused by: java.lang.IllegalAccessError at net.sf.cglib.core.ClassEmitter.setTarget(ClassEmitter.java:45)`. Parece incompatibilidade de biblioteca... Você está usando maven? Pode postar seu `pom.xml`? Chute alto: problemas com versão do `cglib` e `asm` (fonte: http://sagarkarnati.wordpress.com/2011/09/13/java-lang-illegalaccesserror-at-net-sf-cglib-core-classemitter-settargetclassemitter-java47/)
Comment: Não estou usando maven. Todas as minhas biblioteas estão no diretório WEB-INF/bin.
Comment: Anthony Accioly, era isso mesmo. Baixei as versões mais recentes das bibliotecas e deu tudo certo, foi resolvido.
Answer: Transformando meu comentário em resposta.
Pelo stack trace:
 Caused by: java.lang.IllegalAccessError at
     net.sf.cglib.core.ClassEmitter.setTarget(ClassEmitter.java:45) at
     net.sf.cglib.core.ClassEmitter.(ClassEmitter.java:37) at
     net.sf.cglib.core.KeyFactory$Generator.generateClass(KeyFactory.java:165) at
     net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25) at
     net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216) at net.sf.cglib.core.KeyFactory$Generator.create(KeyFactory.java:145) at
     net.sf.cglib.core.KeyFactory.create(KeyFactory.java:117) at
     net.sf.cglib.core.KeyFactory.create(KeyFactory.java:108) at
     net.sf.cglib.core.KeyFactory.create(KeyFactory.java:104) at net.sf.cglib.proxy.Enhancer.(Enhancer.java:69) at
     // ...

Parece que há alguma incompatibilidade de bibliotecas. Em especial, conforme esse artigo, parece que os culpados desse tipo de exceção costuam ser o cglib e o asm. Tente atualizar essas bibliotecas conforme dependências comuns do Spring e Hibernate.

Integração entre Spring e JPA


what does "go down a break" mean?

Question: http://www.newyorker.com/online/blogs/shouts/2013/09/federers-last-stand.html
I'm not familiar with tennis so I don't know what he's talking about here with this.
"goes down another break ?"
A wild misfire, and Roger Federer goes down another break in the second set.
Answer: It means to lose a game that one served, and then to be behind one's opponent in terms of number of breaks won. To win a set (without having to resort to a tie-break), one needs to break one's opponent at least once, so to go down a break is a significant setback.
e.g. in the following passage, Smith goes down a break. Smith serves the first game:

Smith 1-0 Jones
Smith 1-1 Jones
Smith 1-2 Jones
Smith 1-3 Jones
Smith 2-3 Jones
Smith 3-3 Jones

Smith is serving the 3rd game, but loses it to Jones. Jones therefore breaks Smith and is one break down. Smith then wins the 6th game (on Jones's serve) - he breaks Jones back. However, Jones is not "a break down", because he broke Smith earlier, so they are simply level again.
Comment: Just a minor correction - you don't actually have to break your opponents serve to win a set - you could win the set in a tie-break 7 games to 6.
Comment: Funny how that works isn't it? "Wait! I don't want to confuse them or clutter up the answer...but...it's important...hmm..". I usually error on the side of TMI myself but still a good answer either way.
Comment: He's losing that set, yes.
Comment: @AndySmith Welcome to Sports SE. If this post answers your question, feel free to accept it.
Comment: @jamauss Very true; as a matter of fact I said as much in my original answer, but decided (unwisely?) to edit out the reference to the tie-break, as I thought it would merely confuse matters (bearing in mind the original question). I'll put it back in.
Answer: "In tennis, having the right to "serve" (put in play) the ball is a decided advantage, so players alternate serves between games, sharing this advantage. Between two almost evenly matched players, whoever serves will win most games, by "holding serve." But in the typical "set," the better of the two players will win an occasional game while the other person is serving, a result that is known as "breaking serve." [The person whose serve is broken is said to "go down a break."]
This, together with the fact that he or she is serving half the time and (presumably) holds all serves, means that the slightly better player will likely win the set by getting a majority of the games with a score of say, 6-4. If a player both holds serve and breaks serve consistently, the result could be a more lop-sided 6-0 tally that clearly demonstrates who is the better player."
Except for the boldfaced part in brackets, this tennis analogy was used years ago in a piece of mine on the stock market.
Comment: If this were a piece relevant to sports, I think it would be fine to link to it.  The fact that it's not relevant in any way is why I object: linking to it doesn't add any weight to the argument (it's not a tennis expert's article, or similar).  That's the point of citing.  Honestly if you'd cited some random financial expert's piece, it would just be a bad answer, just like if I cited a bit from Chris Rock in a football answer: there's no reason to believe what he says is relevant to football.
Comment: I would remove the last sentence; it is unnecessary to the answer and feels like self-promotion.
Comment: If you're quoting yourself, you do not need to cite sources (it's yourself).  If you're quoting someone else, cite them directly - but either way this feels like self promotion to me the way it's written.
Comment: @Joe: I took out the "my's" in the last sentence to reduce the promotion, and therefore feel an even greater need for attribution.
Comment: Um, that makes it worse from my point of view (and from the SE rules).  Linking to a piece of yours and not saying it's yours is worse than linking and saying it's yours.
Comment: All things considered, there's no way to deny that the inclusion of the link is a little bit of self-promotion. I'm not going to edit or delete the answer here this time, and I appreciate Tom's contributions here on SE.Sports. I will leave it up to him to decide what state to leave this answer in. In the future I'd advise submitting answers to this [old] question by just submitting your own original answer and only link to articles/pages from authoritative or canonical sources relative to the sport, rather than a financial page, regardless of who the author is.

what does "go down a break" mean?


InStr VBA differentiate between lower and upper character

Question: I am using the following vba code to check if a password has an upper case letter
'See if there is an upper case
    For i = 65 To 90
        If (InStr(1, Me.Password, Chr(i))) Then
            hasUpper = True
            Exit For
        End If
    Next i

But it looks like for a password like "asd12" has Upper is set to true because A is the same as a
Is there a way to use the Instr function so that it can differentiate between upper and lower characters?
Answer: If this is just about upper-case characters, and you don't want to take on regex, an easy approach (which is somewhat suboptimal performance-wise, but a password check taking an extra millisecond probably won't hurt anyone) is checking if the lower-case string is equal to the string (in which case there won't be uppercase characters).
'See if there is an upper case
If StrComp(Me.Password, LCase(Me.Password), vbBinaryCompare) <> 0 Then hasUpper = True


JSLint error - XML Serializer

Question: The code works fine but when i validate using JSLint it gives me the following error
var serializer = new XMLSerializer();

JSLint error : XMLSerializer was used before it was defined.
var serializer = window.XMLSerializer();

The above code works fine in IE and Firefox and doesnt throw a JSLint error. But it doesnt work in Chrome.
The function is as follows :
this.XMLtoString = function (elem) {

        var serialized;
        try {
            var serializer = window.XMLSerializer();
            serialized = serializer.serializeToString(elem);
        }
        catch (e) {
            //Internet Explorer has a different approach to serializing XML
            serialized = elem.xml;
        }

        return serialized;
    };

I also tried adding the following line above the function.It did not help
/* global XMLSerializer */
Please help in writing a function that uses XMLSerializer without a JSLint error and which works across all browsers.
Comment: Probably `XMLSerializer()` is a global function. Just add it to "Globals list".
Comment: @Teemu : It is not a function created by me.
Answer: It works for me in Chrome if you use:
var serializer = window.XMLSerializer();

Alternatively, you can use your original new XMLSerializer(); code and then place this directive at the top of your file:
/*global XMLSerializer */

There must be no space between /* and global (people aren't kidding when they say JSLint is picky!).

JSLint error - XML Serializer


parsing JSON into Ruby iterator

Question: I have a JSON file with parsed data stored in a @colors instance variable, as follows:
[{:color=>"red", :value=>"#f00"} {:color=>"green", :value=>"#0f0"} {:color=>"blue", :value=>"#00f"} {:color=>"cyan", :value=>"#0ff"} {:color=>"magenta", :value=>"#f0f"} {:color=>"yellow", :value=>"#ff0"} {:color=>"black", :value=>"#000"}]

Now I want to iterate through this output to create a table in a view where there is

color	value

When I derive another instance variable like this --
@even_colors = @colors.values_at(* @colors.each_index.select {|i| i.even?}).map(&:values)

I get an array of arrays consisting of every other color/value pair
[["red", "#f00"], ["blue", "#00f"], ["magenta", "#f0f"], ["black", "#000"]]

But what I want to create two separate arrays, one consisting only of the color names indicated by :color  (red, blue, etc.) and the other consisting of just the hexs indicated by :value (#f00, #00f, etc.). I can't seem to figure out how to do that. Anyone have any suggestions? Thanks ...
Answer: You could do it with two passes through @colors:
names = @colors.map { |h| h[:color] }
hexes = @colors.map { |h| h[:value] }

Or you could it with on pass:
parts = @colors.each_with_object({ :names => [ ], :hexes => [ ]}) do |h, parts|
    parts[:names].push(h[:color])
    parts[:hexes].push(h[:value])
end

then look at parts[:names] for the color names and parts[:hexes] for the hex values.
I don't really see why you want to split @colors up though, you could produce your table straight from@colors:

    <% @colors.each do |h| %>

<%= h[:color] %>	<%= h[:value] %>

    <% end %>

Breaking @colors into two arrays seems like busy-work to me.
Comment: Thanks! You're right, I did not need two arrays. Your second suggestion works perfectly. I've seen this syntax before I guess I still haven't internalized it!

parsing JSON into Ruby iterator


Convert a txt file with values seperated to dataframe using pandas in python

Question: How do I convert a text file with values separated to a dataframe?
test.txt:
abc89321 , (('mike', 'A1 passed'),)
abc24862 , (('ross', 'm1 passed'),)
abc17695 , (('carter', 'c2 failed'),)

I have a text file with values like this, how to make these values into a dataframe with two columns?
Expected output:
a           b
abc89321   (('mike', 'A1 passed'),)
abc24862   (('ross', 'm1 passed'),)
abc17695   (('carter', 'c2 failed'),)

Answer: Use .read_csv() in combination with ast.literal_eval:
from ast import literal_eval

df = pd.read_csv(
    'test.csv',
    sep=' , ',
    names=['a', 'b'],
    engine='python',
    converters={'b': literal_eval}
)

df

          a                       b
0  abc89321    ((mike, A1 passed),)
1  abc24862    ((ross, m1 passed),)
2  abc17695  ((carter, c2 failed),)


Referencing different data frames(same size) for conditional change of resulting data frame

Question: I want to include values stored in different data frames(same size) into conditions to generate value for the resulting data frame.
My data:
int contains the intensity of different features (m2, m4, m1e3) measured for a number of people (in rows).
int<-data.frame(int_m2=c(33,32,35) ,int_m4=c(111,113,118), int_m1e3=c(104,99,110))
View(int)

3 different quality evaluation (s_, p_, i_) for each feature (m2, m4, m1e3).
s_<-data.frame(s_m2=rep(8,3) ,s_m4=rep(100,3), s_m1e3=c("NA", 100, 100 ))
p_<-data.frame(p_m2=rep(10,3), p_m4=rep(10,3), p_m1e3=c("NA", 10, 10 ))
i_<-data.frame(i_m2=rep(0.1,3), i_m4=rep(0.5,3), i_m1e3=c("NA", 0.1, 0.5 ))

I need results in which intensity from int would be pasted if conditions are TRUE for quality evaluation. In the case of "NA" or FALSE value should be 0.
Quality evaluation conditions:
if conditions(s_[i,j] >9 & p_[i,j] <20 & i_[i,j]> 0.2
Expected results:
res<-data.frame(m2=c(0,0,0),m4=c(111,113,118), m1e3=c(0, 0, 110 ))

Elaborate ranting:
My goal was to apply this on a big data set and to use foreach and dopar to make it faster.
But, after trying combinations of mutate, ifelse, sappy, or old school if/else loop I always get stuck on how to make inputs for conditions change if applied on the data frame. All that I found during extensive research are constants as conditions applied over data frames.
So each try I had was half-finished code and thus not very useful share.
Any recommendations for further reading on the subject are more than welcome.
Answer: Instead of looping over i, j, create the multiple logical expressions on the whole dataset, and multiply with int.  Those FALSE (-> 0) multiplied returns 0 for corresponding 'int' while the TRUE (-> 1) will return the same value from 'int'
(s_ > 9 & p_ < 20 & i_ > 0.2) * int

-output
 int_m2 int_m4 int_m1e3
1      0    111        0
2      0    113        0
3      0    118        0

Comment: Thank you that solves this problem and a lot of future ones! It didn't cross my mind to use such a simple and elegant solution!


Format labels on bar charts in Altair

Question: [![chart showing numbers without correct formatting][1]][1]
I need to format the label on these bars, so that they are rounded to nearest whole number. I have the following code:
def chart_tender_response_times(dataframe=None):

        chart = (
            alt.Chart(dataframe, title="Median time to respond to a tender")
                .mark_bar()
                .encode(
                alt.X("year(date):O"
                ),
                alt.Y("mean(median_duration):Q",
                     ## This is our units section, only describe the units of measurement here.
                     axis=alt.Axis(title="Unit: days.")
                ),
                alt.Tooltip(["mean(median_duration):Q"], format=",.2r", title="Days to respond to a tender")
            )
        )

        text = (
            chart.mark_text(align="center", baseline="bottom")
            .encode(text='mean(median_duration):Q')
        )

        return chart+text

I've tried variations of the following...
text = (
            chart.mark_text(align="center", baseline="bottom")
            .encode(text='mean(median_duration):Q', format='.,2r')
        )

but this returns the following schema validation error:
SchemaValidationError: Invalid specification

altair.vegalite.v3.api.Chart, validating 'required'

'data' is a required property

My hunch is that I have to somehow call and format the value, before adding it to the chart, but I can't see how to do this from either the documentation or the examples.
Answer: You need to wrap the format in alt.Text, as in encode(text=alt.Text('mean(median_duration):Q', format=',.2r'))
Also, I think format=',.0f' is more robust to round to the nearest integer (e.g. if you have 256.4, it would be rounded to 256, whereas with format=',.2r' you'd get 260)
Below is an example with a function a bit modified to fit another dataset (as you did not provide one):
import altair as alt
from vega_datasets import data

cars = data("cars")

def chart_tender_response_times(dataframe=None):
    chart = (
        alt.Chart(dataframe, title="Median time to respond to a tender")
        .mark_bar()
        .encode(
            alt.X("year(Year):O"),
            alt.Y(
                "mean(Displacement):Q",
                ## This is our units section, only describe the units of measurement here.
                axis=alt.Axis(title="Unit: days."),
            ),
            alt.Tooltip(
                ["mean(Displacement):Q"],
                format=",.0f",
                title="Days to respond to a tender",
            ),
        )
    )

    text = chart.mark_text(align="center", baseline="bottom").encode(
        text=alt.Text("mean(Displacement):Q", format=",.0f")
    )

    return chart + text

chart_tender_response_times(cars)

Format labels on bar charts in Altair


Outlook VBA Macro Prevent Running Specified Email Account

Question: I have been using Office 365 Outlook account. Now I configured 3 email accounts. since I created a VBA macro script. I don't want this script was running in all of my email accounts. I want to run VBA Script in specified accounts only. How can achieve that?
For example: Assume my three accounts

firstname.lastname@example.com,
firstname.lastname@example.com,
email@example.com.

I want to execute my VBA code only in

email@example.com,
email@example.com,

Not running VBA script at

firstname.lastname@example.com

My Code:-
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
    Dim recips As Outlook.Recipients
    Dim recip As Outlook.Recipient
    Dim pa As Outlook.PropertyAccessor
    Dim prompt As String
    Dim strMsg As String

    Const PR_SMTP_ADDRESS As String = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E"

    Set recips = Item.Recipients
    For Each recip In recips
        Set pa = recip.PropertyAccessor
        If InStr(LCase(pa.GetProperty(PR_SMTP_ADDRESS)), "@newsdozens.com") = 0 Then
        If InStr(LCase(pa.GetProperty(PR_SMTP_ADDRESS)), "@newsdozens2.com") = 0 Then
        If InStr(LCase(pa.GetProperty(PR_SMTP_ADDRESS)), "@bnewstest.com") = 0 Then
            strMsg = strMsg & "   " & pa.GetProperty(PR_SMTP_ADDRESS) & vbNewLine
        End If
        End If
        End If
    Next

    If strMsg <> "" Then
        prompt = "This email will be sent outside of newsdozens.com to:" & vbNewLine & strMsg & "Do you want to proceed?"
        If MsgBox(prompt, vbYesNo + vbExclamation + vbMsgBoxSetForeground, "Check Address") = vbNo Then
            Cancel = True
        End If
    End If
End Sub

Comment: How do you currently run that macro?
Comment: Please [edit] your question and add the code you are using.
Comment: yeag i have added my used code
Comment: What exactly do you mean? Do you only want to run your code against a particular message store? Or only when an email from a particular account is received? Or when it is sent using a particular account?
Answer: To selectively start a macro, you could do something like the following:
Dim Session As Outlook.NameSpace
Dim Accounts As Outlook.Accounts
Dim currentAccount As Outlook.Account

Set Session = Application.Session
Set Accounts = Session.Accounts

For Each currentAccount In Accounts
    Debug.Print currentAccount.SmtpAddress

    If currentAccount.SmtpAddress <> "firstname.lastname@example.com" Then
        '  call your macro
    End If
Next

Answer: You can check out the Sender's email address in the ItemSend event and cancel any further actions if no VBA macros should be run for a particular account:
 Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)

   If InStr(LCase(Item.SenderEmailAddress), "email@example.com") = 0 Then Exit Sub

   Dim recips As Outlook.Recipients
   Dim recip As Outlook.Recipient
   Dim pa As Outlook.PropertyAccessor
   Dim prompt As String
   Dim strMsg As String

   Const PR_SMTP_ADDRESS As String = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E"

  Set recips = Item.Recipients
  For Each recip In recips
    Set pa = recip.PropertyAccessor
    If InStr(LCase(pa.GetProperty(PR_SMTP_ADDRESS)), "@newsdozens.com") = 0 Then
    If InStr(LCase(pa.GetProperty(PR_SMTP_ADDRESS)), "@newsdozens2.com") = 0 Then
    If InStr(LCase(pa.GetProperty(PR_SMTP_ADDRESS)), "@bnewstest.com") = 0 Then
        strMsg = strMsg & "   " & pa.GetProperty(PR_SMTP_ADDRESS) & vbNewLine
    End If
    End If
    End If
  Next

  If strMsg <> "" Then
    prompt = "This email will be sent outside of newsdozens.com to:" & vbNewLine & strMsg & "Do you want to proceed?"
    If MsgBox(prompt, vbYesNo + vbExclamation + vbMsgBoxSetForeground, "Check Address") = vbNo Then
        Cancel = True
    End If
  End If
End Sub

Answer: There are various ways of getting sender information. This should work for either EX or SMTP addresses.
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)

    Debug.Print Item.SenderEmailAddress
    ' use text from the debug.print, that is unique to the account
    If InStr(Item.SenderEmailAddress, "test2") Then Exit Sub

    ' code here for all other accounts

End Sub


Quotations mark syntax in Windows Batch files

Question: When I try to run
netsh -c interface ipv4 add neighbors "Wi-Fi" "192.168.1.1" "00-24-36-A0-A0-61" store=persistent

in a bat file, it comes out as
netsh -c interface ipv4 add neighbors ΓÇ£Wi-FiΓÇ¥ ΓÇ£192.168.1.1ΓÇ¥ ΓÇ£00-24-36-A0-A0-61ΓÇ¥
store=persistent

in cmd. What can I do to fix this so they show up as regular quotation marks?
note: I am just learning bat so if there is something really easy to spot that I'm completely missing, that's why.
Comment: The issue is because you're using the incorrect quotation mark type. What you should be using are straight, _(dumb)_, quotes, not curly, _(smart )_ quotes. `@"%__AppDir__%netsh.exe" -c interface ipv4 add neighbors "Wi-Fi" "192.168.1.1" "00-24-36-A0-A0-61" store=persistent`
Comment: What do you mean by "it comes out"?
Comment: That depends on the editor you're using. Use one designed for programming rather than for creating documents. I recommend notepad++
Answer: For me, it looks like, you are using "Unicode"-Quotations copied out from Microsoft Word.
Copy them into Notepad and replace them by real Quotations '"'.
Comment: Could be using wordpad or excel or just about anything. They shouldn't need to copy and paste the correct quotes, they should just use an appropriate editor :)


how start another activity when java.lang.OutOfMemoryError

Question: My app run in most of devices but in some of device dont run and in Mainactivity.java The error is
java.lang.OutOfMemoryError

I want in SplashScreen.java if dont run Mainactivity.java, run another Activity for example Main2.activity
I use this code but does not work:
        try {
         Intent mainactivity = new Intent(SplashScreen.this, MainActivity.class);
        startActivity(mainactivity);
      }
      catch (OutOfMemoryError e) {
         Intent main2 = new Intent(SplashScreen.this, Main2.class);
        startActivity(main2);
      }

please help
my logcat:

    10-22 08:32:28.311: E/AndroidRuntime(1394): FATAL EXCEPTION: main
    10-22 08:32:28.311: E/AndroidRuntime(1394): Process: ir.maddahha.imamalip, PID: 1394
    10-22 08:32:28.311: E/AndroidRuntime(1394): java.lang.OutOfMemoryError
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:594)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:429)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:840)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at android.content.res.Resources.loadDrawable(Resources.java:2110)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at android.content.res.Resources.getDrawable(Resources.java:700)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at android.graphics.drawable.AnimationDrawable.inflate(AnimationDrawable.java:282)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:937)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at android.graphics.drawable.Drawable.createFromXml(Drawable.java:877)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at android.content.res.Resources.loadDrawable(Resources.java:2092)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at android.content.res.Resources.getDrawable(Resources.java:700)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at android.view.View.setBackgroundResource(View.java:15303)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at ir.maddahha.imamalip.Main.onCreate(Main.java:43)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at android.app.Activity.performCreate(Activity.java:5231)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at android.os.Handler.dispatchMessage(Handler.java:102)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at android.os.Looper.loop(Looper.java:136)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at android.app.ActivityThread.main(ActivityThread.java:5001)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at java.lang.reflect.Method.invokeNative(Native Method)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at java.lang.reflect.Method.invoke(Method.java:515)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
    10-22 08:32:28.311: E/AndroidRuntime(1394):     at dalvik.system.NativeStart.main(Native Method)

Answer: You can't recover from OutOfMemoryError. This error means your app used all available memory and OS can't allocate more for you. Your best shot is to try to investigate source of the problem. You might have some memory leaks, so try to fix that.


Schedule a Python script in crontab on Google Compute Engine VM

Question: I've scheduled my Python script to be executed once an hour by typing crontab -e in the shell, then adding this line of text to the cron file:
0 * * * * /usr/bin/python /home/myUserName/automatedProject/test.py &>> /home/myUserName/automatedProject/log.txt

but no matter what variations I try, it doesn't execute.
As a test script, I'm using Jessica Yung's simple script to append a timestamp to a file:
#! /usr/bin/env python
import time
filename = "record_time.txt"
current_time = time.strftime('%a %H:%M:%S')
with open(filename, 'a') as handle:
    handle.write(str(current_time))
    handle.write('\n')

Comment: `cron` _does_ run crontab commands under your user ID.  Note that that Python script writes directly into a file named `record_time.txt` in the current directory, which should be your home directory.  Check that file to see if the command is being executed.  The script does not print anything, so the redirect into `log.txt` will not collect anything. (It's always a good idea to run a command manually before you put it into a crontab, just to make sure it behaves the way you expect in normal circumstances.)
Comment: My `cron` does not like the `&>>` redirection, because that's a `bash` syntax and `cron` uses plain old `sh` to run crontab jobs.  Try changing that from `&>> /path/to/logfile` to `>> /path/to/logfile  2>&1` which is the traditional `sh` way of doing the same thing.  If that doesn't fix it then let's start from square one and check that the `cron` service is actually running (do `ps -efa | grep cron`).
Comment: Cron does not run as `your username`. Therefore do not try to access files files based upon your home directory. The cron logfile varies by Linux distribution: look for cron errors in `/var/log/syslog`. This may also help you: https://askubuntu.com/questions/418237/how-to-detect-error-in-cron-jobs
Comment: Hi @JohnHanley, I've moved everything into `/opt/*` but the Google Compute Engine VM still doesn't execute my cron job, not even when I set the cron time/date options to `* * * * *` (all 5 options as "any")
Comment: What do the logfiles show you?
Comment: Hi @ottomeister, thanks for that. i realized it was a local path and changed it to an absolute path. the command runs manually, but it doesn't run not when it's put into `crontab`.
Answer: In Google Compute Engine, with an Ubuntu 16.04 VM, the user-level cron jobs don't seem to be kicked off at all; however, root-level jobs work as expected.
Instead of editing crontab like this:
crontab -e
use sudo crontab -e
A simple, working example is * * * * * /usr/bin/python /home/myUserName/test.py to run test.py once a minute.


Does time fixed effect always have to be considered in panel regression analysis?

Question: This question might sound very silly, but I haven't found a clear answer so far.
Suppose you are working with a panel including several time series data for different countries/cities/firms: when analyzing the panel in a regression is it somehow mandatory to consider time and countries/cities/firms fixed effects?
If this is not the case, what makes you decide when these have to be considered or not?
Thanks
Comment: For the most part it is always the case to control for cross section and temporal variance, esp since these are the key structural factors in the data. In fact, I'm not aware of anything in the PDM literature where this is *not* done.
Comment: There is a discussion of different ways to specify time in panel data models here ... https://stats.stackexchange.com/questions/323549/looking-for-advice-regarding-model-selection-for-forecasting-dynamic-panel-da/324428#324428  Also, Singer and Willett's book *Applied Longitudinal Data Analysis* has one of the best discussions I'm aware of in the literature about a range of specifications of time in order to tease out different relationships. P. 210 in their book discusses Mosteller and Tukey's suggestion of a 'ladder of transformations and the rule of the bulge.' Could be useful.
Comment: Hi @DJohnson, it is certainly a good discussion, but here I am not talking about time series forecasting or dimensionality reduction or transformation. What I am talking about here is something way less elaborated: something like this https://www.dartmouth.edu/~ethang/Lectures/Class17/Always%20Control%20for%20Year%20Effects%20in%20Panel%20Regressions.pdf . Now I know that generally in panel regression, you want to control for time and country fixed effect, I was just wondering if this is always the case or if there is a rule that you can apply to decide if the control should be used or not
Answer: Please, consider that this is not THE way to go, it is just a quick roadmap to start analyzing panel data. A more rigorous procedure should be tested for the specific case of the user and supported by the literature.
After studying a bit more in detail the topic, although there is not a standardized procedure to apply to these analyses, a sequential approach that could be adopted is the following (ref and more info in this website and this video):
(example code in R using the plm package)

clean the panel data and set up the panel analysis (not explained here);
Estimate a simple OLS model
OLS<-plm(Y ~ X, data = my_panel, model = "pooling")

Estimate a random effect model
random<-plm(Y ~ X, data = my_panel, model = "random")

Estimate a fixed effect model
fixed<-plm(Y ~ X, data = my_panel, model = "within")

Test the difference between the models
# LM test for random effects versus OLS
plmtest(OLS)

if the p-values is small enough, it will indicate alternative hypothesis: significant effects, then opt for a random effect model.
    # LM test for fixed effects versus OLS
    pFtest(fixed, OLS)

if the p-values is small enough, it will indicate alternative hypothesis: significant effects, then opt for a fixed effect model.
    # Hausman test for fixed versus random effects model
     phtest(random, fixed)

if the test suggests alternative hypothesis: one model is inconsistent, then it would be more appropriate to go for a fixed effect model.


Shell command to find the newest created files recursively from a root directory?

Question: Is there a shell command to find the newest created files recursively from a root directory?
Answer: find /mydir -type f -exec stat -c '%y %N' {} \; | sort -n

Comment: You may want to tweak "%y". Refer to "man stat".
Comment: In general, you should avoid using -exec for security reasons. GNU find offers -execdir as an alternative.
Answer: This method uses only find (and sort):
find /somedir -type f -printf "%T+ %p\n" | sort

You can constrain it to the most recent 3 days, for example, like this:
find . -type f -mtime -3 -printf "%T+ %p\n" | sort

Or the last 42.5 hours:
find . -type f -mmin -2550 -printf "%T+ %p\n" | sort

which is the same as:
find . -type f -mmin -$((42 * 60 + 30)) -printf "%T+ %p\n" | sort

Answer: To avoid forking one process per file checked, if you're on a machine with GNU versions of find and xargs, consider something like this:
find /dir -type f -print0 | xargs -0 stat -c '%Y %N' | sort -n

Comment: with no time limit on find, it would match a lot more files.
Answer: This handles spaces correctly and executes a command (ls in this case) on a per file basis. Change (or delete) -n1 to execute the command on multiple files simultaneously.
find . -type f -printf "%T@ %p\0" | sort -z -nr | cut -z -d' ' -f2- |xargs -0 -n1 ls


jQuery Uploadify Question

Question: First off I am asking here vs the Uploadify forums because I am hoping to get a quicker answer to my issue. =>
I am using a CMS for my web site (Business Catalyst) and I do not have server side access. I cannot write to a folder etc. I would like to use Uploadify because of its features for the file upload in a form. I need to be able to have the upload file sent with the form. I am not sure if this is even possible but I am asking to see if it is.
A guy on the Uploadify forums said this: "You need a script like php, asp and so on for moving the file uploaded...But you can work this without php for your form file...
Example:
myform.html and on it using your upload form"
I am a bit confused as what exactly he is saying to do there.
Any advice about what to do?
Thanks in advance!
Answer: What the guy is trying to say is the following:

You can write your page with an uploader (using uploadify or any
uploader) normally
But, for the file to be uploaded phisically, the server has to be
configured to accept uploads from  your page
Also, to be able to do something with your file in the server (for
example, move it or save it to database), it has to be done with a
server scripting language: (php, asp.net, ruby, etc)

So, you can build your page using uploadify but there's no guarantee that the file will be saved on the server.
Hope this helps. Cheers
Comment: Thanks, if I could get the file to be attached to the email I get that is all I need. I assume that this won't work since I do not have server side access.
Comment: Was just thinking about something. I can use the standard file upload field and accept files, the question is how would I go about configuring Uploadify to use the process. Make sense?
Comment: Been messing with this a little. Can the javascript be tweaked to send the file with the form and let the CMS handle it like it normally does with form file uploads? Here is a page I have been messing with: http://ubhape2remodel.businesscatalyst.com/test.html
Answer: After speaking with people both here and on other forums (and support for Business Catalyst) I have come to the conclusion that with Business Catalyst you cannot use Uploadify. Since you do not have server side access there is no way around setting up this to work properly.

jQuery Uploadify Question


Python - Twisted, Proxy and modifying content

Question: So i've looked around at a few things involving writting an HTTP Proxy using python and the Twisted framework.
Essentially, like some other questions, I'd like to be able to modify the data that will be sent back to the browser. That is, the browser requests a resource and the proxy will fetch it. Before the resource is returned to the browser, i'd like to be able to modify ANY (HTTP headers AND content) content.
This ( Need help writing a twisted proxy ) was what I initially found. I tried it out, but it didn't work for me. I also found this ( Python Twisted proxy - how to intercept packets ) which i thought would work, however I can only see the HTTP requests from the browser.
I am looking for any advice. Some thoughts I have are to use the ProxyClient and ProxyRequest classes and override the functions, but I read that the Proxy class itself is a combination of the both.
For those who may ask to see some code, it should be noted that I have worked with only the above two examples. Any help is great.
Thanks.
Comment: Why didn't those solutions work for you? Did you get a traceback, did nothing happen when you ran it, or did you not understand how to modify the classes for your needs?
Comment: Good question. I forgot to mention this. The first one "Need help writing a twisted proxy", I added a ProxyFactory and reactor to the answer code and it worked as a bypass proxy, but no inversion. The second, I got it working, however it would only print the HTTP requests from the browser. I was not able to get it to print the requested pages.
Answer: To create ProxyFactory that can modify server response headers, content you could override ProxyClient.handle*() methods:
from twisted.python import log
from twisted.web import http, proxy

class ProxyClient(proxy.ProxyClient):
    """Mangle returned header, content here.

    Use `self.father` methods to modify request directly.
    """
    def handleHeader(self, key, value):
        # change response header here
        log.msg("Header: %s: %s" % (key, value))
        proxy.ProxyClient.handleHeader(self, key, value)

    def handleResponsePart(self, buffer):
        # change response part here
        log.msg("Content: %s" % (buffer[:50],))
        # make all content upper case
        proxy.ProxyClient.handleResponsePart(self, buffer.upper())

class ProxyClientFactory(proxy.ProxyClientFactory):
    protocol = ProxyClient

class ProxyRequest(proxy.ProxyRequest):
    protocols = dict(http=ProxyClientFactory)

class Proxy(proxy.Proxy):
    requestFactory = ProxyRequest

class ProxyFactory(http.HTTPFactory):
    protocol = Proxy

I've got this solution by looking at the source of twisted.web.proxy. I don't know how idiomatic it is.
To run it as a script or via twistd, add at the end:
portstr = "tcp:8080:interface=localhost" # serve on localhost:8080

if __name__ == '__main__': # $ python proxy_modify_request.py
    import sys
    from twisted.internet import endpoints, reactor

    def shutdown(reason, reactor, stopping=[]):
        """Stop the reactor."""
        if stopping: return
        stopping.append(True)
        if reason:
            log.msg(reason.value)
        reactor.callWhenRunning(reactor.stop)

    log.startLogging(sys.stdout)
    endpoint = endpoints.serverFromString(reactor, portstr)
    d = endpoint.listen(ProxyFactory())
    d.addErrback(shutdown, reactor)
    reactor.run()
else: # $ twistd -ny proxy_modify_request.py
    from twisted.application import service, strports

    application = service.Application("proxy_modify_request")
    strports.service(portstr, ProxyFactory()).setServiceParent(application)

Usage
$ twistd -ny proxy_modify_request.py

In another terminal:
$ curl -x localhost:8080 http://example.com

Comment: @dulac: `buffer.upper()` probably should not be called on arbitrary content. Replace it by mere `buffer`.
Comment: I tried this one and I keep getting a Content Encoding Error. Any Ideas?
Comment: Sebastion:

Ok! This is the one I'm going with. I can view the content as it goes through. Also, I didn't use your main function. I did:

from twisted.internet import reactor

reactor.listenTCP(8080, ProxyFactory() )
reactor.run()

And it works just the same
Comment: @dulac:`listenTCP()` listens on all interfaces (not only `localhost`), run `lsof -i tcp:8080` to check. Additionally if there are errors `endpoints` variant shutdowns the reactor properly.
Answer: For two-way proxy using twisted see the article:
http://sujitpal.blogspot.com/2010/03/http-debug-proxy-with-twisted.html
Comment: Thanks. I read through this. It WILL work, however I am wondering if there would be a way to do this with the proxy.Proxy modules like the above two. Would it even matter?


How PHP frameworks like Laravel/Symfony autopass class object to methods and/or constructors? e.g Request $request

Question: I have a question that may be troubling many PHP programmers.
How PHP frameworks like Laravel, Symfony, etc. autopass class object to methods and/or constructors?
For example:
class TestController extends Controller
{
    public function testAction(Request $request)
    {
        //how Request $request object is autopassed here?
    }
}

Do they used php built in functions like func_get_args()?
C# ASP.NET for example also can do this (autopass objects). But C# is staticly typed language, so compiler know all types that method/constructor require. You also need to explicitly register classes that will be auto injected in ConfigureServices in Startup.cs. When you have done this, C# will use reflections to correcly inject class instances (C# got all the data he need to do this).
http://dotnetliberty.com/index.php/2015/10/15/asp-net-5-mvc6-dependency-injection-in-6-steps/
PHP does not know types. How he can do that?
Comment: Dependency Injection
Comment: Yes, but how that exactly works? How Symfony/Laravel knows what to inject when PHP do not know type of class that will inject?
Comment: You do realise that `public function testAction(Request $request)` is identifying that the argument `$request` should be an object of type `Request`?
Comment: Do PHP store argument type somewhere? If yes - how to access that metadata? Without it, that trick is impossible. For example - in c# you can use reflections. And in PHP?
Comment: It's stored in the class code that PHP needs to execute that code, and can be read with tools like Reflection
Answer: In case of Symfony there are multiple mechanisms at play for example ArgumentResolver and ParamConverters and also the HttpKernel and Event Dispatcher.
To better understand how this works you should be familiar with the HttpKernel. Basically it will take the Request object, pass it to an event dispatcher and then some listeners will be triggered on certain events and modify the request, e.g. by adding attributes. One of the events being triggered in Symfony's cycle is responsible for getting the controller arguments. The arguments being extracted be it from the container in case of autowiring, from the request or from the session are then passed to the controller action using call_user_func_array($controller, $arguments).
So basically what Symfony does is take a request, find out which controller and action to use, inspect the controller to check which arguments it wants and what data the request provides. If the request provided enough data to satisfy the controller's needs it will be called, if not you will get an exception.
With Laravel and other frameworks using a Middleware-approach, like Silex, it's pretty similar but in these cases it's the Middleware enriching the request and adding attributes. In case of Silex the middleware will even use the Symfony Event Dispatcher and the same Symfony events, making the middleware easily transferable to a Symfony Event Listener. As discussed in this article: https://medium.com/@derrabus/migrating-silex-middlewares-to-symfony-4f81e8548530
Comment: And if you to know some of the details take a look at the HttpKernel::handle method as well a the ControllerResolver and ArgumentResolver.  in the end it boils down to: $response = \call_user_func_array($controller, $arguments);
Comment: Yes, one of the links in the bold section references the `HttpKernel::handleRaw()` where you can exactly see how the arguments are passed to the controller on a code level. If you fully look at handle and handleRaw you can trace this process. The events are making it a little difficult to follow, but tools like xdebug will help navigate them.


Android application crashes while launch camera activity (Visual studio Xamarin)

Question: Hello to all programmers.
While creating my first android app in Visual studio Xamarin, I stuck with one more problem (there was lot of them =) ). I try to make permissions check for Android Marshmallow+. And while I try to launch Camera Activity (MediaStore.ActionImageCapture), my app crashes. Here the code
const int REQUEST_CAMERA = 1;
const int REQUEST_EXTERNAL_STORAGE = 2;
const string cameraPermission = Android.Manifest.Permission.Camera;
const string storageWritePermission = Android.Manifest.Permission.WriteExternalStorage;
const string storageReadPermission = Android.Manifest.Permission.ReadExternalStorage;
public static class App
{
  public static File _file;
  public static File _dir;
  public static Bitmap bitmap;
  public static string fileName;
}
private bool IsThereAnAppToTakePicture()
{
  Intent intent = new Intent(MediaStore.ActionImageCapture);
  IList<ResolveInfo> availableActivities =
  PackageManager.QueryIntentActivities(intent, PackageInfoFlags.MatchDefaultOnly);
  return availableActivities != null && availableActivities.Count > 0;
}
private void CreateDirectoryForPictures()
{
  App._dir = new File(Enviroment.GetExternalStoragePublicDirectory(Enviroment.DirectoryPictures), "Kuponguru");
  if (!App._dir.Exists())
  {
    App._dir.Mkdirs();
  }
}
private void StartCameraActivity()
{
  Intent intent = new Intent(MediaStore.ActionImageCapture);
  App.fileName = String.Format("picture_{0}.jpg", Guid.NewGuid());
  App._file = new File(App._dir, App.fileName);
  intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(App._file));
  StartActivityForResult(intent, REQUEST_CAMERA);
}
protected override void OnCreate(Bundle savedInstanceState)
{
  base.OnCreate(savedInstanceState);
  SetContentView(Resource.Layout.TakePicture);
  pictureImageButton = FindViewById<ImageView>(Resource.Id.pictureButton);
  pictureImageButton.Click += TakePicture;
  if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
  {
    if (CheckSelfPermission(storageReadPermission) == (int)Permission.Granted &&
    CheckSelfPermission(storageWritePermission) == (int)Permission.Granted)
    {
      if (IsThereAnAppToTakePicture())
      {
        CreateDirectoryForPictures();
      }
    }
    else
    {
      RequestPermissions(new string[] { storageWritePermission, storageReadPermission }, REQUEST_EXTERNAL_STORAGE);
    }
  }
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
  switch (requestCode)
  {
    case REQUEST_EXTERNAL_STORAGE:
    {
      if (grantResults[0] == Permission.Granted)
      {
        if (IsThereAnAppToTakePicture())
        {
          CreateDirectoryForPictures();
        }
      }
    }
    break;
    case REQUEST_CAMERA:
    {
      if (grantResults[0] == Permission.Granted)
      {
        StartCameraActivity();
      }
    }
  }
}
private void TakePicture(object sender, EventArgs e)
{
  if (Build.VERSION.SdkInt >= BuildVersionCodes.M) {
    if (CheckSelfPermission(cameraPermission) == (int)Permission.Granted &&
                    CheckSelfPermission(storageWritePermission) == (int)Permission.Granted)
    {
      StartCameraActivity();
    }
    else
    {
      RequestPermissions(new string[] { cameraPermission, storageWritePermission }, REQUEST_CAMERA);
    }
  }
  else
  {
    StartCameraActivity();
  }
}

If I delete string intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(App._file)); in StartCameraActivity, then camera works, but with this command app crashed.
I'll be appreciated for all suggestions.
--UPDATED--
I check Uri.FromFile(App._file) in intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(App._file)); File is not exists So, problem is - app can't create file (but can create directory)
--UPDATED--
I check application on Marshmallow emulator. All works fine. Also I check on emulated device - file, where camera should save photo, is not exists when I send it to Camera activity in intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(App._file)); Well problem is still here.
--UPDATED--
Added try catch for Camera activity start and get exception file:///storage/emulated/0/Pictures/MyApp/picture_123.jpg exposed beyond app through ClipData.Item.getUri
Comment: Does your code crash in an emulator, a real device or in both?
Comment: To @AndreKraemer - It crashes on real device with Android Marshmallow+. On real device with KitKat and Lollipop everything works. For emulating i use VS emulator and there are KItKat only.
Comment: I think that is related to permissions
Comment: To @JesusAngulo Well, I get permissions WriteExternalStorage and ReadExternalStorage before creating directory, and it's create without problem. Same with File. Before using camera i got Camera permission. I check in Settings - My app have all this permissions. Something wrong in the Camera Activity.
Comment: I recommend you to use **Android Device Monitor** to get more details.
Comment: How can I use ADM if I run app on real device?
Answer: At least I found whats wrong. It's god damned version issue. In Android N+ there are no more file:// URIs, only content:// URIs instead. That's why Camera Activity can't work with Uri.FromFile(App._file).
For this solution I have to thank request Answer of question by questioner SuperThomasLab and users Pkosta, hqzxzwb and Java coder
The solution, changed for VS Xamarin, I used:
**Solution **
protected override void OnCreate(Bundle savedInstanceState){
  StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
  StrictMode.SetVmPolicy(builder.Build());
  base.OnCreate(savedInstanceState);
  ...
}

Other code is without changes.
I tried it on Android N 7.1.1 on real device and it's works.
Thanks to all, who take attention to my problem.


How to add attributes to forms?

Question: I am trying to style the registration/login forms so far I have copied all the files from \drupal\core\themes\stable\templates\form\ to themes\mytheme\template\form.
Inside this folder, for example there is input.html.twig which has the following code.
{#
/**
 * @file
 * Theme override for an 'input' #type form element.
 *
 * Available variables:
 * - attributes: A list of HTML attributes for the input element.
 * - children: Optional additional rendered elements.
 *
 * @see template_preprocess_input()
 */
#}
<input{{ attributes }} />{{ children }}

My question is how can I add a specific class name to this input, so I can apply styles to it in my css file
Answer: You can use the addClass() method of the attribute class:
{%
  set classes = [
    'my-class-1',
    'my-class-2',
  ]
%}

<input{{ attributes.addClass(classes) }}>

You can either pass an array like the example above or pass a single class in the method directly: attributes.addClass('my-class').
For reference see the Drupal docs: https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates
Comment: Funny, I was just trying this and it does not work. I had to enclose the the the first portion of the code in `{%%}` though
Comment: Oh yeah, that's correct. Updated my anwer, thanks!

How to add attributes to forms?


Elementary question about the Lebesgue-measure $\lambda$

Question:

Formally speaking, the Lebesgue-measure $\lambda$ on $\mathbb{R}$ is the restriction of the outer Lebesgue-measure
    $$
\lambda^*(A)=\inf\left\{\sum_{n=1}^{\infty}p(C_n): A\subset\bigcup_{n=1}^{\infty}C_n, \forall n\in\mathbb{N}: C_n\in\mathcal{S}\right\}
$$
    where $p$ is the Lebesgue pre-measure on the semiring $\mathcal{S}$ of all intervalls of the form $(a,b]$ defined by $p((a,b])=b-a$ and $p(\emptyset)=0$ on the $\sigma$-algebra $\mathcal{M}(\lambda^*)$ of all sets that are $\lambda^*$-measurable.
    One says that $\lambda$ is the unique continuation of $p$ and especially $\mathcal{B}(\mathbb{R})\subset\mathcal{M}(\lambda^*)$, i.e. all Borel sets are Lebesgue-measurable.
    So far so good.

Now I have one (maybe very stupid) problem.
If one has f.e. the intervall $(a,b)$ (which is in the Borel-$\sigma$-algebra and therefore formally it is Lebesgue-measurable) it is $$\lambda((a,b))=\lambda^*_{|\mathcal{B}(\mathbb{R})}((a,b))=b-a.
$$

Why?
Is it right that calculating the Lebesgue-measure of a Borel-set is calculating the outer Lebesgue-measure in fact? So that writing $\lambda$ is in fact not very precisely? Instead one should write $\lambda^*_{|\mathcal{B}(\mathbb{R})}$.
In which way is $\lambda=\lambda^*_{|\mathcal{B}(\mathbb{R})}$ a continuation of $p$, because $\lambda=p$ on $\mathcal{S}$?
Answer:
Because that is the definition of restriction: if we have a function $f\colon A\to B$ and a $C\subseteq A$, then $f|_C$ is the function $C\to B$ such that for all $c\in C$ we have $f|_C(c)=f(c)$. Unless you're asking why $\lambda^*((a,b))=b-a$ -- that follows from continuity of $p$ on $\emptyset$, for example.
Why would that be imprecise? If you define $f(x)=x^5+3x^2+6x$, would you regard writing $f(1)=10$ (instead of $1^5+3\cdot 1^2+6\cdot 1=10$) as imprecise?
I'm not sure what is meant by continuation, but I think it's most likely meant in a sense synonymous to "extension". In that case, yes, the point is, $p=\lambda|_{\mathcal S}$.
Comment: @mathfemi: It is not really important how the measure is constructed: its important properties are that: it is a (regular, countably additive, positive) measure, it attains on intervals the values we want it to attain, and it is translation invariant. The rest is only really a construction to show that it exists.
Comment: 1. Yes, my question is, because $\lambda^*((a,b))=b-a$, but now I think it is clear: $(a,b)=\bigcap_{n\geqslant 1}(a,b+\frac{1}{n}]$ and $\lambda^*(a,b+1]=b+1-a<\infty$ so it is $\lambda^*((a,b)=\lim_{n\to\infty}b+\frac{1}{n}-a=b-a$. 2. I do not see what your example has in common with that to be honest. I think it would be more clear not to write $\lambda$ but to write it as the restriction of an outer measure to make clear how the measure is constructed. 3. Yes, I mean extension.


Alternative to the need for dozens of roles to access special materials

Question: My organization wants to create access to specific resources and materials based on a role, but the issue is that there is the potential for dozens of such roles, each granting access to specific materials.
Is there a better way to manage this without having to have dozens of roles and permissions in the system, such as to use taxonomy or something else that is set up to accommodate such a volume?
Scenario:
A user can access our site and pay for and subscribe for special access to sections A, B, and C, each separately. Then we would need a way to track who has paid for access to which sections. I believe the section would include text, downloads, and possibly a forum and training videos.
Note: CiviCRM takes and tracks payments and memberships.
Comment: If these "roles" only gate content (no other permissions needed) you could possibly add a user field for these "roles" that's attached to a taxonomy, then create some custom access permissions for your content types. But it seems like just as much work as setting up roles... what are your concerns about having dozens of roles? it shouldnt affect performance too much IMO
Comment: My concern was having a list of permissions associated with each role multiplied so many times, editing and saving them taking extra processing power and stability issues. As well as the amount of work to the system each time the organization wants to add content. It just seems messy.
Comment: what do you have available in your site to actually facilitate, track, those payments and subscriptions in your site ( per the scenario in your updated question)?
Answer: Have a look at the Group module (commonly perceived as an alternative for Organic Groups).
Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable. Which also makes it integrate very well (out of the box) with commonly used modules such as Rules, Views, etc.
Some more questions you may want to look at for more details:

What are the various roles supported by the Group module?, which explains the various types of roles that can be used.
How to bulk assign existing content to a group created with the Group module?, a typical issue when adding this module to an existing site.
What are the features of the Group module versus Organic Group module?

Sample configuration
Below is an example of a possible configuration, which may help to get you started with possible configurations (using the Group module):
<code>Group type ID ! Group type ! Group role ID ! Role
--------------+------------+---------------+------------
 1            ! Class      ! 3             ! Instructor
 1            ! Class      ! 4             ! Student
 2            ! Customers  ! 5             ! Lead
 2            ! Customers  ! 6             ! Prospect
 2            ! Customers  ! 7             ! Licensed Customer
 2            ! Customers  ! 8             ! Sales
 2            ! Customers  ! 9             ! Support
 2            ! Customers  ! 10            ! Accounting
 2            ! Customers  ! 11            ! R&D
 3            ! Project    ! 12            ! Project Manager
 3            ! Project    ! 13            ! Developer
 3            ! Project    ! 14            ! Customer
</code>
Group Types
The above example consists of 3 group types:

Class.
Customers.
Project.

Group Roles
For each of the 3 group types, there are specific Roles defined, some more details about some of them:

for the Class group, these are the 2 roles that are configured:

Instructor.
Student.

for the Project group, these are the 3 roles that are configured:

Project Manager.
Developer.
Customer.

These are the Group Specific Roles: these roles can be configured per group type and will only be available on groups of that group type. As an example, for group type "Class", the defined roles are Instructor and Student (which are not available for the other group types.
On top of the group specific roles, there are also Special Global Roles: These are the special (hardcoded) roles named Outsider (= a signed in user that did not join a group) and Member  (= a signed in user that did join a group). These cannot be defined by the Drupal administrator, and they are always available for any group. These roles can have different permissions sets for each group type. Special case: the role Anonymous is related to a user that is not signed.
Groups
Each of the configured group types can have any number of Groups.
Examples of groups:

for the Class group type, there could be these Groups:

Getting started with Drupal.
Drupal for site builders.
Become an expert in using the Rules module.

for the Customers group type, there could be these Groups:

Service Requests.
Order Processing.
Sales Orders.
Relationship Management.

Permissions
For each of the configured group types, you can then also configure for each Content Type which Role has what kind of access (= none, view, create, edit, delete). Be aware: even though this looks similar to Drupal's permission configuration, these permissions are not the same permissions (they are specific to the Group module).
Rules integration
Since you seem to be using CiviCRM also, you should definitely also consider using the CiviCRM Entity module, especially because of its integration with the Rules module ... combined with automagically creating (or deleting) so called "Group memberships" (which you can do via Rules). For an example of how to use Rules to create or remove such group memberships, refer to my answer to "How to add and delete a user to another group using the Group module?".
Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".

Note
About your concern (as in your additional comment), which includes:

... having a list of permissions associated with each role multiplied so many times, editing and saving them taking extra processing power and stability issues. As well as the amount of work to the system each time the organization wants to add content. It just seems messy.

You're right, using standard Drupal permissions (with a zillion of roles) it would indeed become messy. But after you realize/discover how the Group module's roles/permissions work, your concern should be addressed ...
Comment: Thank you! We are also using CiviCRM and want to use that to manage the subscription process. I didn't mention this in my original post, but it sounds like the Group module is what we need. I'll need to see if it will work with the CRM and get back to you, thank you!
Answer: The Monster Menus Module was developed especially for educational organizations, but can be used outside of that context as well. It allows you to have many different groups with different permissions that are controlled by the module instead of Drupal itself.


Number theory problem, 3rd degree diophantine equation

Question: How many positive integers are there that can be written in the form
$$\frac{m^3+n^3}{m^2+n^2+m+n+1}$$
where $m$ and $n$ are positive integers.
I invented this problem and was stuck with it for a long time. It is really interesting to know if there is a solution for this problem.
Answer: A few lines of code trying the first 5000 numbers will give you those answers up to changing order between $m$ and $n$, let $f(m,n) = \frac{m^3 + n^3}{m^2+n^2+m+n+1}$:
$f(1,2) = 1; \qquad f(182,379) = 341; \qquad f(664,4286) = 4200; \qquad f(692, 3847) = 3747$
$f(961,1712) = 1531; \qquad f(996,692) = 896; \qquad f(1112, 270) = 1064$
$f(1712, 961) = 1513; \qquad f(2778,3210) = 3024$
Surely there are more but maybe you could try to find a pattern or see something in common?
As too whether it's interesting, well it's number theory. Fermat's Theorem is hugely famous and Andrew Wiles spent about 5 years to initially find a flawed proof which has then been corrected and yet it has no application whatsoever.
So I guess the interesting bit is purely mental, not practical (or at least not yet).
Answer: For fixed $n\ge 1$ we can sometimes solve the question as follows. Write
$$
\frac{m^3+n^3}{m^2+m+n^2+n+1}=(m-1) -\frac{(n^2+n)m-(n^3+n^2+n+1)}{m^2+m+(n^2+n+1)}.
$$
The LHS is an integer, if and only if the last fraction on the RHS is an integer. However, for fixed $n$, the denominator grows quadratically, and the nominator only linearly in $m$. For $m$ big enough, the fraction will not be an integer. For small $n$ this works, e.g., say for $n=1$ we have
$$
\frac{m^3+1}{m^2+m+3}=(m-1) -\frac{2m-4}{m^2+m+3},
$$
where the last fraction is an integer if and only if $m=2$. For $n=2$ we obtain
the fraction $\frac{6m-15}{m^2+m+7}$ which is an integer if and only if $m=1$, etc. In general, of course, this still leaves finitely many possible solutions for $m$, if $n$ is fixed, and we have not answered the question.


connect my netcore app to mongodb using docker-compose?

Question: I can't seem to connect my app container to the mongodb container
here is the mongo class inside my app
public BaseDao(string dbName)
        {
            m_mongoClient = new MongoClient("mongodb://localhost:27017");
            m_mongoDb = m_mongoClient.GetDatabase(dbName);
        }

here is my docker-compose
version: '3.4'

services:
  app:
    image: vinnie_app:latest
    depends_on:
      - 'mongodb'
  mongodb:
    image: mongo:latest
    container_name: "mongodb"
    ports:
      - 27017:27017

and my docker-compose.override
version: '3.4'

services:
  app:
    build: ./app
    environment:
      - ASPNETCORE_ENVIRONMENT=Staging
      - NODE_ENV=staging
      - ASPNETCORE_URLS=http://*:50000
      - MONGODB_URI='mongodb://mongo:27017/'
    ports:
      - 50000:50000

I get a 500 error when I try to fetch stuff from the database from the app container. What's the error and how do I connect my app container to the mongodb?? I run the containerized app at http://192.168.99.100:50000/
Answer: m_mongoClient = new MongoClient("mongodb://localhost:27017");
this line should instead read the URI from MONGODB_URI environment variable.
m_mongoClient = new MongoClient(System.getenv("MONGODB_URI"));
Comment: `m_mongoClient = new MongoClient(System.getenv("MONGODB_URI") || "mongodb://localhost:27017");`
Comment: @Siyu beat me to a more concise form :)
Comment: what if I want to run the app from VS and not docker, it won't work anymore right? I want to be able to run the app from both VS and docker
Comment: `String m_url = System.getEnv("MONGODB_URI"); if (m_url == null) {m_url = `mongodb://localhost:27017"}  `
Comment: System.getenv does not compile. Also Siyu i can't use ||


How do I find the remainder for the following?

Question: I know this is a very typical question for modular arithmetic but still I haven't found a comprehensive explanation for this question, so I'm posting it here. So here goes:
I need to find the remainder when $19^{38}$ is divided by $38$.
Here is my attempt:-
$$19\equiv 19\pmod {38}$$
$$19^2\equiv 19^2\pmod {38} \implies 19^2\equiv 19\pmod {38}$$
$$\implies (19^2)^2\equiv 19^2\pmod {38} $$
$$\implies 19^4\equiv 19\pmod {38}$$
$$\implies 19^8\equiv 19\pmod {38}$$
$$\implies 19^{16}\equiv 19\pmod {38}$$
$$\implies 19^{32}\equiv 19\pmod {38}$$
And carrying on I do get the answer that $$19^{38}\equiv 19\pmod {38}$$
But this seems a very cumbersome task, for higher powers it may be hard, or if 19 would not have been a factor of 38, then probably I wouldn't have been able to develop the pattern. Is there an easier and more methodical way to solve this using number theory/modular arithemtic?
I think I may have seen a solution involving Euler's Totient Function, but it was a while ago and I simply can't seem to relate it with this question and cant remember what the solution was. Can that be used to simplify this question?
Comment: For this question in particular, it is not hard to prove by induction that $19^n\equiv 19\mod 38$ for all $n\geq1$. I'm not aware of any faster methods for the general problem $a^b\equiv x\mod c$, however.
Comment: To prove by induction note that if $m$ is odd then $m=2\lfloor \dfrac m2\rfloor +1$ so $m^2=(2m)\lfloor \dfrac m2\rfloor +m\equiv m \mod 2m$; here is the specific case $m=19$
Answer: Since $19^{38} - 19$ is divisible by both 2 and 19, it is divisible by 38.  Therefore,
$$19^{38} \equiv 19 \pmod{38}.$$
Euler's Theorem can't be applied here, since $\gcd(19,38)$ is not equal to 1.  But the fact that 19 divides 38 actually makes the calculation much easier.
Answer: Precisely, Euler's totient function comes to be very handy for such problems. Euler's theorem states that if gdc$(a,m)=1$, then $a^{\phi(m)} \equiv 1 \pmod{m}$. In your case, since gdc$(19,38) \neq 1$, the fact that $19^2 \equiv 19 \pmod{38}$ is crucial, and from that one gets $19^n \equiv 19 \pmod{38}$, for every $n \in \mathbb{N}$. For instance, if you want to calculate the remainder of $17^{38}$ when divided by 38, first observe that gdc$(17,38) = 1$ (here we can use Euler's theorem), and that $\phi(38)=18$. So, since $38= 2 \times 18 +2$, we have
$$
17^{38}=17^{2 \times 18 +2}=(17^{18})^217^2 \equiv 17^2 \equiv 23 \pmod{38}.
$$
That's the "canonical" way.
Answer: $19(2)\mid 19(18)\mid 19^{n+1}\!-19$
since: $\, a(a\!-\!1)\mid a(a^n-\,1)$
Answer: For $19^{a+1}\pmod{38},$
let us find $19^a\pmod{\dfrac{38}{19}}$
As $19\equiv1\pmod2$
$19^a\equiv1^a\equiv1\pmod2$ for integer $a\ge0$
$\implies19^{a+1}\equiv1\cdot19\pmod{2\cdot19}$
See also : How to find last two digits of $2^{2016}$


Proving $\lim_{x \to c}f(g(x)) = f( \lim_{x \to c} g(x))=f(L) \text{ where } \lim_{x \to c} g(x) = L \text{ and } f(x) \text{ is continuous at } x=L$

Question: I am new to the $\epsilon - \delta$ definition of a limit and I'm trying to understand this proof.
Prove that $\displaystyle \lim_{x \to c}f(g(x)) = f( \lim_{x \to c} g(x))=f(L) \text{ where } \lim_{x \to c} g(x) = L \text{ and } f(x) \text{ is continuous at } x=L$
This is the proof:
$\displaystyle \lim_{u \to L} f(u) = f(L) \text{ means } \forall \epsilon>0 \hspace{0.2cm} \exists \delta_1 > 0 \text{ such that } 0<|u-L|<\delta_1 \implies |f(u)-f(L)|<\epsilon$
$\displaystyle \lim_{x \to c} g(x) = L \text{ means } \forall \epsilon_1>0 \hspace{0.2cm} \exists \delta > 0 \text{ such that } 0<|x-c|<\delta \implies |g(x)-L|<\epsilon_1$
Then here he substitutes $\delta_1$ instead of $\epsilon_1$, so the statement becomes this:
$\displaystyle \forall \delta_1>0 \hspace{0.2cm} \exists \delta > 0 \text{ such that } 0<|x-c|<\delta \implies |g(x)-L|<\delta_1$
I understand the fact that because $\epsilon_1$ is any number we choose, we can just plug in $\delta_1$, but what I don't understand is why the statement above is true $\forall \delta_1>0$. What if we choose a $\delta_1$ value that doesn't have an $\epsilon$ value associated with it. We know that $\forall \epsilon>0 \hspace{0.2cm} \exists \delta_1>0 \text{ but this doesn't imply that } \forall \delta_1>0 \hspace{0.2cm} \exists \epsilon>0$. Here is the rest of the proof:
let $u=g(x)$, so the statements become this:
$\displaystyle \forall \delta_1>0 \hspace{0.2cm} \exists \delta > 0 \text{ such that } 0<|x-c|<\delta \implies |g(x)-L|<\delta_1$
$\displaystyle\forall \epsilon>0 \hspace{0.2cm} \exists \delta_1 > 0 \text{ such that } 0<|g(x)-L|<\delta_1 \implies |f(g(x))-f(L)|<\epsilon$
$\displaystyle \therefore\forall \delta_1>0 \hspace{0.2cm} \exists \delta > 0 \text{ such that } 0<|x-c|<\delta \implies |f(g(x))-f(L)|<\epsilon$
Then he just checks $g(x) = L \implies |f(g(x))-f(L)|=0<\epsilon$
Thank you all in advance.
Comment: Please use more descriptive titles.
Answer: This is notation heavy, so it's easy to get confused. You can just plug in $\delta_1$ for $\epsilon_1$ because $\epsilon_1$ is arbitrary, as you say. $\delta_1$ is just a number. We don't know or care whether or not 'there is an $\epsilon$ associated to it'. The author is, perhaps confusingly, setting up the proof in a particular way.
I might 'rewrite' it as follows. Fix an $\epsilon>0$. Because $f$ is continuous, I know that there is a $\delta'>0$ with $|L-y|<\delta$ implying $|f(y)-f(L)|<\epsilon$, (among all $y$ in the domain of $f$).
Because $\lim_{x\to c}g(x)=L$, I know that there is a $\delta>0$ such that $0<|x-c|<\delta$ implies $|g(x)-L|<\delta'$ (among all $x$ in the domain of $g$), where $\delta$ is the same number I used above (everything is fixed).
The chain of dependencies: $\epsilon$ is 'free', $\delta'$ depends on $\epsilon$, and $\delta$ depends on $\delta'$.
Now let $x$ be any number with $0<|x-c|<\delta$. I want to check, is $|f(g(x))-f(L)|<\epsilon$? If so, then the proof is done, because $x$ is arbitrary, this value of $\delta$ 'works, and $\epsilon$ is arbitrary.
I know $|g(x)-L|<\delta'$. That means $y=g(x)$ is a number with $|y-L|<\delta'$, so by definition of $\delta'$ we know $|f(y)-f(L)|<\epsilon$. That is, $|f(g(x))-f(L)|<\epsilon$. We are done.
Answer: For any $\epsilon_1 > 0$ there exists a $\delta_1 > 0$ such that $|x-c|<\delta_1 \implies |g(x) - L|<\epsilon_1$
And, for any $\epsilon_2 > 0$ there exists a $\delta_2 > 0$ such that $|u- g(L)|<\delta_2 \implies |f(u) - f(g(L))|<\epsilon_2$
In the first condition, we can choose ANY value for $\epsilon_1.$
In the second condition, we know that $\delta_2$ exists.
That means we can set $\epsilon_1 = \delta_2$
Answer: $\displaystyle \lim_{u \to L} f(u) = f(L) \text{ means } \forall \epsilon>0 \hspace{0.2cm} \exists \delta_1 > 0 \text{ such that } 0<|u-L|<\delta_1 \implies |f(u)-f(L)|<\epsilon$
assume that you were given an arbitrary $\displaystyle \epsilon_1$ then you have an  $\displaystyle \delta_1$ in which the proposition above is true. since $\displaystyle \delta_1>0$ we can simply let our choice of $\displaystyle \epsilon_1 $ be equle to $\displaystyle \delta_1$  since $\displaystyle \epsilon_1 =\delta_1 > 0  $ and it is guaranteed that for every  $\displaystyle \epsilon_1 >0 $ there is $\displaystyle \delta$ such that proposition : $\displaystyle \lim_{x \to c} g(x) = L \text{ means } \forall \epsilon_1>0 \hspace{0.2cm} \exists \delta > 0 \text{ such that } 0<|x-c|<\delta \implies |g(x)-L|<\epsilon_1$  holds
then it is also the case that for every $\displaystyle \epsilon_1 =\delta_1 > 0  $ there exists $\displaystyle \delta$ such that :
$\displaystyle \ 0<|x-c|<\delta \implies |g(x)-L|<\delta_1$ hence the proposition :
$\displaystyle \forall \delta_1>0 \hspace{0.2cm} \exists \delta > 0 \text{ such that } 0<|x-c|<\delta \implies |g(x)-L|<\delta_1$  is true as we have argued about it.


Coordinates rotation by $120$ degree

Question: If I have a point on a standard grid with coordinates say:

$A_1=(1000,0)$
  $A_2=(707,707)$

Is there a easy way to transfer this points to $\pm 120$ degrees from the origin $(0,0)$, and keeping the same distance?
So for $A_1$, the result should be something like:
$B_1=(800,-200);\  C_1=(800,-200)$
I can make this with triangles and calculate it but there should be some formula. I need a formula to use with software.
Comment: Your results are wrong : the distances are not the same.
Answer: If $f$ is your angle, $(x,y)$ becomes $(x \cos f - y \sin f, y \cos f + x \sin f)$.
So with $f=120°$, $(x,y)$ becomes $(-\frac{1}{2}x-\frac{\sqrt{3}}{2}y, -\frac{1}{2}y+\frac{\sqrt{3}}{2}x)$.
And with $f=-120°$, $(x,y)$ becomes $(-\frac{1}{2}x+\frac{\sqrt{3}}{2}y, -\frac{1}{2}y-\frac{\sqrt{3}}{2}x)$.
Answer: In general, the rotation matrix of angle $\theta$ is $$r_\theta=\left(\begin{array}{cc}\cos\theta & -\sin\theta\\ \sin\theta & \cos\theta\end{array}\right).$$
In your case, $\theta=\pm120°$, so $\cos\theta=-1/2$ and $\sin\theta=\pm\frac{\sqrt 3}2$.
You just have to apply the matrix to the vector to get the image of the vector by the rotation.

Coordinates rotation by $120$ degree


Open a Python port from Erlang: no reply messages

Question: Based on Chapter 12 of the OTP in Action book and Cesarini's book I wrote this Erlang code:
Erlang:
p(Param) ->

    ?DBG("Starting~n", []),

    Cmd = "python test.py",

    Port = open_port({spawn,Cmd}, [stream,{line, 1024},  exit_status]),
    ?DBG("Opened the port: ~w~n", [Port]),

    Payload = term_to_binary(list_to_binary(integer_to_list(Param))),
    erlang:port_command(Port, Payload),

    ?DBG("Sent command to port: ~w~n", [Payload]),
    ?DBG("Ready to receive results for command: ~w~n", [Payload]),

    receive
        {Port, {data, Data}} ->
            ?DBG("Received data: ~w~n", [Data]),
            {result, Text} = binary_to_term(Data),
            Blah = binary_to_list(Text),
            io:format("~p~n", [Blah]);
        Other ->
            io:format("Unexpected data: ~p~n", [Other])

    end.

Python:
import sys
def main():
    while True:
        line = sys.stdin.readline().strip()
        if line == "stop-good":
                return 0
        elif line == "stop-bad":
                return 1
        sys.stdout.write("Python got ")
        sys.stdout.write(line)
        sys.stdout.write("\n")
        sys.stdout.flush()
if __name__ == "__main__":
 sys.exit(main())

The Erlang code suspends at the recieve clause - it never gets any message.
I have also checked Python from a regular Linux shell - it prints out every user input (1 - "Python got 1").
Where is the mistake here? Why doesn't my Erlang code get anything back?
Answer: Does your Param contain the command limiter for Python? (in this case I assume newline, "\n").  Also, list_to_binary/1 and then a term_to_binary/1 feels kinda wrong. term_to_binary/1 directly (including the newline) should be sufficient.
Answer: There are two points:

make sure that Python does not buffer your output, try running python -u in open_port
using term_to_binary/1 and binary_to_term/1 won't work, since they assume that Python is able to encode/decode Erlang External Term Format, which does not seem to be the case. If you want to go this route, check out ErlPort


Iterating through Seq in Scala and find an element who satisfies the condition

Question: I am new to Scala and I have a Seq[String] - regex of regexes and I want to iterate through this sequence and if another string, let's call it id, matches at least one of the regexes from the string, to return true.
More clear: to iterate through all of the elements of regex and if (id.matches(regex)) for at least one, then return true, otherwise false).
Can I achieve this with the .map function or creating a find function? Thanks
Comment: [Finding an item that matches predicate in Scala](http://stackoverflow.com/a/9556600/432903)
Comment: Simply: `regexs exists id.matches`
Answer: You can use seq.exists(regex => id.matches(regex))