Can we know which variables are certain Principal components are made of in PCA?

Question: In PCA, if we have ax1+bx2+c*x3 = y, say we get 2 principal components(d1,d2) out of x1,x2,x3. Can we know which of the x1,x2,x3 and in how much magnitude were used to create the d1 and d2?
If not, how is PCA useful for determining which variables affect your outcome when all you get is a mishmash of original variables?
Comment: This link here might give a good example https://online.stat.psu.edu/stat505/lesson/11/11.4. In general PCA is used for creating informative (in the sense of variance of your data explained) low-dimensional representation of your original data were you are not so much interested in keeping your original data interpretation.
Answer: A common method for understanding how the PCs are related to the original variables is to calculate the correlation between the variables and the PC. It is important to use correlations rather than the coefficients that define the linear combinations to avoid scaling effects.
It can sometimes happen, however, that certain variables will have low correlations individually, but higher correlations in combinations with other variables. You can use the variable pairs heat map to understand not only how individual variables correlate with a PC, but also how sums and differences of standardized variables are correlated with a PC. In the graph shown below, the diagonal shows absolute correlations
between the individual variables and the PC; the upper
triangle shows absolute correlations between the differences
$Z_i − Z_j$ and the PC; and the lower triangle shows absolute correlations
between the sums $Z_i + Z_j$ and the PC.

Further details are given in Teaching Principal Components Using Correlations, Multivariate Behavioral Research
Volume 52, 2017 - Issue 5.


Need help createing the hbm.xml

Question: I'm new to hibernate and I came a cross a problem. I've read all throu the starter guides etc. on the hibernate website and I still can't come up with a solution.
I have a class like this:
public class ResultTree {
String attrName;
Map<String, ResultTree> valueMap;
String classValue;
int caseQuant;
Set<Map<String, String>> otherRules;

public String getAttrName() {
    return attrName;
}
public void setAttrName(String attrName) {
    this.attrName = attrName;
}
public Map<String, ResultTree> getValueMap() {
    return valueMap;
}
public void setValueMap(Map<String, ResultTree> valueMap) {
    this.valueMap = valueMap;
}
public String getClassValue() {
    return classValue;
}
public void setClassValue(String classValue) {
    this.classValue = classValue;
}
public int getCaseQuant() {
    return caseQuant;
}
public void setCaseQuant(int caseQuant) {
    this.caseQuant = caseQuant;
}
public Set<Map<String, String>> getOtherRules() {
    return otherRules;
}
public void setOtherRules(Set<Map<String, String>> otherRules) {
    this.otherRules = otherRules;
}

}
How should a hbm.xml for a class like this look? I'm free to create any data structure.
Thanks for the help,
MM
Comment: why do you need Set>.. you can acheive that by simply Map.. is there any specific requirement ?
Comment: You'll have to simplify your model to bring it in line with the relational model. As Ranna already pointed out, using that map within a set is really not something you map to the relational DB. Even if you find out how to map it, it's going to be a huge pain to use.
Comment: @Ranna That class is modeling a decision tree with an adition of multiple paths if an unrecognized value is found, the Set> is basicly a set of sets containing pairs .

Basicly it's a list of requirements.
Comment: You are true. But one value can have many value and many keys are possible. See i m insisting as , as far my knowledge you can not map Set>.. Using Map you will acheive the functionlity..
Comment: Map itself provides list of values.. so you dont need a SET of MAP.. follow the answer with Map entity.All D Best..
Comment: @Ranna Not exactly - there is a possibility that two "rules" (Map objects) have different values of the same attribute so I can't put them all into one Map. Would it work if I made another class containing only the Map object and mapped a set of said classes into my present class?
Comment: @kemaleq - yeah this would definitely work.
Answer: With the help of Ranna's solution I managed to model the class by dividing it to two separate classes:
public class ResultTree {
private Long id;
private String attrName;
private Map<String, ResultTree> valueMap;
private String classValue;
private int caseQuant;
private Set<Rule> otherRules;
}

and
public class Rule {
private Long id;
private Map<String, String> terms;
private ResultTree tree;
private String classValue;
}

hbm.xml has the following form:
    <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="lib.experiment.result">
    <class name="ResultTree" table="RESULT_TREE">
        <id name="id" column="RESULT_TREE_ID" type="long" />
        <property name="attrName" type="string" column="ATTR_NAME" />
        <property name="classValue" type="string" column="CLASS_VALUE" />
        <property name="caseQuant" type="int" column="CASE_QUANT" />
        <map name="valueMap" table="RESULT_TREE_LEAF" lazy="false">
             <key column="RESULT_TREE_ID"/>
             <map-key column="ATTR_VALUE" type="string"/>
             <many-to-many class="ResultTree" />
        </map>
        <set name="otherRules" table="RULE" lazy="false">
            <key column="RESULT_TREE_ID"/>
            <one-to-many class="Rule"/>
        </set>
    </class>
    </hibernate-mapping>

and
    <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="lib.experiment.result">
    <class name="Rule" table="RULE">
        <id name="id" column="RULE_ID" type="long" />
        <property name="classValue" column="CLASS" type="string" />
        <map name="terms" table="RULE_TERM" lazy="false">
             <key column="RULE_ID"/>
             <map-key column="ATTR_NAME" type="string"/>
             <element column="ATTR_VALUE" type="string"/>
        </map>
        <many-to-one name="tree" class="ResultTree" lazy="false">
            <column name="RESULT_TREE_ID"/>
        </many-to-one>
    </class>
    </hibernate-mapping>

Thanks a lot for the help!
Answer: Hope this would help you.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.ResultTree" table="result_treeid">
<meta attribute="class-description">This class contains student details.</meta>
<id name="id" type="long" column="id">
<generator class="native" />
</id>
<property name="attrName" type="string" length="100" not-null="true" column="attr_name" />
<property name="classValue" type="string" length="100" not-null="true" column="class_value" />
<property name="caseQuant" type="bigint" not-null="true" column="case_quant" />
<map role="valueMap" table="value_map">
     <key column="id"/>
     <map-key column="keyname" type="string"/>
     <element column="valuename" type="ResultTree"/>
</map>
<map role="otherRules" table="other_rules">
     <key column="id"/>
     <map-key column="keyname" type="string"/>
     <element column="valuename" type="string"/>
</map>
</class>
</hibernate-mapping>

Need help createing the hbm.xml


Proving that a particular restriction of a projection is a quotient map

Question: I was hoping somebody could help me with the following problem:

Let $\pi: \mathbb{R} \times \mathbb{R} \rightarrow \mathbb{R}$ be the
  projection onto the first coordinate, and let $p=\pi|_X$, where
  $X=(\mathbb{R}_{\geq0} \times \mathbb{R}) \cup (
 \mathbb{R} \times \{0\})$ (so $X$ should be the x-axis union everything to the
  right of, and including, the y-axis...right?). Show that $p$ is a
  quotient map, but $p$ is not an open map or a closed map.

Using a property of the subspace topology (namely that we can restrict the codomain of a continuous function and still retain continuity) $p$ must be continuous. Surjectivity is also apparent. However, I'm not sure how to prove that $p$ is a quotient map, and that it is neither open nor closed. I feel like examining neighborhoods of the origin might give a clue towards a solution, but I've tried a handful of examples of such neighborhoods and gotten nowhere. Any help is appreciated, thanks!
Comment: What is meant by $>\Bbb R$?
Comment: To coincide with your description, $X$ should be $...\cup(\Bbb R\times\{0\})$.
Comment: edited! Thanks! I think when I blockquoted, the $>$ appeared next to the $\mathbb{R}$.
Answer: Hint: (1) $\pi$ is a quotient (as it is open), hence $\pi|_X$ is also.
(2) $\{x \in \mathbb R^2 \mid x_1 \ge 0, x_1x_2 = 1\}$ is closed in $X$.
(3) $\{x \in X \mid \left|x-(0,2)\right| < 1 \}$ is open in $X$.
Answer: You can use the following lemma:

Let $q:X\to Y$ be a quotient map, $A$ a subspace of $X$, and $q'=q|_A:A\to q(A)$ the restriction. Then $q'$ is a quotient map if and only if each closed and $q'$-saturated subset of $A$ is the intersection of $A$ with a closed and $q$-saturated subset of $X$. The same is true if "closed" is replaced by "open".

We actually only need the "if"-direction. Assume that $C$ is closed and saturated in $X$. Being closed and saturated means that it is of the form $D\times\{0\}\cup E\times\Bbb R$ for closed $D\subseteq(-\infty,0]$ and $E\subseteq[0,\infty)$. But then its $\pi$-saturation is $(D\cup E)\times\Bbb R$ which is again closed.


Data matrix, predictor matrix, observation matrix, model matrix, and design matrix. What do they mean?

Question: Is there a clear distinction between these terms? To the best of my knowledge:
Suppose we have $N$ observations and $p$ predictors.

predictor matrix $\in \mathbb{R}^{N\times p}$ is synonymous to observation matrix and data matrix. They contain the raw, untreated data. design matrix refers to the same concept in the context of a designed experiment.
model matrix is the result of applying some basis expansion* to the predictor matrix.

However, according to Wikipedia, design matrix and model matrix are synonymous:

In statistics, a design matrix, also known as regressor matrix or model matrix or data matrix, is...

Furthermore, MathWorks offers a function to

Convert predictor matrix to design matrix

* see Elements of Statistical Learning, chapter 5 and this question
Answer: I wouldn't get caught up in the terms. Just know they are referring to your data. Every discipline (engineering, CS, statistics) has different terms for the same thing.
However, to dive in to the detail, if your data is all numerical (no categorical data), then the model matrix = design matrix because there are no categorical values to expand on (no contrasts). A design matrix will most likely contain categorical values like gender, race, or some other type of binary/categorical status. A categorical matrix with these categorical values need to be one-hot coded to be numerically meaningful. Then, depending on your contrasts settings, you may see k-1 categorical vectors from the k categorical values.
An example of these types of settings are included in R's documentation contrasts.
Depending on your settings, you may see the following:
> warpbreaks =  warpbreaks[order(runif(dim(warpbreaks)[1])),] ## random shuffle
> head(model.matrix(breaks ~ wool, data = warpbreaks)) ##
     (Intercept) woolB
30           1     1
39           1     1
32           1     1
16           1     0
6            1     0
7            1     0
> head(model.matrix(breaks ~ wool - 1, data = warpbreaks))
     woolA woolB
30     0     1
39     0     1
32     0     1
16     1     0
6      1     0
7      1     0

Python's patsy also has similar settings.
Comment: I am not asking because I have trouble understanding what the words refer to in any particular case. Rather, the motivation behind my question is to get a 'dictionary definition' that tells you how to use the words in all different contexts and areas.
Comment: These concepts are generalized across multiple disciplines so it's natural to see multiple names for the same thing. Like I mentioned earlier, I wouldn't get stuck on the definition for this, they're just referring to your data.
Answer: The answer by @Jon states that these terms are just synonyms. I do not agree with that. Certainly there will be differences in use between disciplines and softwares, so you must always look out for the authors/programmers definitions.
But there are at least two different concepts here:

The raw data matrix just containing the data. In R this would be represented as a data frame. This do not depend on the model that you is going to fit, so can be defined before modeling. The data matrix, variously named.
The model matrix, which also depends on the model you are going to fit. Here polynomial terms will be expanded in some polynomial basis, spline terms will be expanded in some spline basis, and so on. A column of ones for the intercept might be included. Categorical variables represented by dummys or some other categorical encoding scheme.

Some examples:

A very simple example, a response $y$ and a predictor $x$. Simple linear regression will have a model matrix with $1,x$, polynomial regression maybe $1, x, x^2, x^3$.
A more complex example. A large dataset with variables $y, x_1, \dotsc, x_{100}, \text{cat}$ where the $x$'s are numerical variables and $\text{cat}$ is a categorical variable with 30 levels. That last one can be coded with dummys $d_1, d_2, \dotsc, d_{30}$. Usual multiple regression fitted with OLS will use a model matrix $1,x_1, \dotsc, x_{100} , d_2, \dotsc, d_{30}$. (One dummy must be left out for identifiability, doesn't really matter which. But the same multiple linear model fitted with ridge or lasso (or some other regularization) will need $1,x_1, \dotsc, x_{100} , d_1, \dotsc, d_{30}$ (all dummys must be included, see Dropping one of the columns when using one-hot encoding.  Another theme is that with regularization you might want to standardize the predictors What algorithms need feature scaling, beside from SVM?, so the model matrix will include the standardized $x$'s, not the original ones. But some softwares will do that for you ...

So while data matrix just includes the raw data (or maybe after some common preprocessing), the model matrix will/can depend in addition on the model to be fit, the method of fitting, and the software used.


unset the path for the library used by FullCalendar

Question: I am using FullCalendar module to display some events. I had to modify the design of the calendar and the only solution was to alter the way javascript of fullcalendar displays events and so . Now i do not want that at an update of the fullcalendar, all the changes i have made to dissapear.My question is how can i unset the path of the current fullcalendar library and set the path to my own customized library ?
Comment: Try this: check where in the module the JavaScript library is getting included. Now change the path to your customized library
Comment: @subhojit777 i know where it is but how can i do it permanentlly ?
Comment: You need to change that in fullcalendar module
Comment: @subhojit777 and if the fullcalendar module is updated without me knowing about it ? It will not render my file anymore...
Comment: well this is the custom work you are doing in a contributed module, so you have to be careful when the module is updated
Comment: @subhojit777 well all your comments were not helpful at all
Answer: When you update a module what ever changes you have done would automatically be over written. if you have just made changes to js then it would be better to add that JS to your theme rather than the module itself.
You could you the hook_js_alter (On Drupal 7) or jsalter (On Drupal 6) in yout theme to remove the module specific js.
Comment: It will , but if there it is a hook or in theme something that rewrites an entry in the array then does not matter how much updates are made because it will rewrite the path everytime... The only problem is if the fullcalendar changes the entries in the array.
Comment: That would be an issue. But you could effectively remove all the js from the specific module. and add the js through theme.
Comment: Could you provide me an example of how could i do it ?
Comment: what version of drupla are you using?
Comment: http://pastebin.com/JrEczaUm
Comment: That assumes that the file is in sites/all/modules/fullcalender folder. this would unset all the js files in the fullcalender module
Comment: Thank you for support, I am using drupal 7.I see how to unset but how do i add my file and how would fullcalendar know about it ?
Comment: You can use drupal_add_js - http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_js/7
Comment: tried your solution but it does not seem to work ...
Comment: could you send me the code?
Comment: http://pastebin.com/TxcG8ctY
Comment: is the name of your theme "theme" if not you need to replace that with the name of your theme.
Comment: lol i know that , in my code is replaced but for you i have changed back to theme ...
Comment: :-) which part of it is not working for you? the unsetting part or the adding part?
Comment: unset part , the file is still loaded after a dsm() call ( at the end of function off course).
Comment: have you checked if it is actually called in the page?
Answer: According to this issue FullCalendar should support the Libraries API module - http://drupal.org/node/980886
Comment #7 is especially relevant I believe.
This means you should be able to use Libraries http://drupal.org/project/libraries to handle getting your customized version of the library to be used instead of the bundled one.
Ie. Make sure it is named the same as the original and stick it in sites/all/libraries


What properties of a chant can be used to encode information (w/o lyrics)

Question: I am currently researching for a (fictional) draft and need help. I am a complete layman in music and musical theory.
A single person or a group of people is singing a song to control a machine, which has a vocal interface.

The lyrics are not used in this process
They may be backed by instruments, but the chanting is the important part

The machine can be "instructed" to do the following (not complete, here to give you an idea):

work slower / faster
increase / decrease working intensity
end the processing of a single piece of work and go to the next.
pause work and save energy (note: silence will stop the machine at once if longer than a "normal" pause in a song, so this cannot be encoded with prolonged silence)
Fuse two or more simple pieces of work to a more complex one.
There should be a possiblity of "doing it wrong" with dangerous consequences (e.g. malfunction, energy discharge)

What I want to do is to somehow "map" vocal input (as a song) to these machine actions. A properly chanted song is then a chain of working instructions which will produce a fixed outcome.
Which properties of chanting (e.g. volume, pitch, speed, melody, rhythym) can be assigned to this outcomes?
Note: I am a complete layman. Should I choose other properties of a song?
How could the structure of a song (recurring themes etc.) be used to encode information?
Are there "laws" for a harmonic song, which if not obeyed could produce suboptimal to very dangerous results?
Is this the right stack exchange to ask this question?
EDIT: Thanks to David Vogel
This is not for a practical application. The machine can do whatever I want it to do. My question is about which properties of a human chant are best suited to transfer "reliable" information.
Answer: It's a little unclear to me what you are trying to do with this, but here are some thoughts:
Pretty much any audio property can be used to control this system granted you have the ability to analyze the input and know how to map it to the control value.
If you do not want/need the input filtered out, you could use a glockenspiel, for example, which will produce a very identifiable amplitude and frequency change which can then be mapped to the control value you desire.
If you cannot have a noticeable change in the sound like that, it is much more difficult. You would have to use an identifiable change in pitch (frequency), rhythm (time), amplitude (volume), or timbre (frequency spectrum--probably something other than a voice).
Comment: The main components of a chant are the melody/harmony (frequency and frequency spectrum), the way it progresses through time (rhythm), and the "loudness/volume" (amplitude). The values for these components can easily be captured and analyzed. It would be up to you how you would want to map these values to control other aspects of the project. There are no "laws" unless you are trying to adhere to the conventions of some specific style.
Comment: It might be useful to do some historical research on uses of music to communicate information between humans, for example military bugle calls, and various type of signalling horns (e.g. Swiss alphorns) that were used for communication in mountainous regions of Europe. There is no obvious reason why a machine couldn't be built to recognise the same type of messages.
Comment: This is not for a practical application. The machine can do whatever I want it to do. My question is about which properties of a chant can be used to tranfer information. Thanks for the valuable input!
Comment: In that case, the last paragraph gives you the properties of a chant which could be used.
Comment: Would you mind to elaborate on the last part? How would you advise to map this properties to an outcome? Are these 4 properties all there are, or could you point out some more? Are there "laws" of harmony?
I know this may be highly subjective, but I find this hard to form out properly.
Answer: You can pretty much do all the things that are used in digital communications (theory and practice).  For examples:
Code by pitch , aka the tune.
Code by rhythm, i.e. half, quarter, eighth, etc. notes act as Lev-Zimpel compressed data bits.
Code by meter - which is closer to FM broadcast, sort of, in that you're sending information over the speed rather than the "carrier" tune.
Code by amplitude, rather like AM broadcast.
Or any combination of the above.
Further, dunno if you've heard of the method used in cable/internet traffic: "QAM" , or quadrature amplitude modulation. This basically sends the same data twice, out of phase, for error correction.  A "canon" would do this :-)


drupal_add_js and drupal_flush_all_caches

Question: I was trying to call drupal_add_js in the callback of a button. It seems, even with after_build, that this can be done successfully only you are working without cached data.
So, before i start the page, i run drupal_flush_all_caches, and the javascript is successfully added to the page.
The problem is I want to get some user input data from a form, pass to the javascript and exibit the result. The way i'm trying to do, it is getting a string that contains the processed values and concatenating with another string that contains the other part of the javascript (probably this is not a good practice), and calling this string with drupal_add_js. But, when if i call drupal_flush_all_caches, the form will be reset and i will not be able to get the data.
So, my questions are: How can i pass values from a form to a javascript?
Do i need to flush all caches every time to use drupal_add_js?
Is there different solutions to deal with this during development and production?

Thanks for the help guys. I found some answers:   How can i pass values from a form to a javascript? I had to name my variable as Drupal.settings.myModule.myVar in the javascript code. This way i can pass variables from php code to javascript. If you want to modify the javascript code you really need to flush caches. Until now, i have not found nothing about differences between production and development best pratices.
Comment: Do you pass only data from the user function to the javascript which is added to the page, or also javascript code?
Answer: Is there any problem with writing a menu callback that does this, and processing in PHP?
If you must use JavaScript for the processing, why not intercept the user's value in JavaScript and never "really" submit the form?
Answer: I think you can add the javascript using Drupal.behaviors. This will ensure that the javascript code gets reloaded even if the page is cached.


Ruby rails iniciante

Question: Como crio um programa onde EU USO meu Nome e outputs com uma saudaçâo?
Comment: ruby é uma linguagem de programação, ruby on rails é um framework feito usando a linguagem ruby. Sua pergunta não deixa claro onde é que vc tem o problema.
Answer: TL;DR
puts 'Qual é seu nome?'
nome = gets.chomp
puts "E aí, #{nome}!"

Sobre Ruby e Rails
Ruby é a linguagem. Ruby on Rails é o framework para construir aplicações web.
A minha recomendação é que você estude primeiro a linguagem Ruby e depois se aprofunde no framework Rails. Isso vai fazer você sofrer menos na curva de aprendizagem.
Brincando com I/O em Ruby
Tendo instalado o Ruby em seu computador, basta criar um arquivo ola.rb (.rb é a extensão de arquivos Ruby) e começar a programar.
Para imprimir um texto na tela, você pode usar o método IO#puts. puts vem do inglês "put string".
puts 'Olá, meu nome é user104809!'

E é assim que se imprime um texto no console em Ruby. Para rodar esse código, basta executar ruby ./ola.rb no seu console.
Para receber o nome do usuário, pode usar o método IO#gets. Ele vai ser responsável por capturar um input do usuário. Como ele retorna uma String com uma linha em branco no final (/n - sequência de escape), eu irei retirar utilizando o String#chomp.
puts 'Qual é seu nome?'
nome = gets.chomp
puts "E aí, #{nome}!"

O resultado fica algo como:

Veja que no último IO#puts, eu utilizei uma interpolação de string (#{nome}). Não se assuste! É bem simples. Ele só vai inserir na string o valor de uma expressão. Ou seja:
"um mais um é igual a {1 + 1}."
=> um mais um é igual a 2.

É a forma curta de fazer:
"um mais um é igual a " + (1 + 1).to_s + "."

Com a interpolação fica bem melhor de ler, né?! As interpolações estão disponíveis desde o Ruby 1.9.
Onde aprender Ruby?
Existem algumas fontes muito boas para se aprender a linguagem. Se houver possibilidade, manda ver!

No site oficial do Ruby
Nos tutoriais interativos do RubyMonk
No getting started do Ruby em 15 minutos do Try Ruby
No livro The Ruby Way
No grupo de estudos da comunidade do Training Center (estou lá!)
Comment: Acredito que esse site pode ser de grande ajuda também: https://gorails.com/setup/ubuntu/17.10

Ruby rails iniciante


webpack duplicate code in multi chunks and sooooo big common chunk file

Question: duplicate code in multi chunks or sooooo big common chunk file
Suppose I have a SPA website. And I have a file main.js in which I config the route.
```js
define(function(){
  // suppose I define route here
  route.when('#/aaa', function(){
    // a code split point
    require([
      'services/A',
      'style/a',
      'module/a'
    ])
  }).when('#/bbb', function(){
    // a code split point
    require([
      'services/A',
      'services/B',
      'style/b',
      'module/b'
    ])
  }).when('#/ccc', function(){
    // a code split point
    require([
      'services/B',
      'serivces/C',
      'style/c',
      'module/c'
    ])
  }).when('#/ddd', function(){
    // a code split point
    require([
      'services/A',
      'serivces/C',
      'style/d',
      'module/d'
    ])
  })// and has many route configs like this
});
```

I use webpack to bundle code. My webpack.config.js like this
```js
module.exports = {
  entry: {
    main: path.resolve(__dirname, 'main.js')
  },
  output: {
    path: path.resolve(__dirname),
    filename: 'bundle.js'
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: 'main',
      async: true
    })
  ]
}
```

When I run webpack, various chunks have duplicate services/A services/B etc. code.
This is not I want.
I read webpack docs, and then I add minChunks: 2 option to CommonsChunkPlugin.
Then I run webpack again.
Now, every chunk only have its own code. But I also get a big common chunk file, which include
services/A, services/B, services/C and other shared code between various page file.
When I run these code, in page /aaa, the /aaa's files loaded, and also the big common chunk file.
Now the big problem is, page /aaa doesn't need services/B and services/C code at all, But the common chunk files contains all shared code between various page files. So the common chunk file is so big, and have many unused code.
I know I can set minChunks to bigger number, but in this way, every page file may agagin have duplicate code.
HELP
Can I have other methods to only load necessary common chunks when route to different page?
Answer: just same problem here. And I write a small test, it looks like that webpack can handle multiple common chunks. in your case, maybe we can save common chunks in service/A, service/B and service/C into service/common.js, and other common chunks still go into common.js, try this:
plugins : [
//common chunks from A/B/C go into service/common.js
new CommonsChunkPlugin(( {
            name : 'service/common',
            minChunks : 2,
            chunks : [ 'service/A', 'service/B', 'sevice/C' ]
        })),
        //this common pkg holds all the other common chunks; and in my test,
//it MUST comes out in the last of this array
        new CommonsChunkPlugin( {
            name : 'common.js',
            minChunks : 2
        } )
]

Comment: I solved the problem myself. You can find my example at https://github.com/Treri/webpack-angular-example

And my blog http://isay.me/2016/02/angular-used-project-from-requirejs-to-webpack-1.html
Comment: @Treri 天朝的,试试天朝是不是关键字
Comment: 那我觉得你可以把我用的then-loader 和 commonChunksPlugin 结合起来使用了


Why is Bayes Classifier the ideal classifier?

Question: It is considered the ideal case in which the probability structure underlying the categories is known perfectly.
Why is that with Bayes classifier we achieve the best performance that can be achieved ?
What is the formal proof/explanation for this? As we always use Bayes classifier as a benchmark to compare the performance of all other classifiers.
Answer:
Why is that with Bayes classifier we achieve the best performance that can be achieved ? What is the formal proof/explanation for this?

Usually, a dataset $D$ is considered to consist of $n$ i.i.d. samples $x_i$ of a distribution that generates your data. Then, you build a predictive model from the given data: given a sample $x_i$, you predict the class $\hat{f}(x_i)$, whereas the real class of the sample is $f(x_i)$.
However, in theory, you could decide not to choose one particular model $\hat{f}_\text{chosen}$, but rather consider all possible models $\hat{f}$ at once and combine them somehow into one big model $\hat F$.
Of course, given the data, many of the smaller modells could be quite improbable or inappropriate (for example, models that predict only one value of the target, even though there are multiple values of the target in your dataset $D$).
In any case, you want to predict the target value of new samples, which are drawn from the same distribution as $x_i$s. A good measure $e$ of the performance of your model would be
$$e(\text{model}) = P[f(X) = \text{model}(X)]\text{,}$$ i.e., the probability that you predict the true target value for a randomly sampled $X$.
Using Bayes formula, you can compute, what is the probability that a new sample $x$ has target value $v$, given the data $D$:
$$P(v\mid D) = \sum_{\hat{f}} P(v\mid \hat{f}) P(\hat{f}\mid D)\text{.}$$
One should stress that

usually $P(v\mid \hat{f})$ is either $0$ or $1$,
since $\hat{f}$ is a deterministic function of $x$,
not usually, but almost all the time, it is impossible to estimate $P(\hat{f}\mid D)$ (except for the aforementioned trivial cases),
not usually, but almost all the time, the number of possible models $\hat{f}$ is too big, for the upper sum to be evaluated.

Hence, it is very hard to obtain/estimate $P(v\mid D)$ in most of the cases.
Now, we proceed to the Optimal Bayes classifier. For a given $x$, it predicts the value
$$\hat{v} = \text{argmax}_v \sum_{\hat{f}} P(v\mid \hat{f}) P(\hat{f}\mid D)\text{.}$$
Since this is the most probable value among all possible target values $v$, the Optimal Bayes classifier maximizes the performance measure $e(\hat{f})$.

As we always use Bayes classifier as a benchmark to compare the performance of all other classifiers.

Probably, you use the naive version of Bayes classifier. It is easy to implement,
works reasonably well most of the time, but computes only a naive estimate of $P(v\mid D)$.
Comment: Is the Bayes classifier (not naive bayes) the same as the bayes optimal classifier ???? and is $ P(v|f) $ the prior probability ?
Comment: @RuiQi I don't think that there is such thing as _the_ Bayes classifier. I am aware of the naive Bayes classifier and the optimal Bayes classifier.
Comment: @RuiQi $P(v\mid \hat{f})$ is the probability that a sample to be classified will fall into class $v$ if we use predictive model $\hat{f}$. I guess, you can call it prior probability.
Answer: The performance in terms of success rate of a classifier relates to the probability that a true class $C_T$ equals the predicted class $C_P$.
You could express this probability as the integral over all possible situations of the feature vector $X$ (or sum when $X$ is discrete) and the conditional probability to classify correct for those $x$
$$P(C_T=C_P) = \int_{\text{all possible $X$}} f(x)P(C_T=C_P|x) \text{d}x$$
Where $f(x)$ is the probability density for the feature vector $X$.
If, for some possible set of features $x$, a classifier does not select the most probable class for that set of features then it can be improved upon.
The Bayes classifier always selects the most probable class for each set of features $x$ (the term $P(C_T=C_P|x)$ is maximum), thus can not be improved upon, at least not based on the features $x$.


Failed to connect to server in ssis integrationservices in C# upon deployment

Question: I have this code
    var connectionString = "Data Source=" + servername + ";Initial Catalog=" + databasename + ";Integrated Security=True";
            var connection = new SqlConnection(connectionString);
            var integrationServices = new IntegrationServices(connection);   // ERROR HERE. Failed to connect to server.

            var package = integrationServices
                .Catalogs["SSISDB"]
                .Folders["MyFolder"]
                .Projects["MyProject"]
                .Packages["MyPackage.dtsx"];

            long executionIdentifier = package.Execute(true, null);

            ExecutionOperation eo = integrationServices.Catalogs["SSISDB"].Executions[executionIdentifier];
            while(!eo.Completed)
            {
                eo.Refresh();
                System.Threading.Thread.Sleep(5000);
            }

During development, no error is encountered but when I web deploy it, error occurs when I instantiate integrationServices like
    var integrationServices = new IntegrationServices(connection);

It is saying "Failed to connect to server". I know the error because when I console.log the error in my browser, it says so. So something is preventing me to connect my integrationservices.
Can anyone give me an idea on this? Thanks.
edited:
I already enabled allow remote connections
Comment: Does the SSISDB exist on the target server?
Comment: Yes, it is now on the target deploy server. But it's working on development server, where my visual studio resides.
Answer: Looks like a case of either a bad connection string or a SQL Server which doesn't allow 1433 port connections.
do the following:

wrap your whole code under a try catch
on error, try to display/log the connectionString variable value.

once you have that, either it'll show as an incorrect value. (possibly because the Dts variables or the source of your servername/databasename variable values are not set) OR the Sql server is not allowing remote connections. (you need to open up the ports)


How can I improve in melodic dictation for real?

Question: And/or how can I improve my melodic memory?
I think I have a little problem with this, because whenever I'm practicing melodic dictation, either at teoria.com or EarMaster -and even at solfege classes, I'm a beginner of course- I can figure notes and duration but even four bars are too much for me to remember... I can't easily fix it at my memory (to recall it several times in order to transcribe it) This last, is the advice teachers has given me in order "to never fail at melodic dictation" since, according to them, if you memorize melody you can play it as many times as needed and than you'll be able to transcribe easier. But this doesn't seem to be working for me, because of the memory issue I'm describing.
Is this memory issue normal in beginners?
I don't usually have problems with memory, au contraire, I have an outstanding memory for words... But I suppose one can remember things one doesn't understand fully, so what can I do?
I do it fine if I go listening bar by bar, or two bars by two bars, but that's simply impossible at classes because we have limited auditions of the melody, and everytime is played fully...
In adition, any different method, tip or advice on improving this is welcome.   Teachers just tell me to "study hard" but that tip above is the only thing they give me. I don't have a well defined study routine, so I'm looking for one. Please, help me!
Comment: Do your teachers tell you to "practice daily"? Because that's what I'm thinking would help most.
Comment: Sure, they have, but not exactly how and I'm not sure I'm doing it in a proficient way so that is why I asked this.
Answer: Generally speaking, melodic memory is like any other "type" of memory. We improve it by using mnemonic and "chunking" techniques, by getting more familiarized with the subject matter and, definitely yes, by practicing regularly.
By "chunking" I refer to any kind of approach where you memorize a single property of a group of items, rather than each individual item (like "first 10 letters of the alphabet, rather than a-b-c-d-e...).
Familiarity is also important. It's much easier to memorize an arbitrary list of first names in your mother tongue than in a language that's completely foreign to you.
So in a way, although I understand what your teacher is trying to say, and I agree that trying to memorize the melody is important, I don't agree with completely separating memorization ability from the dictation ability it self, as most of the skills required for dictation are also required to be able to memorize an extended melody.
Again, a daily life example, you'll have no trouble at all in memorizing a normal sentence in your language, but it will be much more difficult memorizing the exact same letters in a totally random order.

So, in melodic dictation, what are the "words" that can be used to help us memorize/recognize the notes?
Most melodies don't have completely arbitrary sequences of notes (not all the time any way), they usually are made of segments that follow specific patterns, with an interval leap here and there.
So, when you're trying to memorize a melody, it helps if you look out  for patterns that can easily be recalled, namely scales, arpeggios, and other common sequences.
Familiarity with all intervals is of course critical, as is scale degree identification within a tonality (e.g., given the tonal center, know when you hear a specific degree of the scale).
So, to give an example, if you have, in C major, a melody like "C-E-G-C-B-A-G-F-E", you can identify an arpegiated major chord starting on the tonic, followed by a descendant diatonic scale down to the mediant ("third degree"). This knowledge need not replace the "audiation" memory you may have of the melody "in your head", but both types of memory reinforce each other.
Of course not all melodies are made purely of scales and arpeggios, and it helps to practice with some simple patterns (e.g., with scale degrees, 1-2-4-5, 1-3-4-5, 1-4-6, 1-3-2-4-3-5-4, etc.,etc.). It's not possible of course to memorize all possible note sequences, but with time you'll recognize more and more and it will become easier to instinctively identify unfamiliar ones.

BTW, an excellent (and completely free!) resource that can complement what have with your teacher and that will allow to practice alone in a progressive way is the Musical Dictation: Tonal Ear Training website, from the Canandian univerity Cégep Marie-Victorin. They provide for download a full set with literally hundreds of dictations that follow a progressive schedule, for example, the first level:

1 The pentachord
2 The tonic chord
3 Tonal attractions
4 The upper tetrachord
5 6-7-1 motion
6 The dominant triad
7 The dominant 7th chord
8 The dominant 7th chord without root
9 Melodies containing stepwise sequences

As you can see they introduce different types of common patterns, little by little.

So, to summarize, melodic memory, ear training for melodic dictation and ear training related to music theory are not skills that can be compartmentalized from each other, but must be practiced in a coherent way. If you have difficulty with longer melodies, keep practicing with smaller segments, but trying to recognize "the language", not just trying to repeat in your head the sounds you've heard. Keep practicing recognizing intervals, tonal degrees, scales and arpeggios and other simple patterns. Increase the difficulty in a gradual way, and, as commented Todd, practice daily
Comment: These make sense, I'll follow this advice. Thanks for the time taken for such complete answer.
Comment: coincidentally, I've just came across this article which also focus some of the issues I mentioned in my answer
https://www.alfred.com/blog/audiation-foundation-music-learning-theory/


HP ProLiant DL180 Gen9 modding/cabling

Question: I bought a HP ProLiant DL180 Gen9 server in 12LFF drives configuration. Now I'd like to put two additional 2.5" SATA drives inside the case to serve as system drives.
As there isn't a default spot for that inside the case, I thought on using this.
It fits nicely as you can see on the image

Also, I've ordered another riser cards, so I can fit both of these brackets.
Now, as this is a 12LFF configuration, it comes with P840 controller (in the lower-right corner).

It also has embedded B140i controller on the system board (below the P840). I bought the cable to connect SATA disks to a Mini-SAS port on the B140i.
Remaining part is to somehow power these additional drives.
Some DL180 models can be stuffed with an optical drive (though this on cannot, but the system boards are/should be the same). Documentation shows that the optical drive power and the hard drives power come out from the same port (go back 3-4 pages). The port and the connector are here.

Those 5 unused pins made me think they are "reserved" for that optical drive.
The real question is: can someone help me to figure out the pin-out of the remaining pins? A friend of mine and I have disassembled the whole casing, took the system board out in hope of finding the power lines on the bottom side of the board, but it looks like they are in some middle layer. The last resort is to find pin-out by using a voltmeter, but I don't know if I could make something let out the blue smoke :)
Advices? Hints?
Thanks in advance,
Ognjen
Comment: Why are you trying to mod this server? This is wholly unsupported and defeats the purpose of buying server-class equipment.
Comment: Those 2 additional hard drives are to serve as a system drives. The budget is not that great, but the storage space needs are. I couldn't find an affordable server with dedicated 2.5" slots inside the case, hence the modding. But it isn't some mumbo-jumbo modding. It's using existing stuff for a bit different purpose...
Comment: You can create a system volume on the main drive array.
Answer: What's the real goal here?
If you're just trying to get a pair of disks separate from the main drive array, why not use a PCIe SSD?
Otherwise, you're butchering perfectly good and serviceable equipment and increasing the risk profile of the system by making bad modifications.
The other approach to get a system drive or space out of an HP Smart Array is to create multiple Logical Drives on the same array. Most people don't know this is possible, but you can have multiple logical drives of the same or different RAID levels on the same Array (group of physical disks).
That's how this should be done if you intend on using the hardware RAID controller to its full potential.

There are really cheap PCIe SSDs that can work for you. There's even a better bracket option that can work.

But I was trying to illustrate that you don't have to waste two slots for the system drives. It's possible to make multiple logical drives on the same array using HP's tools.
Comment: As I've already stated in previous comment, "The budget is not that great, but the storage space needs are.". Why not PCIe SSD? Expensive as hell... I don't think I'm butchering anything... There are free PCI slots - I'm using them; there are free Mini-SAS port on RAID controller - I'm using them; there is power available on the board - I'm using it. The front drive slots are to be populated with 6TB drives, in a RAID 6 configuration. I don't want to waste 2 6TB slots for a system drives. That's the main point here.
Comment: Also, I don't get you... Why so much hate? I asked for a help with figuring out a connector pin-out on some server board, not to hear moral lectures. On the other hand, I wanted to show you guys the full story behind the pin-out question. Though it would be more interesting for you to answer on that than some plain connector issue with no background story...
Comment: @geewid The point was to inform you that it [is possible to create logical volumes](http://serverfault.com/questions/725191/what-raid-configuration-do-i-actually-have/725199#725199) on your main disk array to hold the system drives and your data. But the other point is that there are better PCIe brackets and adapters out there, too. See my edit above.
Comment: I'm aware of the logical volume possibility, but thanks anyway. I've already bought two of WD Red 1TB 2.5" drives for this purpose. Front will be populated with Red Pro 6TB drives. These system drives will also host some virtual machines, so I wanted to leave P840 to deal with NAS storage load only and to use embedded B140i for system storage load (which would otherwise remain unused). Btw, Delock has a pretty good German quality stuff. This bracket has hot swap support, so no hassle with drive replacement like on the one you suggested.
Comment: You may run into issues using non-HP drives, too... Gulp.
Comment: Well.. There is an older HP server (G5) currently in production. Working with non-HP drives all the time. RAID + Backup keeps issues at bay. Also, this WD Red series are marketed as NAS drives, so... If it's OK for Synology/QNAP solutions, it's OK with me :) Thank you for your help and your time...

HP ProLiant DL180 Gen9 modding/cabling


In drupal 7 I want to crop same image for different device ratios. How can I do this?

Question: In drupal 7 I want to crop same image for different  device ratios. How can I do this.
On uploading image and We have to crop for different ratios.
Answer: You can use picture module combined with breakpoints module. Worked perfect for me.


Minha controller não encontra a view

Question: Fiz um controller chamado Email. Na ActionResult eu dou um Add View e crio a view. Quando eu clico com o botão direito em cima da ActionResult e dou um Go to View, diz que não encontrou a view, mas se clico com direito em cima da View e dou um Go to Controller ele acha o Controller. O que pode estar errado?
Comment: Qual o nome da *View*? Existe um arquivo de extensão `.cshtml` com o mesmo nome da *Action* num diretório dentro de `Views` com o mesmo nome do *Controller*?
Comment: Sim, a View se chama Email.cshtml.A mensagem é: `Unable to find a matching view`
Comment: Alguma coisa na nomenclatura deve estar errada. Pode tirar uma foto da tela com o Visual Studio e colocar na sua pergunta?
Comment: O *Controller* é `EmailController` e a *View* é `Email` também? Ali não vejo uma *Action* `Email`. Vejo só o *Scaffold* padrão.
Comment: Foi mal pessoal. Eu tive que refazer o projeto e dessa vez esqueci de renomear de Index para Email a Controller. Peço descilpas a todos. Valeu @CiganoMorrisonMendez, obrigado mais uma vez.
Answer: É algum problema de nomenclatura. Pela foto que você tirou, não vejo a Action Email no seu EmailController.
Experimente criar a Action e tente novamente.

Minha controller não encontra a view


Computation differences of RBMs and CNNs

Question: CNNs often surpass RBMs in most computer vision tasks in terms of classification accuracy. However, has there been any analysis comparing the following factors:

Hyper-parameter sensitivity
Amount of training data required
Computational power/time required

Note that I do understand that RBMs and CNNs are two completely different algorithms, as covered in this question. However, they can and often are, both used for classification. Even though in classification, the RBM is mostly just used as a feature extractor for an SVM.
Comment: Note that I usually ask these very application-heavy questions on cs.stackexchange.com, but I thought I would try this site this time.
Answer: If RBM reference to a Restricted Boltzmann Machine than there is no reason to compare RBM and CNN, because they are completely different algorithms. CNN is supervised algorithm and RBM is unsupervised. They are trying to achieve different goals in different ways.
Comment: Right. I'll add more detail to my question.


Proof with derivatives (most likely induction)

Question: Let $f:\mathbb{R} \rightarrow \mathbb{R}$ be given by an equation
$$f(x)=(\sin(x^3))^3$$
With use of the fact that function f is odd, show that all derivatives in a form $f^{(2n)}(0)$ for $n=0,1,2, \ldots$ are equal. Maybe inductional proof will be the most suitable, but i do not know i would appreciate detailed explaination.
Answer: Hint:
$$f''(x)=\displaystyle{\lim_{h \to 0}}\frac{f(x+h)-2f(x)+f(x-h)}{h^2}$$
Once you see what happens, induction should follow easily.
Answer: You can show using induction that for any function $f : \Bbb R \to \Bbb R$ given in the form of $f(x) = p[\sin(x^3), x] $ where $ p(s, t) $ is a bivariate polynomial of $s$ and $t$ $f^{(n)} (x)$ is also a polynomial of $\sin(x^3)$ and $x$.
To be a it more formal you can write down the general $f$ in the form,  $$ f(x) = p[\sin(x^3), x] = \sum_m \sum_n (\sin(x^3))^m \cdot x^n \;\;\;\; m, n \in \Bbb N$$
And it is easy to see that any bivariate polynomial whose terms are multiples of powers of $x$ and $\sin (x^3)$ takes the value $0$ at the origin.
Answer: Show that any odd differentiable function $f\colon (a,b)\to \mathbb R$ has even derivative $f'\colon (a,b)\to \mathbb R$ and that any even differentiable function $g\colon (a,b)\to\mathbb R$ has odd derivative $g'\colon (a,b)\to\mathbb R$.
Then $f$ is odd, $f'$ is even, $f''$ is odd, $f'''$ is even...


Guitar - How to play two-string mini-barre chords?

Question: How chords that require two-string barre should be fretted to avoid constraining other fingers in terms of general practice tips?
See example below. My 2nd finger tends to block the D string. It is pretty tricky to fret this chord starting from bass note (piece may require it being played first).
I try to curve 2nd finger more and place fingers parallel to frets and perpendicular to the fretboard but it is still quite hard to press the barre with 3rd. Any tips for this case and in general?

   4
   3
   3
   1
   2

E -10
B -8
G -8
D -6
A -8
E --
Answer: I can't give particular tips for that chord, it's hard to give a solution to a problem you've never experienced. but here's a general overview for how I learn voicings:
Try practicing similar but easier chords to come to grips with a tricky new voicings.
eg the F13 might be easier than the Fm13 you are aiming for.
F13: 10-8-8-7-8-x
if that is also tricky try get the 9 chord well practiced and then simply add the 13 with your pinky.
F9: 8-8-8-7-8-x
and also try the same idea with this
  F6/9:  8-8-7-7-8-x
and F6/b9 8-7-7-7-8-x
and F7add6 10-10-8-7-8-x
or 10-10-8-10-8-x
and F7#9#5 9-9-8-7-8-x
or myriad other voicings that use partial bars and similar fingerings.
Playing to a metronome and comping through all the voicings your currently working on is a good musical way of getting many voicings down quickly. play them in various order and with various roots and come up with voice leading moves and different top melodies, play through progressions you know (ii V i's etc) etc etc. You can also work on other technique simultaneously, 16th note strumming, fingerpicking etc etc
If your serious about learning lots of great voicings the renown Ted Greene books are amazing.
Answer: You are on the right track, but right now you are biting off more than you can chew. You need to get a good grasp of the basic shape before you can play that chord.
Let's look a the shape:

E -10
B -8
G -8
D -6
A -8
E --

The way to play this is to use your 1st finger on the D string, use your 2nd finger on the A string, use your 3rd finger for the B and G string, and use your 4th finger on the E string. It's not the easily shape right now so let's simplify it just for a moment. Right now we will forget about the 10 on the high E string and just bar the E, B , and G string with your 3rd finger to give us this shape:

E -8
B -8
G -8
D -6
A -8
E --

Is it still too hard to bar the 3 strings? Lets take the shape up to the 12 fret:

E -12
B -12
G -12
D -10
A -12
E ---

Is it still too hard to bar the 3 strings? Then we need to make your 3rd finger stronger. Just barring those 3 string with your 3rd finger and making sure all ring out should be a good finger strength exercise:

E -12--11--10--9--8--7--6--5--4--3--2--1
B -12--11--10--9--8--7--6--5--4--3--2--1
G -12--11--10--9--8--7--6--5--4--3--2--1
D --------------------------------------
A --------------------------------------
E --------------------------------------

If your fingers aren't strong enough for a certain shape, you need to make the stronger through practice. It's not always easy, but it's what you have to do.
Answer: Fretting non-barre chord first (3rd finger frets only one note) is useful because it helps to remember correct placement of other fingers. Make sure there no string blocking occurs.
Next, learn to adjust only 3rd finger so that it can fret barre. You will initially need to place it almost between strings so that when it straightens it will firmly fret two strings while other fingers will remain static.
This method worked for me after some practice.
Answer: Yes, your approach to the fingering is wrong as pointed out. The first finger should be on the lowest fret.
Generally speaking, if the you look at your finger position on the neck, think of one "finger per fret" with your first finger on the lowest fretted notes (lower=closest to the end of the neck with the tuning machines and nut) and your fourth finger taking the highest notes.
Good luck! Just keep practicing and you will get it! :^)


Como eu posso gravar informações com Arduino?

Question: Estamos desenvolvendo um sistema de leitura para verificar parâmetros de pulsos elétricos que são medidos direto da rede elétrica de um residencia, e para que isso ocorra  precisamos ler e arquivar esses parâmetros durante um mês.
 Seria possível fazer isso com o Arduíno(a parte de leitura de dados já esta ok)? Qual a forma de armazenagem ideal?
Comment: atualizei a resposta com mais algumas informações. Podem ser úteis.
Answer: Sim, é possível.
Existem três maneiras bem interessantes de gravar as informações geradas pelo Arduino.
Computador (via Serial RS-232 ou Ethernet)
Essa é a maneira mais básica. Você liga o Arduino em um computador (via Serial RS-232) e faz um programa (script simples) que se conecta ao Arduino e grava as informações num arquivo texto. Linguagens sugeridas para isso: Processing, Python ou Groovy.
Cartão SD
Você consegue armazenar informações no Arduino utilizando um cartão SD. Existem módulos, shields e até mesmo Arduinos que já vem com uma entrada para um cartão SD. Além disso, as bibliotecas existentes para gravação e leitura são bem simples de serem utilizadas.
Notas sobre o uso de SD com Arduino
ScadaBR (ModBus)
Uma outra opção, bem interessante é utilizar o ScadaBR. O ScadaBR é uma aplicação Java WEB (para ser executada no Tomcat). Essa aplicação consegue interpretar vários protocolos, sendo um deles chamado ModBus (via Serial RS-232 ou RS-485 ou via Ethernet). Assim, você utiliza uma biblioteca ModBus no Arduino, liga o seu Arduino via Serial no Computador com ScadaBR e configura o ScadaBR para receber informações do Arduino. A grande vantagem dessa abordagem é que o ScadaBR pode ser utilizado para vários Arduinos e para logar os mais diferentes tipos de informação. O céu é o limite.
O ScadaBR utiliza o banco de dados Derby (Apache) e nele ficam registrados as informações. É bem simples obter um período de tempo. Tem inclusive gráficos prontos.
Para você ter uma ideia do poder da combinação do Arduino + ScadaBR, na empresa que trabalho a equipe de manutenção desenvolveu uma solução com essa combinação que permite religar uma sub-estação elétrica utilizando o ScadaBR.
Resumo
Se o seu Arduino pode executar perto de um computador e o problema que você deseja resolver é pontual, vai na opção Computador via Serial. Você vai resolver isso bem rápido.
Se o seu Arduino deve rodar longe de um computador e você não tem tempo para conectá-lo via Ethernet ou RS-485, então vai pela opção Cartão SD.
Se você quer uma solução para atender vários Arduinos e outros tipos de dispostivos que conversam ModBus, vai pelo ScadaBR.
Comment: @cardoni muito obrigado cara!! Ajudou muito vou falar com a equipe sobre as suas  importantes soluções!!


Seperate /user/register fields and admin/people/create

Question: i extended the add user field by adding a role field as part of the fields that will be displayed when you click  create user in mydomain.com/user/register. With the addition of some rules, this helps me to assign automatic roles to registering users.
I however noticed that when you  add user from the admin menu in People>Add user, this roles fields are added to the already existing fields. This is undesirable because the Add user page already have a section where you can pick the role. This therefore makes the form to have 2 different section where you can pick roles.
I want to hide my custom role field in mydomain.com/admin/people/create but show it in mydomain.com/user/register. Please how do I achieve this
Answer: Probably hook_form_FORM_ID_alter on user_register_form then some logic like
function MYMODULE_form_user_register_form_alter(&$form, &$form_state) {

  // Is logged in user admin.
  if (user_access('administer users')) {

    // Hide myfield.
    $form['myfield']['#access'] = FALSE;
  }
}


In David Fuentes FOM workbook 1.3, what does the arrow next to the V mean?, And the T?

Question: I'm working through David Fuentes (Berklee College of Music) FOM workbook. In exercise 1.3, what does the arrow next to the V mean in the 3rd bar?, And also the T?  I figure the T means 'Tendency Tone' in this context (if I'm correct on that), but what makes it a tendency tone?   (This is from Bach's Violin Partita #1, Sarabande-Double in B minor).  Obviously this is a C chord, with the 7th a B, but why the E#? Why a V chord (it's not, C is a iiº chord surely)? And why the arrow?
See attached screenshot. Thank you!
Comment: Can we see the cleft and key signature? Without that, we don't know what the notes are exactly.
Comment: @Dom Key signature is Bm (two sharps), in the treble clef.  Trying to respect the author and not post too much of their work. Not sure the best way to do that.
Comment: @Dom ok I posted the whole part, being that it's a Bach piece anyway.
Answer: The arrow is indicating that the chord is a secondary dominant: "five of five". In other words, the F# major chord in m. 4 is the V chord of b minor, and the preceding chord, with the arrow, is the V chord (C# major) relative to F#. Another common notation is to use a slash: V/V.
That's also why there's an E#. The iio would have an E natural (C#-E-G); the V/V chord — C# major (actually it's V7, C#7) — has an E# (C#-E#-G#).
The "T" is either indicating the "leading tone" (tendency tone), the altered pitch, or both.
Comment: @AgentZebra The "leading tone" is the seventh scale degree (raised in minor: the leading tone is always a half-step below the tonic), so called because of its strong tendency toward the tonic (it "leads" the ear toward the tonic). The chord is C#7 because of the B (marked "7") in the example: C#-E#-G#-B. This is the dominant seventh chord (V7 chord) in the key of F# major.
Comment: @AgentZebra Yes, I agree. But the reason it's a tendency tone is because it's the seventh degree of the corresponding scale. E# is the seventh degree (leading tone) in F# major; A# is the (raised) seventh degree (leading tone) in B minor.
Comment: Got it, it's kind of like a cousin chord once removed.  Thanks I youtubed secondary dominants, and understand them a little more now: https://www.youtube.com/watch?v=7omUNDQ7Xm0

So he's using the arrow to indicate a 5 of 5, a V/V. Why's it called a leading tone, wouldn't that be be a 7th scale degree?

Why is it C#7? That's the final piece of the puzzle :)
Comment: Thank you, got it, I think. He's marked the 3rd scale degree of the C# major scale as T (tendency tone) tho?
Comment: Got it, and because we're in the corresponding scale of F# maj (the V chord, C#) , that's the one that matters. Wow that's quite the puzzle for my dyslexic brain. I get I now. Thank you for your help.


what is this probability distribution?1

Question: if $X_1,X_2,X_3,...,X_n$ is a sample size $n$ and $i.i.d.$ of a random variable with distribution $f(x)$, and
$$Y=X_1.X_2.X_3.....X_n$$
what is the approximate distribution of $\log{Y/n}$ for large sample (high $n$)?
Is not information missing from this question? Because $n$ is high  I think I can assume that $f(x)$ is normal distribution, but I'm stuck on it
Comment: Not quite following here. Did you mean for $Y$ to be the product of the $X$'s?
Answer: If you mean to write $Y_n = X_1X_2\ldots X_n$ and are asking about the distribution of $\frac{1}{n}\log(Y_n),$ then this is the sample mean of independent samples of $\log(X).$ Provided that $E(|\log(X)|)<\infty,$ the law of large numbers says that this converges almost surely to $E(\log(X)).$ So the limiting distribution is a degenerate point at that value.
If we're looking to make a scale transformation so that the limiting distribution is non-degenerate, then provided we have $\operatorname{Var}(\log(X)) < \infty$ we can use the central limit theorem to conclude $$ \frac{\sqrt{n}(\frac{1}{n}\log Y_n-E(\log X))}{\sqrt{\operatorname{Var}(\log X) }}\to_D N(0,1),$$ so for $n$ large the distribution of $\frac{1}{n}\log Y_n$ looks like a $N\left(E(\log X), \frac{\operatorname{Var}(\log X)}{n}\right).$
Comment: $E(|\log(X)|)<\infty\to_{a.s.} E(\log(X))$?

what is this probability distribution?1


Programmatically create an entity

Question: I created an entity via Entity Construction Kit, Initially I wanted to use rules to create the new entity but the entity is fielded and the fields don't get exposed in rules (as of now, someone is trying to work on a patch for that), but in the interm I wanted to write a simple function that creates a entity, which I assumed would be somewhat like creating a node programmatically, but I've been at this for like 4 hours and I haven't gained an inch, I have entity_create and entity_save but they don't do much and I can't find any documentation on it.
What I'd like to see is how to create an example entity from a bundle made with eck, or through code, that is fielded.
Thanks so much
Edit: The last thing I need to figure out is how to specify the name of the fields that are attached to the entity so I can enter values for those as well.
$values = array('uid' => 1, 'field_receipt_prod_ref' => 1, 'type' => 'receipt');
$new_ent = entity_create('receipt', $values)->save();

Comment: dupe http://drupal.stackexchange.com/questions/7271/how-do-i-programmatically-create-an-entity-with-its-fields
Answer: The simpler approach is with the help of entity_metadata_wrapper().
$e = entity_create($entityType, array('type' => $bundleName));
$ew = entity_metadata_wrapper($entityType, $e);
$ew->field_name->set('value');
$ew->save();

Answer: Most of what you have doesn't look too bad. The key thing with fields that you are missing is that they have a language, that they can be multi-valued, and that the value is generally stored in a 'value' subkey. I'm assuming that the ref field is a nodereference, which means it's actually stored with nid instead of value.
The easiest thing you can do to see how this is structured is to install the Devel module, and use the Devel tab that to look at the structure. Not sure if that shows up with ECK entities, but it does for Nodes.
Try this:
$new_ent = entity_create('receipt', array(
  'uid' => 1,
  'type' => 'receipt', //bundle
  'field_receipt_prof_ref' => array(
    LANGUAGE_NONE => array(
      0 => array(
        'nid' => 1,
      ),
    ),
  ),
))->save();

Programmatically create an entity


How can I import a JSON file encoded in UTF-8 in SQL Server 2017, preserving the international characters, avoiding the "mojibake"?

Question: I tried to import json file into sql server using OPENJSON function but it returned with garbled characters. JSON data file encoded with UTF-8. Is there any parameters to use within the SQL query for this issue?
USE CreateTableJSON;
GO
INSERT INTO movies
SELECT movies2.*
 FROM OPENROWSET (BULK 'C:\Users\Mañana\source\repos\WebApplication3\WebApplication3\JSON\Deep Impact.json', SINGLE_CLOB) as j
 CROSS APPLY OPENJSON(BulkColumn)
 WITH( Title nvarchar(MAX), Year int, Rated nvarchar(MAX),
 Released nvarchar(MAX), Runtime nvarchar(100), Genre nvarchar(MAX),
 Director nvarchar(MAX), Writer nvarchar(MAX), Actors nvarchar(MAX),
 Plot nvarchar(MAX), Language nvarchar(MAX), Country nvarchar(MAX),
 Awards nvarchar(MAX), Poster nvarchar(MAX), Ratings nvarchar(MAX),
 Metascore int, imdbRating float, imdbVotes nvarchar(MAX), imdbID nvarchar(MAX),
 Type nvarchar(MAX), DVD nvarchar(MAX), BoxOffice nvarchar(MAX),
 Production nvarchar(MAX), Website nvarchar(MAX), Response nvarchar(MAX)
 ) AS movies2
 GO

I found another related question that was not answered here.
EDIT
Here is a sample JSON:
{
  "Title": "Deep Impact",
  "Year": "1998",
  "Rated": "PG-13",
  "Released": "08 May 1998",
  "Runtime": "120 min",
  "Genre": "Action, Drama, Romance",
  "Director": "Mimi Leder",
  "Writer": "Bruce Joel Rubin, Michael Tolkin",
  "Actors": "Robert Duvall, Téa Leoni, Elijah Wood, Vanessa Redgrave",
  "Plot": "Unless a comet can be destroyed before colliding with Earth, only those allowed into shelters will survive. Which people will survive?",
  "Language": "English",
  "Country": "USA",
  "Awards": "5 wins & 14 nominations.",
  "Poster": "https://m.media-amazon.com/images/M/MV5BYTUwMTY1YmMtN2U5NC00YjkzLTg0YWQtZmEwNTEzZjdkNzQ2XkEyXkFqcGdeQXVyMTQxNzMzNDI@._V1_SX300.jpg",
  "Ratings": [
    {
      "Source": "Internet Movie Database",
      "Value": "6.2/10"
    },
    {
      "Source": "Rotten Tomatoes",
      "Value": "45%"
    },
    {
      "Source": "Metacritic",
      "Value": "40/100"
    }
  ],
  "Metascore": "40",
  "imdbRating": "6.2",
  "imdbVotes": "147,487",
  "imdbID": "tt0120647",
  "Type": "movie",
  "DVD": "15 Dec 1998",
  "BoxOffice": "N/A",
  "Production": "Paramount Pictures",
  "Website": "N/A",
  "Response": "True"
}

The problematic line:
"Actors": "Robert Duvall, Téa Leoni, Elijah Wood, Vanessa Redgrave"

Comment: Welcome to Stack Overflow; can you please post a sample of json file you want to import?
Comment: Hi, @Andrea. I've added a sample JSON file.
Comment: For what it's worth, SQL Server 2019 supports UTF-8 natively.
Comment: https://stackoverflow.com/questions/12512687/how-to-use-utf-8-collation-in-sql-server-database
Answer: I solved my problem by first converting the encoding of the JSON file to UTF-16 and then using the following SQL command:
cmd.CommandText =
                    "INSERT INTO movies SELECT temporal.* " +
                    "FROM OPENROWSET (BULK '" + parameter.Value.ToString().Replace("'", "''") +
                    "', SINGLE_NCLOB) as j " +
                    "CROSS APPLY OPENJSON(BulkColumn) " +
                    "WITH( imdbID nvarchar(50), Title nvarchar(MAX), Year int, Rated nvarchar(MAX), " +
                    "Released nvarchar(MAX), Runtime nvarchar(100), Genre nvarchar(MAX), " +
                    "Director nvarchar(MAX), Writer nvarchar(MAX), Actors nvarchar(MAX), " +
                    "Plot nvarchar(MAX), Language nvarchar(MAX), Country nvarchar(MAX), " +
                    "Awards nvarchar(MAX), Poster nvarchar(MAX), " +
                    "Metascore int, imdbRating float, imdbVotes nvarchar(MAX), " +
                    "Type nvarchar(MAX), DVD nvarchar(MAX), BoxOffice nvarchar(MAX), " +
                    "Production nvarchar(MAX), Website nvarchar(MAX), Response nvarchar(MAX)) AS temporal";


Twitter not working on HybridAuth

Question: I have uploaded the website on pantheon. Users aren't able to login by using twitter provider on my website. I'm using the HybridAuth module. When I try to login, it shows this error

Fatal error: Cannot redeclare class OAuthException in /srv/bindings/6349f4db8cd54067ae94453f36acb8ec/code/sites/all/libraries/hybridauth/hybridauth/Hybrid/thirdparty/OAuth/OAuth.php on line 11

How do I fix this issue? I have a Facebook login as well and it works. And both the logins work on local host.
Comment: What is in all your error logs? Server's one? Drupal's watchdog? Browser's console?
Comment: Either that's a bug in hybrid auth, or a problem in your configuration, (such as libraries being included twice). In either case, it's not really on-topic here.
Comment: @Letharion actually problem with configuration may be on topic - if only OP will provide needed data to really answer it. Like error messages and his configuration (except sensitive data of course).
Comment: @Mołot We do have the error message though, don't we? A class is declared twice, and my first guess would be that the files are installed twice, and libraries, or some other method, includes them twice.
Comment: @Letharion i think I commented on cached, pre-edit version, sorry. Yes, it looks like bug in HybridAuth module now.
Comment: @Mołot I deleted the exception class from the OAuth.php files. Its working now.
Answer: You should update the HybridAuth library to the latest version
Comment: I have the latest version (2.2)
Answer: This is how I solved it, I removed the OAuthException class from the OAuth.php file which can be found in sites/all/libraries/hybridauth/hybridauth/Hybrid/thirdparty/OAuth/OAuth.php and twitter login started working.
Answer: I just ran into this issue. In your Twitter App settings, make sure you specify the Callback URL. Should be http://YOUR_URL/hybridauth/endpoint

Twitter not working on HybridAuth


A 2D Brownian Motion will hit any given line on the plane with probability one.

Question: I recently read about an interesting fact involving $2$-D Brownian Motions. If $B(t) = (B_1(t), B_2(t))$ is a two-dimensional standard Brownian motion, then $B(t)$ will hit any given line on the plane with probability one.
As an useful reference I believe https://www2.math.upenn.edu/~pemantle/papers/coverage.pdf can help. But I am not sure how to prove this!
Comment: The 1D property says that a BM on the line almost surely hits every point. More astonishingly:  a BM that starts at zero hits every point (as far away as you want it to be from zero) with non zero probability instantly after $t=0\,.$ In 2D the result in your title is slightly less trivial and in 3D it does not hold. Topics you should read about are recurrence and transience.
Comment: What's your background? Do you know how to prove the corresponding one-dimensional property?
Comment: I am not sure about the corresponding 1D property
Comment: The line is straight line or can be any curve line?
Comment: As per the question it is a straight line
Answer: Remark: We notice that a uni-dimensional Brownian Motion $W_t$ will reach the value $a\in \mathbb{R}$ almost surely. The proof can be found here  (the question and the accepted answer). Indeed, as $W_t$ goes to $\pm \infty$ almost surely, $W_t$ will reach any value $a$ before a time $T_a<+\infty$.

Now, in the bi-dimensional case, we will prove that the bi-dimensional BM $(B_{x}(t),B_y(t))$ will hit almost surely (which is stronger than with probability $1$) the line $(d)$ passing through the point $(x_0,y_0)$ and having the direction vector $p\vec{e}_x+q\vec{e}_y$ (with $p^2 +q^2 = 1$).
Indeed, instead of using the canonical coordonnate system $Oxy$, we use the coordinates $Ouv$ defined by
$$\begin{cases}
\vec{e}_u=p\vec{e}_x+q\vec{e}_y\\
\vec{e}_v=-q\vec{e}_x+p\vec{e}_y\\
\end{cases}
\iff \begin{cases}
\vec{e}_x&=p\vec{e}_u-q\vec{e}_v\\
\vec{e}_y&=q\vec{e}_u+p\vec{e}_v\\
\end{cases}
$$
In this new coordinate system $Ouv$,

the line $(d)$ is in parallel with the axis $Ou$ and perpendicular to the axis $Ov$. The direction of the line in the new plan is $ 0\cdot \vec{e}_u+ \color{blue}{(-x_0q+y_0p)}\cdot\vec{e}_v $
The bi-dimensional $(B_{x}(t),B_y(t))$ can be expressed in the plan $Ouv$ as follows
$$\begin{align}
B_x(t)\vec{e}_x+B_y(t)\vec{e}_y&= (pB_x(t)+qB_y(t))\vec{e}_u +\underbrace{(-qB_x(t)+pB_y(t))}_{=:\color{red}{W(t)}}\vec{e}_v
\end{align}$$

The process $\color{red}{W(t)}:=-qB_x(t)+pB_y(t))$ is Brownian Motion because $B_x(t)$ and $B_y(t)$ are two independent BM and $p^2+q^2 = 1$.
According to the Remark, the Brownian motion $W(t)$ reaches the value $\color{blue}{(-x_0q+y_0p)}$ almost surely at the time $T<+\infty$. Then, the bi-dimensional $(B_{x}(t),B_y(t))$ in the new coordinate system $Oxy$ hit the line $(d)$.
We conclude that the process $(B_{x}(t),B_y(t))$ hit almost surely the line $(d)$.
Q.E.D


Dados alterados no banco não são apresentados no DataTable do PrimeFaces

Question: Estou tentando desabilitar a cache do JPA (EclipseLink 2.5.2) através do "persistence.xml", mas não está funcionando.
Alterações feitas nas tabelas, externamente à aplicação, não são apresentadas no DataTable do PrimeFaces 5.0 com JSF 2.2.
Ambiente: Netbeans 8.0.2 + GlassFish 4.1 (com Pool de conexões)
O que pode estar faltando?
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="br.com.empresa_Teste_war_1.0-SNAPSHOTPU" transaction-type="JTA">
    <jta-data-source>jdbc/teste</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
        <property name="eclipselink.cache.shared.default" value="false"/>
        <property name="eclipselink.query-results-cache" value="false"/>
        <property name="eclipselink.refresh" value="true"/>
    </properties>
  </persistence-unit>
</persistence>

Comment: Bem-vindo ao [pt.so]! O problema não pode ser no seu *Managed Beans*, que está armazenando a lista, sem buscá-la no banco de dados quando a tela é atualizada? Qual o escopo do MB? Como está implementado o getter da lista?
Comment: Ótimo. Se quiser colocar sua solução como resposta para sua própria pergunta, fique à vontade.
Comment: Obrigado pelas boas vindas! No projeto que estou testando, as classes foram geradas automaticamente pelo NetBeans. Eu já havia testado os diferentes tipos de escopo, mas não havia percebido que o gerador não cria a anotação `@ManagedBean` na classe MB. Adicionando esta anotação e passando o escopo para `@ViewScoped` funcionou como eu desejava.
Answer: No projeto que estou testando, as classes foram geradas automaticamente pelo NetBeans. Eu já havia testado os diferentes tipos de escopo, mas não havia percebido que o gerador não cria a anotação @ManagedBean na classe MB. Adicionando esta anotação e passando o escopo para @ViewScoped funcionou como eu desejava.


Interpretation of a contour diagram

Question: Below is a contour diagram below for the sales of a product as a function of the price and the amount spent for advertising. Which axis corresponds to the latter?

If $y$ is fixed and $x$ increases, then the sales decrease. So $x$ corresponds to the price, and $y$ corresponds to the amount spent for advertising. Am I right?
Answer: Yes I would think so. If it were flipped, then for a fixed price, as the amount of advertising increases, the sales would decrease, which intuitively doesn't make sense. However it's always good to note if you're dealing with a special case, so there may be a more concrete way of going about it if there was more information presented in the problem.

Interpretation of a contour diagram


Custom Taxonomy dentro de outra Custom Taxonomy em WordPress

Question: Estou precisando criar a seguinte hierarquia dentro do admin do WordPress:
Categoria -> Linha de Produto -> Produto
Um produto pertence a uma linha que por sua vez pertence a uma categoria.
Pensei em criar uma Custom Taxonomy para Categorias, uma para Linhas.
Populá-las com os dados necessários.
O que eu preciso saber se é possível, é quando for criar um produto (post), se há alguma maneira de puxar para dentro de um select as categorias criadas e as linhas criadas para inserir no produto.
Existe essa possibilidade?
Obrigado.
Answer: Você pode fazer os produtos como custom posts e criar as taxomonias e os termos próprios pra ele.
EX:
Categoria -> subcategoria -> post
Categoria -> linha de produto -> produto
As duas correndo em paralelo e sem precisar modificar nada na hora de cadastrar o produto, ja que ele vai responder aos suas próprias categorias e termos.
Pra criar o custom do que você precisa coloque isso no functions.php:
<code>add_action('init', 'type_post_produto');
function type_post_produto() {
            $labels = array(
                'name' => _x('Produto', 'post type general name'),
                'singular_name' => _x('Produto', 'post type singular name'),
                'add_new' => _x('Adicionar Novo Produto', 'Novo Produto'),
                'add_new_item' => __('Novo Produto'),
                'edit_item' => __('Editar Produto'),
                'new_item' => __('Novo Produto'),
                'view_item' => __('Ver Produto'),
                'search_items' => __('Procurar Produto'),
                'not_found' =>  __('Nenhum registro encontrado'),
                'not_found_in_trash' => __('Nenhum registro encontrado na lixeira'),
                'parent_item_colon' => '',
                'menu_name' => 'Produtos'
            );

            $args = array(
                'labels' => $labels,
                'public' => true,
                'public_queryable' => true,
                'show_ui' => true,
                'query_var' => true,
                'taxonomies' => array( 'Categoria' ),
                'rewrite' => array('slug' => 'produto'),
                'capability_type' => 'post',
                'has_archive' => true,
                'hierarchical' => false,
                'menu_position' => null,
                'supports' => array('title', 'editor', 'thumbnail', 'revisions'),
            );

        register_post_type( 'produtos' , $args );
        flush_rewrite_rules();
        }
</code>
Com isso você só vai precisar criar as hierarquias de categorias de produto e criar loopings customizados para recuperar os "produtos".


Angular Datatable not able to assign the data from variable

Question: i am trying to assign data to dtOptions - but not works. what is the correct way to do it?
here is my function:
 getDatas(){
        this.datas = this.http.get('data/data.json').subscribe(values =>  values);//values available  here
    }

    ngOnInit() {

        this.categoryListCopy = this.categoryList;
        this.getDatas()

        const that = this;
        this.dtOptions = {

            columns:[{
                data: 'id'
            }, {
                data: 'firstName'
            }, {
                data: 'lastName'
            }],
            pagingType: 'full_numbers',
            pageLength: 10,
            serverSide: false,
            processing: true,
            ajax: this.datas
            };

        }

Answer: You just need to use  Observable, your code will look like this:
getDatas(): Observable{
        return this.http.get('https://jsonplaceholder.typicode.com/todos/1');
    }

  ngOnInit() {
        this.getDatas().subscribe(values =>  {
           console.log(values);
           // You can assign dtOptions here, you will have your data in values.
        });
  }

You can find the working plunk here.
Comment: as well how to update with adding some filter later? ( user want to see x item of data only )
Comment: You can simply use .map and .filter to filter out your response, please look for the how to use it.


How to discover events for event dispatcher

Question: I want to write an implementation of EventSubscriberInterface for an event in commerce, there is a handy example, but

How do I find out what events are available (as a whole for my site) and/or
How do I know what events are getting hit on a request?

This question is not specific to the commerce module, it is just the context of my current problem.
Comment: \Symfony\Component\EventDispatcher\Event
Answer: I was stumped by this for a while, so I was pleased to find an answer in the Devel module
Install the Devel module and look at the toolbar menu item:
"Events info" which links to /devel/events
So for the commerce events I can see the following:

Callable    Priority
commerce_order.place.post_transition
Drupal\commerce_order\EventSubscriber\OrderReceiptSubscriber::sendOrderReceipt  0

commerce_order.place.pre_transition
Drupal\commerce_cart\EventSubscriber\OrderEventSubscriber::finalizeCart 0
Drupal\commerce_order\EventSubscriber\TimestampEventSubscriber::onPlaceTransition   1
Drupal\commerce_order\EventSubscriber\OrderNumberSubscriber::setOrderNumber 2
Comment: Thanks @Duncanmoo, today you saved my life!!!
Answer: You can simply use the Drupal console.
List all the events that could be debugged:
drupal debug:event
drupal dev
Show the information for the specific event, for example "commerce_order.commerce_order.update":
drupal dev commerce_order.commerce_order.update


How prove this limits $\lim_{n\to\infty}\int_{0}^{1}g(x)f'(nx)dx=0$

Question:
let $f'(x)$ be  continuation on $R$, and $f(x)=f(x+2\pi),\forall x\in R$, and such
  $|f'(x)|\le 1$,Now define $g(x)$,such for any $x_{1},x_{2}\in [0,1]$, we have
  $$|g(x_{1})-g(x_{2})|\le \sqrt{|x_{1}-x_{2}|}$$
show that
  $$I=\lim_{n\to\infty}\int_{0}^{1}g(x)f'(nx)dx=0$$

This problem is form analysis problem book excise (MIn hui Xie)
Maybe we can use Dominated convergence theorem,but I can't use this condition
$$|g(x_{1})-g(x_{2})|\le \sqrt{|x_{1}-x_{2}|}\Longrightarrow \left|\dfrac{g(x_{1})-g(x_{2})}{x_{1}-x_{2}}\right|\le \dfrac{1}{\sqrt{|x_{1}-x_{2}|}}$$
because $\dfrac{1}{\sqrt{|x_{1}-x_{2}|}}\in (0,+\infty),\forall x_{1},x_{2}\in [0,1]$,so $g$ is not Lipschitz continuity,Then I can't
Answer: Let $[a] = \{ x : |x| \le |a| \}$ for any $a \in \mathbb{C}$.
$f'$ is continuous and periodic and $\int_{[t,t+2\pi]} f' = 0$ for any $t \in \mathbb{R}$, from the condition given.
$g$ is continuous, from the condition given.
[With $[0,1]$ being compact, the above conditions are all we actually need.]
Let $p,q \in \mathbb{R}$ such that $f' \in [p]$ on $\mathbb{R}$ and $g \in [q]$ on $[0,1]$
Also $g$ is uniformly continuous on $[0,1]$.
For any $ε > 0$:
  Let $a > 0$ such that $g(x+[a]) \subseteq g(x) + [ε]$ for any $x \in [0,1]$, by uniform continuity.
  For any $n \in \mathbb{R}$ such that $n \ge \max(\frac{2\pi}{a},\frac{2\pi}{ε})$:
    Let $c = \lfloor \frac{n}{2\pi} \rfloor$
    $\int_{[0,1]} g(x) f'(nx)\ dx$
    $ = \sum_{k=1}^c \int_{\frac{2\pi}{n}[k-1,k]} g(x) f'(nx)\ dx + \int_{[\frac{2\pi}{n}c,1]} g(x) f'(nx)\ dx$
    $ \in \sum_{k=1}^c \int_{\frac{2\pi}{n}[k-1,k]} \left( g(\frac{2\pi}{n}k) + [ε] \right) f'(nx)\ dx + (1-\frac{2\pi}{n}c) [pq]$ [because $\frac{2\pi}{n} < a$]
    $ = \sum_{k=1}^c \int_{\frac{2\pi}{n}[k-1,k]} [ε] f'(nx)\ dx + (1-\frac{2\pi}{n}c) [pq]$ [because $\int_{\frac{2\pi}{n}[k-1,k]} f'(nx)\ dx = 0$]
    $ \subseteq \sum_{k=1}^c \frac{2\pi}{n} [ε] [p] + \frac{2\pi}{n} [pq]$
    $ \subseteq [εp] + [εpq] = ([p]+[pq])ε$
Therefore $\int_{[0,1]} g(x) f'(nx)\ dx \to 0$ as $n \to \infty$
Comment: It's Nice! ..  +1
Comment: @chinamath: I think this result that I've proven is used on the function $f' = x \mapsto e^{inx}$ to show something about Fourier transforms but I can't remember.


Soundness and consistency in type theory

Question: On page 9 of the paper Simplicial Model of Univ. Foundations, we have the following brief discussion of consistency:

It seems that, assuming soundness, in type theory we have that any theory with a model is consistent. But then it must be the case that there is never such a section of $p_{0_1}$, correct? If this is correct, then how do we verify that such a section is never possible? If not, then how do we prove that having a model implies consistency (presumably in a way similar to the classical version, which follows easily from soundness)?
Answer:
any theory with a model is consistent.

This is not the case. For instance, every algebraic theory has an initial and a terminal model, but neither of these have a bearing on consistency.
The initial model is the syntax of a theory, and consistency is a statement about definability in the syntax. So the initial model is just part of the setup. The terminal model is a model where all underlying sets are given as the singleton set; e.g. the terminal category is the singleton category. Terminal models don't imply anything about the syntax; they're trivial.
There can be other models, neither terminal nor initial, which interpret the empty type as a nonempty set, and thus don't imply syntactic consistency. Consistency only follows from a model which interprets the empty type with an empty set or an analogous "empty" structure.
Comment: I'm actually confused again. When it says that Theorem 3.4.3 can be read as proving consistency, what is the justification for this? It seems, based on your explanation, that the $\mathbf{sSet}$ model they construct interprets the empty type as an empty structure.  But how do we know this is the case?
Comment: @CuriousKid7 Definition 1.4.11 introduces the empty type. Theorem 2.3.4 interprets it, they don't give any detail other than "straightforward". The empty type should be essentially the empty Kan complex in the model.
Comment: Thank you, in conclusion, would you say that the description of the relation between soundness and consistency found at https://ncatlab.org/nlab/show/type+theory#semantics_of_typetheoretical_foundations is simply incorrect?
Comment: The "Semantics of type-theoretical foundations" section is mostly from a classical model-theoretic perspective, which is rarely used in the practice of semantics of type theory. There, the notion of model is greatly restricted, the last paragraph of "Term model" mentions the notion of model which is actually used in the simplicial model paper.


Theming and designing css in Drupal 7

Question: Ok, I know this is a general question, but I really looked information for a long time, and couldn't find helpful info that helped me.
I almost finish developing my community site in Drupal 7. Now I am starting to design it. I chose Zen theme, and created sub-theme.
Can you please recommend me about the best convenient method to implement CSS to DRUPAL site?
Thanks in advance
Comment: @EdenBitton I'm sorry, but we do need to keep this closed; it's still a very broad topic.  My suggestion would be to pick up the Packt book *Drupal 7 Themes*, Cederholm's *Web Standards Solutions* and *Handcrafted CSS*, and Budd's *CSS Mastery*.  Those will get you on your way.
Comment: Hi, requests for tutorials are off-topic here - if you have a specific question about a problem you're having implementing CSS in Drupal, please edit the question to ask it. Please don't ask about CSS syntax/specificity or anything like that as questions about the language itself are also off-topic (but can of course be asked on Stack Overflow); it just needs to be a Drupal-specific question for this site. Thanks
Comment: I reworded my question. how can I remove the [on hold] feature, and get my question back live again? I will really appreciate help here..
Answer: Well that's  very vast topic, however few things I would like to share with you are:

The best place to start can be the documentation of ZEN theme: https://drupal.org/node/193318. They are having pretty good maintained doc.
Must go through tutorial is drupal's theming guide: https://drupal.org/documentation/theme
To undertand the basics of theming: http://drupalize.me/videos/introduction-theming-basics-drupal-7
How to create the subtheme: here is official doc on how to create a sub-theme as per drupal standard.
Also there is one nice video tutorial on creating a sub-theme of Zen: http://www.youtube.com/watch?v=y-IXpbdgA3A
One good answer on creating a theme with drush command: How do I create a Zen's sub-theme using Drush?
Moving further you can check how do drupal process theme variables for templates: Setting up variables for use in a template (preprocess and process functions)
It would be good to learn few of the CSS frameworks: SASS framework, LESS framework

I tried to cover few of the quick points that striked me first, but anyways there is no limit of learning, so keep on exploring!!

Theming and designing css in Drupal 7


Every compact set is an image of a compact set under a continuous open surjection from locally compact into Hausdorff space

Question: Firstly, the task:
Let $X$ be locally compact space, $Y$ be a Hausdorff space, $f:X \rightarrow Y$ be a continuous open surjection and let $K$ be a compact set in space $Y$. Prove that there exists a compact set $C$ in space $X$ such that $f(C)=K$.
I think that I have a proof, but it seems to use the axiom of choice. I have tried, but I can't decide whether I really use that axiom or not. I need a proof that doesn't use it. Please, help me prove it without that axiom, or explain me that I haven't really used it.
Sketch of my (incorrect) proof:
Since $f$ is surjective, for each $y \in Y$ there is some $x_{y} \in X$ such that $f(x_y)=y$. Let's choose $C=\{x_y | y \in Y\}$. Now $f$ maps each open covering of $C$ to an open covering of $K$ and that one has a finite subcovering. Now for every $y \in K$ there exists some open set in that subcovering that contains it, so the corresponding open set in the initial covering of $C$ contained $x_y$. The collection of all the corresponding open sets (the sets whose images are in the subcover of $K$) is finite and cover whole $C$, since elements $x_y$ are unique among those that map to a chosen $y \in Y$, so we can conclude that $C$ is compact too.
I doubt that this is correct, since I used only one of four conditions, and I think that it is because I use the axiom of choice.
Comment: The existence of $C$ does not mean that $f^{-1}(K)$ is compact as suggested in the title.
Comment: I agree with Paul Frost that the title is misleading. What you're trying to prove is that every compact set is the image of a compact set, not that every compact set has compact preimage (which is false in general).
Comment: You are right, sorry, I am not familiar with english names of things.
Answer: Your proof isn't correct, indeed. The subtle mistake is that, since $f$ is not (in general) injective, if $y\in f(U)$ you can't argue that the $x_y \in U$.
HINT: Every point of $f^{-1}(K)$ admits a compact neighborhood. Use these compact neighborhoods to get an open covering of $K$. (Keep in mind that these neighbourhoods are subsets of $X$ whereas $K$ is a subset of $Y\dots$).
Comment: Wow, that is so basic mistake, thank you for pointing it out to me! On the hint, I think I seek what you want to say, but did you mean something else other than $K$ at the end?
Comment: I meant $K$. :-) Use (somehow) those neighborhoods to get an open covering of $K$. The remaing part of the proof should follow quite naturally.
Comment: Ok, sorry :) I will try it then. Thanks


How to redirect user to login page when anonymous user click on the flag link?

Question: Redirect user to login page when anonymous user click on the flag link.
How to achive this?
I have created flag links by
<code>   function MYMODULE_preprocess_node(&$variables) {
 $node = $variables['elements']['#node'];
  $flag_link_service = \Drupal::service('flag.link_builder');
$flag_link = $flag_link_service->build($node->getEntityTypeId(), $node->id(), 'YOUR_FLAG_MACHINE_NAME');
$variables['flag_link'] = $flag_link;
}
</code>
Placed variable in twig template.
I want to do something like
<code> If ($user->uid) == 0)
 {
redirect to login
 {
 else
 {
   {{ flag_link }}
   }
</code>
Answer: I have handled this by only showing the flag element when the user is logged in.  When the user is not logged in, I have rendered out the flag graphic (eg, the heart) as a link to 'user/login?destination=whatever'.  This eliminates the need to alter the flag link, especially since it also typically has AJAX associated with it.
Comment: Is it possible to add flag link in views also,actually i am creating wishlist in which user should be able to remove item from wishlist
Comment: This is a great lead. Thank you.
Answer: I have achived this by using twig
<code>{% if logged_in %}
{{ flag_link }}
{% else %}
custom image link
{% endif %}
</code>


Why docker is not working with this config in iptables?

Question: i have installed docker but standard policy is all open.
I added this rules in iptables
 -N DOCKER-USER
 -I DOCKER-USER -p tcp --dport 80  -j ACCEPT
 -I DOCKER-USER -p tcp --dport 443 -j ACCEPT
 -A DOCKER-USER -i eth0 -j DROP

but the result is
Chain DOCKER-USER (1 references)
target     prot opt source               destination
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:443
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:80
DROP       all  --  0.0.0.0/0            0.0.0.0/0

Comment: I have the same issue.  as soon I started changng the `DOCKER-USER` chain, docker stopped adding it to the `FORWARD` chain and I can't figure out how to make docker use it again.
Comment: for whatever reason, docker isn't creating the `DOCKER-USER` chain until i reboot
Answer: You should not need to create DOCKER-USER.  It should already exist, and the FORWARD chain should use it.  I have found that you need to stop all running containers and restart docker to make it appear.