Não consigo receber token da aplicação, help!

Question: Seguem minhas classes de segurança da aplicação;
Classe OAuth2AuthorizationServerConfigJwt
public class OAuth2AuthorizationServerConfigJwt extends AuthorizationServerConfigurerAdapter{
    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("angular").
        secret(passwordEncoder().encode("@ngul@r0"))
        .scopes("read", "write")
        .authorizedGrantTypes("password", "refresh_token").accessTokenValiditySeconds(300)
        .refreshTokenValiditySeconds(3600 * 12); //na sua implemetação so tira o refresh_token
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        final TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), accessTokenConverter()));
        endpoints.tokenStore(tokenStore()).tokenEnhancer(tokenEnhancerChain)
        .authenticationManager(authenticationManager).reuseRefreshTokens(false);
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
        accessTokenConverter.setSigningKey("secret");
        return accessTokenConverter;
    }

    @Bean
    public TokenEnhancer tokenEnhancer() {
        return new CustomTokenEnhancer();
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

Classe WebSecurityConfigurerAdapterCustom
@EnableWebSecurity
@EnableResourceServer
@Configuration
public class WebSecurityConfigurerAdapterCustom extends WebSecurityConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    public void globalUserDetails(final AuthenticationManagerBuilder auth) throws Exception {
        // @formatter:off
        auth.inMemoryAuthentication().withUser("admin").password(passwordEncoder.encode("admin")).roles("USER");
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/categorias").permitAll().anyRequest().authenticated().and()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf().disable();

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/categorias");
    }

}

Clase CustomTokenEnhancer
public class CustomTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        final Map<String, Object> additionalInfo = new HashMap<>();
        additionalInfo.put("organization", " Token Custom ");
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        return accessToken;
    }
}

Classe WebMvcConfig
@Configuration
@Order(1)
public class WebMvcConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        return bCryptPasswordEncoder;
    }
}

Erro ao tentar buscar um token com a requisição abaixo:

Erro do servidor:
2020-03-24 11:17:32.963  INFO 10716 --- [nio-8080-exec-6] o.apache.coyote.http11.Http11Processor   : Error parsing HTTP request header
 Note: further occurrences of HTTP request parsing errors will be logged at DEBUG level.

java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens
    at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:416) ~[tomcat-embed-core-9.0.31.jar:9.0.31]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:260) ~[tomcat-embed-core-9.0.31.jar:9.0.31]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.31.jar:9.0.31]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-9.0.31.jar:9.0.31]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1639) [tomcat-embed-core-9.0.31.jar:9.0.31]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.31.jar:9.0.31]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_231]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_231]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.31.jar:9.0.31]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_231]

Answer: Isso pode estar acontecendo por que alguma outra aplicação está tentando enviar algo na porta da sua aplicação (8080). Se estiver usando windows rode o seguinte comando no terminal para listar as aplicações usando a porta netstat -a -n -o | findstr <porta> (Altere o  para a porta que deseja localizar) depois rode Taskkill /PID <pid> /F (Alterar o  pelo número do PID que foi encontrado na listagem do comando do netstat).


$ \sum_{j=1}^{M/2}\sum_{k=1}^{M-1}\cos{\left(\frac{2\pi}{M}kj\right)}=-M/2 $

Question: I'm trying to proof something right now. What exactly is not important. I was able to break down the whole thing to the following equation.
$
\sum_{j=1}^{M/2}\sum_{k=1}^{M-1}\cos{\left(\frac{2\pi}{M}kj\right)}=-M/2
$
This should hold for all even values of $M\in\mathbb{N}$. Any ideas? I tried to substitute both summation by a single one, but that yields to a big mess....
I checked it in Mathematica with different values of $M$.
Comment: Have you tried using $\cos x=(e^{ix}+e^{-ix})/2$?
Comment: Thank you all for your useful comments and answers!
Answer: Change to exponential notation.  Let $j$ be fixed and let $d=\gcd(j,M).$  Then $$\sum_{k=1}^{M-1} \exp(2\pi i j k/M)$$ adds up some $M$-th roots of unity.  If you were to increase the upper limit to $M$, then you'd be adding all the $M/d$-th roots of unity $d$ times, which adds to $0$.  So:
$$\sum_{k=1}^{M-1} \cos(2\pi j k/M) = \Re\left(\sum_{k=1}^{M-1} \exp(2\pi i j k/M)\right)$$
$$= \Re\left(\sum_{k=1}^{M} \exp(2\pi i j k/M) -\exp(2\pi i jM/M)\right)
= \Re(0 - 1) = -1.$$  And that should make the outer sum easy.
Answer: First, We know that
$$ \cos x = \frac{e^{ix}+e^{-ix}}{2}$$
Now assume $$ x = \frac{2\pi ji}{M} $$
We can rewrite given expression as
$$ \sum_{j=1}^{M/2}\sum_{k=1}^{M-1}\cos(\frac{2\pi kj}{M}) = \sum_{j=1}^{M/2}\sum_{k=1}^{M-1} \frac{e^{xk}+e^{-xk}}{2}$$
Let us first try to find value of
$$ \sum_{k=0}^{M-1} \frac{e^{xk}+e^{-xk}}{2} $$
Notice that in your expression $k$ is starting from $1$ but it is starting from $zero$ now.
$$ \sum_{k=0}^{M-1} \frac{e^{xk}+e^{-xk}}{2} = \frac{1}{2}(\frac{e^{xM}-1}{e^x-1} - \frac{e^{-xM}-1}{e^x-1})$$
If with put the value of $ x=\frac{2\pi ji}{M} $ in $ e^{xM} $
we get $$ e^{xM} = e^{\frac{2\pi ji}{M}M} = e^{2\pi ji} = 1$$
Similarly $$ e^{-xM} = 1 $$
And therefore $$  \sum_{k=0}^{M-1}\cos(\frac{2\pi kj}{M}) = \sum_{k=0}^{M-1} \frac{e^{xk}+e^{-xk}}{2} = 0 = 1 + \sum_{k=1}^{M-1}\cos(\frac{2\pi kj}{M})$$
$$ \Rightarrow \sum_{k=1}^{M-1}\cos(\frac{2\pi kj}{M}) = -1 $$
Hence,
$$ \sum_{j=1}^{M/2}\sum_{k=1}^{M-1}\cos(\frac{2\pi kj}{M}) = \sum_{j=1}^{M/2}-1 = \frac{-M}{2}$$
Answer: When $j<M$, $kj\bmod M$ is a permutation of the integers $0,1,\cdots M-1$.
Then by cancellatoin of the quadrants,
$$\sum_{k=0}^{M-1}\cos\frac{2\pi kj}{M}=0$$ and
$$\sum_{k=1}^{M-1}\cos\frac{2\pi kj}{M}=-1.$$
The claim trivially follows.


World cup winners qualified through play-offs

Question: Has it ever happened that a team got to the world cup through the playoff and then won the cup?
Or any team who did the playoff is historically doomed? I couldn't find any statistics, maybe you know this stuff better.
Answer: There was no such World Cup where the winner would qualify through play-offs. It's also worth to mention that qualification rules were constantly changing and sometimes winners played only few matches (if played at all, as they were hosts or defending champions till 2006 World Cup qualifiers) in order to qualify.
During the qualification phase of the 1934 World Cup Italy played only  a single match in order to qualify, which can be considered as a play-off match, but in fact was a group stage match.


Error when inserting in to MySQL

Question: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''users' (username, password, first_name, last_name, email) VALUES ('ri' at line 1
INSERT INTO 'users' (`username`, `password`, `first_name`, `last_name`, `email`) VALUES ('rikars', '5aa9d6460f4ada3eb6611d6fda437317', 'Arsen', 'Babajanyan', 'firstname.lastname@example.com')

Comment: why downvote? it's a mistake in the code, like almost all the questions in SoF
Answer: Your table name cannot be in quotes. You can and should use ticks, however:
INSERT INTO `users`
            (`username`,
             `password`,
             `first_name`,
             `last_name`,
             `email`)
VALUES      ('rikars',
             '5aa9d6460f4ada3eb6611d6fda437317',
             'Arsen',
             'Babajanyan',
             'email@example.com')

Comment: Trying to make it a habit when I answer low quality questions

Error when inserting in to MySQL


Problema ao utilizar um container do Docker com "port exposure" no Windows

Question: Eu instalei o Docker no Windows esses dias mas estou tendo vários problemas ao rodar o meu container. Mesmo com ele em pé, não consigo acessar o projeto pelo navegador utilizando o IP da docker-machine, este é o comando que eu estou usando para rodar o container.
docker run -it -d -v /homer/user/html:/usr/share/nginx/html -p 80:80 myimage

Alguém tem alguma ideia do que possa ser? Ao acessar pelo navegador aparece a mensagem de "CONNECTION_REFUSED"
Comment: E suponho que no seu container esteja rodando algo na porta 80, certo? O que você está rodando nele?
Comment: Adicione o dockerfile na pergunta.
Answer: Já tentou colocar outra porta para ver se roda?
Exemplo:
docker run -it -d -v /homer/user/html:/usr/share/nginx/html -p 3000:80 myimage


Undefined reference to `main' when using makefile

Question: I have four files list.h list.c test_list.c Makefile
list.h
#ifndef List_H
#define List_H
#endif
/*nothing else*/

list.c
#include "list.h"
#include <stdio.h>
#include <stdlib.h>
/*nothing else*/

test_list.c
#include "list.h"
#include <stdio.h>
int main(){
    return 0;
}
/*nothing else*/

Makefile
CC=cc
CXX=CC
CCFLAGS= -g -std=c99 -Wall -Werror

all: list test_list

%.o : %.c
    $(CC) -c $(CCFLAGS) $<

test_list: list.o test_list.o
    $(CC) -o test_list list.o test_list.o

test: test_list
    ./test_list

clean:
    rm -f core *.o test_list

when I input make in shell, here comes the error:

/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_line): relocation 0 has invalid symbol index 2
      /usr/lib/gcc/i686-linux-gnu/4.8/../../../i386-linux-gnu/crt1.o: In function _start':(.text+0x18): undefined reference tomain'
      collect2: error: ld returned 1 exit status
      make: *** [list] Error 1

What is wrong here?
Comment: As an aside, your `"%.o` rule does the same as the implicit one. But you should probably make one for `list.o`, to add a dependency to `list.h`.
Answer: You have not specified a rule for building the target list, so make is inferring the following rule, which fails because you do not have a main function in your list.c.
cc     list.c   -o list

Since list should not be built as an executable anyways (no main), simply do not try to build list as a target in your Makefile, and then test_list will build correctly.
all:  test_list

Comment: @brickmanjim, Yes, It is conventional to use the target `all` with the actual binary targets as dependencies.
Comment: @brickmanjim, I have seen it both ways, but I have seen the `test` target independent of the `all` target more often. That is, the default build target does not also perform tests.
Comment: Thanks, this exactly solves my problem, my teacher likes to write `all:  test_list test`, is this more standard? I do not know whether the targets should all be the binary files after linking.
Comment: I mean the second target `test` in `all: test_list test`,  it is not a binary file but it is also in `all`
Answer: You defined a target list but did not define a rule for it. So make tried its implicit rule to generate this target rule by emitting the following command
cc     list.c   -o list

so that you got the linking errors since there is no a symbol named main in list.c
You can see how the implicit rules work just by running
make -r

Answer: You're already building your program as test_list, so no need for a list target.
Change:
all: list test_list

To:
all: test_list


Examples for $ \bar{A}\cap \bar{B}\neq\emptyset $, but $ \bar{A}\cap B=A\cap\bar{B}=\emptyset $.

Question:
Are there examples for sets $ A, B\subset X $, where $ X $ is a topological spacce and $ A, B $ are its nonempty subsets, satisfying $ \bar{A}\cap \bar{B}\neq\emptyset $, but $ \bar{A}\cap B=A\cap\bar{B}=\emptyset $.

I came up with this question when I was reading Basic Topology(M.A.Armstrong). I am trying to gain more intuitions about the difference between conditions for connectedness and separated from one another in $ X $.

Note that a space $ X $ is connected if whenever it is decomposed as the union $ A\cup B $ of two nonempty subsests then $ \bar{A}\cap B\neq\emptyset $ or $ A\cap \bar{B}\neq\emptyset $.
And if $ A $ and $ B $ are subsets of a space $ X $, and if $ \bar{A}\cap\bar{B} $ is empty, we say that $ A $ and $ B $ are separated from one another in $ X $.
Answer: In the ordinary real line, let $A=(0,1)$ and $B=(1,2)$, so that $1 \in \overline{A} \cap \overline{B}$.
Comment: but $\overline{A}\bigcap B \not= \emptyset$
Comment: @JoelPereira how so?  $\overline{A}=[0,1]$.  What belongs to this as well as $(1,2)$, which consists of things **strictly bigger** than $1$?
Comment: oh i read it as "A complement" as opposed to cl(A). my fault.


Combination Problem on white table

Question: Question : How many ways are there to choose 3 cells from a 4x4 table such that any two chosen cells do not belong to the same row nor the same column?
What have i done so far :
choosing $1$ from $16$ cells, each giving remaining $9$ cells option, so my equation would be $$(16)(9)(4)=576$$
which my answer was obviously false since $16C3=560$
Please explain where did I go wrong?
What shall be the correct approach to this answer?
Comment: Hint: How many ways are there to choose a given set of three cells that satisfy the constraint?
Comment: Also, 16C3 is irrelevant here, since it does not take the constraint of no common rows or columns into consideration, and hence overcounts.
Answer: I think there are some double countings in your method.
In the same shape, the method includes $3!$ counts, so my opinion is to divide it into $3!$.

Combination Problem on white table


What statistical tools would you use for identifiying important factors/variables in an experiment?

Question: I conducted a experiment where I measured bacteria on a 1000 peoples' hands after performing a repeatable task.

This scatter graph shows 2 experiments where the humidity of the hands is changed.
 I then repeated the experiment under 4 different conditions. What would you use to work out whether a variable was statistically important in alterring the results?
EDIT:
The experiment is actually numerical in nature:
The black points are produced by a function:
$$Y=f(A,V,\lambda)=\sum_{i=1}^nA_iV_i\lambda_i$$
Where $A$ $V$ and $\lambda$ are drawn from empirical distributions
the red points conform to:
$$Y=g(A,V,\lambda,\beta)=\sum_{j=0}^i \left(\prod_{k=j+1}^i \beta_k\sigma_j\right)$$
where $\sigma=A\lambda V$ and $\beta$ is an empirical distribution
Answer: I'd first be looking at fitting a generalized linear model accounting for the various independent variables in the model; the test would correspond to testing whether one (or perhaps several) coefficients in a model were significantly different from zero.
Comment: It depends on what your criterion for importance is as to whether it's directly available or you need to do further calculation. Knowing there's a nonlinear effect would impact how you model it. In the case of GLMs that might either cause you to consider a different link function, or to look at how to model the curve (which might depend on what you know or expect about it) - GAMs might be used if you don't know its form.
Comment: "*What I'm looking for is a way to distinguish whether one parameter affects the results more than another and to quantify this*". More details would help, but there would usually be several ways to do something like that... but without details it's a little hard to be precise. What 'one factor' and 'other factor'? And do you mean under the red or the black situation?
Comment: And would this tell me to what extent one variable was more important than another? Ie I was thinking about PCA. Also as it happens I know the red dots behave non-linearly whereas the black ones behave linearly. Does knowing this information change anything? Regards,
Comment: Ah interesting. The reason we know the red points are non-linear in nature is because this experiment is actually a simulation and I know the function which generated both red and black. What I'm looking for is a way to distinguish whether one parameter affects the results more than another and to quantify this. Is it possible?
Comment: Added equations to questions


Why Vuforia AR not working in my device?

Question: I am new to Unity AR.I have completed an IOS app which is working with Vuforia plane detection and tested using ipad.Now I took the project and switched to android platform.When I installed and checked it is not detecting any plane.So I tried a sample program[Link].Still it is not working.I checked the devices supported for Vuforia my device was there in the list Samsung Galaxy S7(SM-G930P).
I am using Unity 2017.3.0f3 and Vuforia Version 7.0.36.How to solve this issue?
Answer: I updated my Unity to 2018.1.0f2 and Vuforia Version 7.1.34. Now it's working.


Clone a Red Hat RAID as part of a disaster recovery plan

Question: I am looking for recommendations to clone a Red Hat mirrored raid to a single hard drive located in the same machine. The idea is if the servers hardware ever has an issue we have a similar hardware machine ready to go. All we would have to do is pop in the cloned drive. If the servers RAID ever failed we could just switch to the single drive to maintain uptime and restore the original configuration on the spare server with a backup.
This is a restaurant and they are open 7 days a week. We do have time from 12:am to 9:00am to perform the necessary steps for a clone and we talking about under 10 Gigs of information.
There is a database on the server.
I have looked into Rsync and Clonezilla. But I am just not confident either is capable of completing the task I want. Looking for some suggestions and possibly a step by step if you could be so kind.
Answer: I'm not sure if that is quite a disaster recovery plan; your database and drive are still fried if there's a major upset event (flood, fire, theft...)
I'd personally look at how to recover quickly from an event. You didn't say what the database was, but you can do a dump of it then copy that directory using a standard backup program like Amanda. Or rsync selected directories to another remote server or backup storage location that is offsite.
Take stock of what it would take to get that server running again. Maybe you can build another server with a similar configuration; if the only thing on that system is the database, build a "cloned" system, then do your nightly database dump, transfer it over, then have the new system restore the database as a hot spare system.
Without snapshot support taking a clone of a running system can yield inconsistencies. Especially with the database and in-flight data in memory.
Another thing to consider, if the database is the primarily important function on this, is to cluster your database server. Multiple servers being available will provide failover support. However, this depends on a few factors; what the database is, how big the restaurant (budget) is, how much administration work you want to invest...
Bottom line...personally, I'd look at doing a regular dump and transfer of the database to minimize the work involved in restoring the system to another server if need be (or a virtualized system if you can get a VM server), and use something designed to do system backups like Amanda.
Comment: I agree completely. There are already backups being performed and taken offsite. This would be to give as instantaneous of a recovery as possible the idea is to have a bit for bit copy in the same server for a manual fail over that would be as quick as one of us going down to the restaurant. The head admin is very adamant about having this sort of recovery. I already suggested the same method as you but the admin was less than receptive.
Comment: I'm not a RH expert, but if it's at all modern bits of it are dynamically created at boot time so they can't be just copied bit-for-bit, and with a database server, you can't get the database state without risking corruption. Really having a hot-standby is creating a second server, configured similarly for your additional services, and have it act as a node in a clustered database, depending on DB in use.
Comment: Otherwise get a maintenance contract on the server, and use proper RAID. Chances are with a good backup strategy and decent RAID (RAID 10? 1?) your failure point will be hard disks, not the controller.
Comment: I guess it is convincing time. I am in complete agreement on all your points. I am trying to make something work for someone who has a vision.
Comment: Just had a thought. This line "if the only thing on that system is the database, build a "cloned" system,cr then do your nightly database dump, transfer it over, then have the new system restore the database as a hot spare system." This is probably the best method to satisfy him. I would create a replica of the system and keep it in the same server. Every night we would do a dump of the mysql DB and then in the event of an emergency on the main drives we could boot off the spare and just restore the most recently copied DB dump. Do I have this idea right?
Comment: I was referring to having a second physical server running where you basically restored nightly database dumps (the spare would be "off" by a day if you do daily dumps and something happened). It would run replicated services (copy your files to it daily to sync file shares, etc.) and restore the database files from the primary server using whatever your database's import procedure would entail.
Comment: You'd basically be duplicating power use and disk storage and space in the server room, but you'd have a standby system with redundant parts if the server "died." But if you have an idea that works for your situation then by all means use it. We seem to be agreeing on what we think would be a better alternative.
Comment: Yes in full agreement. Thanks was just looking for clarification.
Answer: I'm sure others are gong to give you a hard time about why your request isn't really the best idea in implement, but that is you decision.
Simply, to answer you question, you are likely going to have difficulties accessing open file to copy them across at night. My suggestion would be to use LVM across your virtual FS on the RAID 1 and the extra drive in side the case.


Multi project template for dotnet new

Question: I am creating a multi-project template, that has a few optional projects and solution folders. I have been through quite a few different documentations and code in github to achieve this, but with very little success. I really appreciate if someone could give me some clarity on some of these questions?

Is VSTemplate xml file still relevant?
This blog suggests making changes in the template.json file, however when I check for examples in github, people use VSTemplate to make to create the project, and also SideWaffle plugin still creates the VSTemplate file. If its still relevant, Would like to know how does it differ from the json file?
Using the above VSTemplate I attempted to create a multi project template,using the ProjectCollection tage, when I run the dotnet run command, the template gets executed but the project does not get created.
<ProjectTemplateLink ProjectName="$safeprojectname$.Forms.Plugin.Abstractions">
  Forms.Plugin.Abstractions\Forms.Plugin.Abstractions.vstemplate
</ProjectTemplateLink>
<ProjectTemplateLink ProjectName="$safeprojectname$.Forms.Plugin.iOS">
  Forms.Plugin.iOS\Forms.Plugin.iOS.vstemplate
</ProjectTemplateLink>
<ProjectTemplateLink ProjectName="$safeprojectname$.Forms.Plugin.iOSUnified">
  Forms.Plugin.iOSUnified\Forms.Plugin.iOSUnified.vstemplate
</ProjectTemplateLink>
<ProjectTemplateLink ProjectName="$safeprojectname$.Forms.Plugin.Android">
  Forms.Plugin.Android\Forms.Plugin.Android.vstemplate
</ProjectTemplateLink>
<ProjectTemplateLink ProjectName="$safeprojectname$.Forms.Plugin.WindowsPhone">
  Forms.Plugin.WindowsPhone\Forms.Plugin.WindowsPhone.vstemplate
</ProjectTemplateLink>
</ProjectCollection>```

Can we create a multi-project template using template.json file?
Would appreciate if anyone can help me get started.
Answer: I have managed to get the multi-project template working by making the changes in the template.json file
this is the final template.json file looks like
This is my updated template.json file

    {
    "author": "Libin Joseph",
    "classifications": ["Xamarin", "Sample"],
    "name": "Sample Enterprise Template",
    "tags": {
        "language": "C#"
    },
    "identity": "libin.sampletemplate",
    "shortName": "sampletemplate",
    "sourceName": "SampleTemplate",
    "guids": [
        "{41F47D3C-C9E4-45D1-A289-3BDC31E44C19}",
        "{980FBE34-066B-4E87-AFC9-C3205844D980}",
        "{FD448FB5-B24B-4CD2-8E3C-2500CF0E4601}",
        "{D8FC665A-7739-4ADE-85E9-C69AA107EEE6}",
        "{92D25D7D-F637-4634-B939-BB38DE53B606}",
        "{5D52EDF7-47B8-48D2-83B6-104B18568CE4}",
        "{12E171B1-0F36-401A-A171-614F1A1C83E9}",
        "{7A4597AE-2C39-4197-94C9-F5B6B45B2106}"

    ],
    "primaryOutputs": [{
            "path": "SampleTemplate\\SampleTemplate.Android\\SampleTemplate.Android.csproj"
        },
        {
            "path": "SampleTemplate\\SampleTemplate.iOS\\SampleTemplate.iOS.csproj"
        },
        {
            "path": "SampleTemplate\\SampleTemplate\\SampleTemplate.csproj"
        },
        {
            "path": "SampleTemplate.UnitTest\\SampleTemplate.UnitTest.csproj"
        },
        {
            "path": "SampleTemplate.UITest\\SampleTemplate.UITest.csproj"
        },
        {
            "path": "SampleTemplate.Core\\SampleTemplate.Core.csproj"
        }
    ],
    "exclude": ["**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.lock.json"]
    }

Comment: Thanks for your sharing ! One question i have, what are the Guids in the "guids" property about ? Is it ProjectType guid, or just random guid for each project, or anything else ? EDIT: Nevermind, find the answer here: https://github.com/dotnet/templating/wiki/Reference-for-template.json . Thanks !

Multi project template for dotnet new


Quantifying the effects of partition mis-alignment

Question: I'm experiencing some significant performance issues on an NFS server.  I've been reading up a bit on partition alignment, and I think I have my partitions mis-aligned.  I can't find anything that tells me how to actually quantify the effects of mis-aligned partitions.  Some of the general information I found suggests the performance penalty can be quite high (upwards of 60%) and others say it's negligible.  What I want to do is determine if partition alignment is a factor in this server's performance problems or not; and if so, to what degree?
So I'll put my info out here, and hopefully the community can confirm if my partitions are indeed mis-aligned, and if so, help me put a number to what the performance cost is.
Server is a Dell R510 with dual E5620 CPUs and 8 GB RAM.  There are eight 15k 2.5" 600 GB drives (Seagate ST3600057SS) configured in hardware RAID-6 with a single hot spare.  RAID controller is a Dell PERC H700 w/512MB cache (Linux sees this as a LSI MegaSAS 9260).  OS is CentOS 5.6, home directory partition is ext3, with options "rw,data=journal,usrquota".
I have the HW RAID configured to present two virtual disks to the OS: /dev/sda for the OS (boot, root and swap partitions), and /dev/sdb for a big NFS share:
[root@lnxutil1 ~]# parted -s /dev/sda unit s print

Model: DELL PERC H700 (scsi)
Disk /dev/sda: 134217599s
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number  Start    End         Size        Type     File system  Flags
 1      63s      465884s     465822s     primary  ext2         boot
 2      465885s  134207009s  133741125s  primary               lvm

[root@lnxutil1 ~]# parted -s /dev/sdb unit s print

Model: DELL PERC H700 (scsi)
Disk /dev/sdb: 5720768639s
Sector size (logical/physical): 512B/512B
Partition Table: gpt

Number  Start  End          Size         File system  Name  Flags
 1      34s    5720768606s  5720768573s                     lvm

Edit 1
Using the cfq IO scheduler (default for CentOS 5.6):
# cat /sys/block/sd{a,b}/queue/scheduler
noop anticipatory deadline [cfq]
noop anticipatory deadline [cfq]

Chunk size is the same as strip size, right?  If so, then 64kB:
# /opt/MegaCli -LDInfo -Lall -aALL -NoLog
Adapter #0

Number of Virtual Disks: 2
Virtual Disk: 0 (target id: 0)
Name:os
RAID Level: Primary-6, Secondary-0, RAID Level Qualifier-3
Size:65535MB
State: Optimal
Stripe Size: 64kB
Number Of Drives:7
Span Depth:1
Default Cache Policy: WriteBack, ReadAdaptive, Direct, No Write Cache if Bad BBU
Current Cache Policy: WriteThrough, ReadAdaptive, Direct, No Write Cache if Bad BBU
Access Policy: Read/Write
Disk Cache Policy: Disk's Default
Number of Spans: 1
Span: 0 - Number of PDs: 7

... physical disk info removed for brevity ...

Virtual Disk: 1 (target id: 1)
Name:share
RAID Level: Primary-6, Secondary-0, RAID Level Qualifier-3
Size:2793344MB
State: Optimal
Stripe Size: 64kB
Number Of Drives:7
Span Depth:1
Default Cache Policy: WriteBack, ReadAdaptive, Direct, No Write Cache if Bad BBU
Current Cache Policy: WriteThrough, ReadAdaptive, Direct, No Write Cache if Bad BBU
Access Policy: Read/Write
Disk Cache Policy: Disk's Default
Number of Spans: 1
Span: 0 - Number of PDs: 7

If it's not obvious, virtual disk 0 corresponds to /dev/sda, for the OS; virtual disk 1 is /dev/sdb (the exported home directory tree).
Comment: First, run `cat /sys/block/sdb/queue/scheduler` and report the result. Second, please describe "performance issues".
Comment: The `ST3600057SS` drive is not a 4k drive, the block size is 512 bytes for that drive.  The bigger question is question is what have you set as the chunk size of your RAID6, and are you properly aligned to that.  I would guess not given the starting sectors you listed in your partition table.
Comment: The performance problems I don't think are relevant to this question.  My question is **not** "please help me solve my performance problems", but rather, "please help me better understand the effects of partition mis-alignment so I can decide for myself if it's related to my issues."
Comment: Consider using the `deadline` I/O scheduler. `CFQ` is the pits in EL5.
Comment: @matt As for the performance issues, alignment isn't at the core of it. You're abstracted through the RAID controller; writes should be cached via the battery-backed cache unit, reads are going to be what they are.
Comment: @ewwhite Do you happen to have a link that talks about why the deadline IO scheduler is better than CFQ on EL5?  Not doubting you, just want to better understand how it might help.  I'll start another question dealing with my performance issue specifics.
Comment: See: http://serverfault.com/questions/373563/linux-real-world-hardware-raid-controller-tuning-scsi-and-cciss
Comment: See this article.  http://technet.microsoft.com/en-us/library/dd758814(SQL.100).aspx for some details about the impact of miss-alignment.  It is written from a Windows perspective, but the OS really shouldn't matter.
Answer: Your partitions are misaligned and it might be difficult to asses how much you're actually losing in performance because that would depend on the type of I/O workload. It might be negligible if your I/O workload is light, compared to the performance of your disks. However, since this is a NFS server, I'm assuming it's not negligible and should be addressed. Some estimates put the performance penalty at 20-30%.
Partition misalignment basically means you might need two I/O operations at hardware level to satisfy one I/O operation at software level. If your software blocks are not ending at the same hardware boundary, that will happen. From what you've written, you already researched and understand this.

Disk = 512-byte sectors
RAID = 65536-byte stripes (OK)
Partition 0 = starting at sector 63 (32256-byte offset)
Partition 1 = starting at sector 465885 (238533120-byte offset)
EXT2/3/4 block size = ?
EXT2/3/4 stride size = ? (calculator)

Keep in mind that partition misalignment is different from having your storage subsystem using block sizes that are different from what you software is using. This could also put more stress on your disks but is not really related to alignment issues.
Use tunefs -l /dev/sdaX | grep size to check the block size on your filesystem.
According to Red Hat Enterprise Linux's recommendations:

Generally, it is a good idea to align the partitions to a multiple of one MB (1024x1024 bytes). To achieve alignment, start sectors of partitions should always be a multiple of 2048, and end sectors should always be a multiple of 2048, minus 1. Note that the first partition can not start at sector 0, use sector 2048 instead.

It looks like you might be looking at having to move the data and recreate your partitions, if that is indeed the root cause of your NFS performance issue. However, the whole thing is usually more complex and I'd try to find evidence that other things are OK before considering a costly reinstall.
Comment: Wow, thank you for the detailed response.  Ultimately, I did a full re-install, also upgrading to CentOS 6.x.  There may be more details, but, given this all happened two years ago, I can't remember them.  :)  But, since the OS upgrade, things have been acceptable.  Thanks again!
Comment: Glad everything is alright. Geez, only now I saw the question's date. LOL.


É correto chave estrangeira com campo nulo? PostgreSQL

Question: Estava construindo um modelo entidade relacionamento (MER) de um banco de dados para uma associação rual, é um trabalho para materia de TABD. Porém me deparei com uma situação atípica para mim, um relacionamento 0,n para 0,1. Como podem ver na figura.
Acontece que nesse banco de dados nem sempre uma transação irá ter uma pessoa relacionada (a transação pode ser a saida de dinheiro com pagamento de contas por exemplo) e como a chave estrageira está na tabela transação isso implicaria em chaves estrangeiras nulas. A minha dúvida é se isso está correto? Chaves estrangeiras podem ser nulas? Caso não, porque?
Pesquisei em alguns lugares antes de perguntar aqui mas não havia concordância nas respostas.
Comment: Não sou especialista, vou deixar para alguém da área responder. Mas como desenvolvedor, não há problemas em deixar a chave estrangeira nula.
Provavelmente você poderá usar o campo `tipo` para diferenciar na hora de realizar as *queries* via aplicação. Caso o tipo seja *comum* (por exemplo, para mostrar que foi uma transação realizada por uma pessoa), então você saberá que há sempre um id_pessoa válido, não nulo. Caso o tipo não seja *comum* (por exemplo, realizada pelo próprio sistema), então você sabe que não há um id_pessoa válido.

Apenas uma visão de developer. Acompanharei a resposta.
Comment: Não tem lógica uma chave estrangeira ter valor nulo. Para além das chaves se poderem repetir, a foreign key se estiver ligada a uma tabela, não tem utilidade como ID.
Comment: Esse é o problema em minhas pesquisas para resolver essa questão. Sempre tem pessoas que dizem que não há problemas (essas dão respostas mais claras e coerentes) e pessoas que dizem que não tem lógica (porém, geralmente não há uma explicação para essa respostas). A pergunta para a segunda resposta é. Se não tem lógica, qual a maneira lógica de ligar duas tabelas nas quais as ligações não são obrigatórias em nenhum dos lados?
Comment: Não existe problema. Isto indica que o relacionamento é opcional. Caso fosse obrigatório você especificaria NOT NULL na chave estrangeira. O que você tem que verificar é se tal situação faz sentido em seu modelo dedados e, parece, você já fez tal verificação. Note que o que não faz sentido é você ter uma chave primária podendo conter NULL e, neste caso, os próprios SGBD não permitem tal construção.
Comment: Exemplo simples , o ENDEREÇO é opcional, mas se informado as FKs das tabelas UF, ESTADO,BAIRRO  tem de existir nss respectivas tabelas.
Answer: Com bases nos comentários dos autores

Andrew Ribeiro & White

cheguei a seguinte conclusão:
Não faz sentido mesmo ter uma chave estrangeira nula, ao mesmo tempo que sim pode existir uma chave estrangeira nula porém ela se torna inútil pois o acesso a tuplas com chaves estrangeiras se faz justamento pelo valor dessa, se a mesma é nula não há como acessa-lá.
O erro no relacionamento que enviei é que não faz sentido existir uma transação sem que ela seja feita por uma pessoa, então o relacionamento deveria ser (1,1) para (0,n).
Answer: Faz sentido dependendo da aplicação do projeto, por exemplo um cliente compra numa loja e ele não quer fazer o cadastro dele na base de dados, ao efetuar a venda o valor da chave estrangeira para este cliente será nulo
Outro cliente com cadastro pode ir e colocar, a chave estrangeira para este cliente será um valor referente a este cliente na base de dados.
O que vai dar erro é referenciar um valor não existente na base de dados cliente, mas valor nulo não tem problema algum fiz este teste e deu certo
<code>CREATE TABLE Cliente (
  id INT PRIMARY KEY IDENTITY(1,1),
  nome VARCHAR(50)
);

CREATE TABLE Pedido (
  id INT PRIMARY KEY IDENTITY(1,1),
  cliente_id INT DEFAULT NULL,
  descricao VARCHAR(100),
  FOREIGN KEY (cliente_id) REFERENCES Cliente(id)
);

INSERT INTO Pedido(descricao)
VALUES('Pedido para cliente anônimo')

INSERT INTO Pedido(descricao, cliente_id)
VALUES('Cliente não existente', 2)

SELECT * FROM Pedido
</code>
O primeiro caso registrou sem problemas o segundo gerou erro :)
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Applying a tansig or tanh function on embedded.fi files

Question: I was trying to apply a tansig or tanh function on my fixpointed data which I am using for my neural nework in MatLab, but when I use these functions on embedded.fi files, MatLab says that tanh or tansig function will not work on embedded.fi.
I am trying to set my neural network using fixpointed weights. I will really appreciate it if anyone has solution for that
Answer: As the error message states, there is no fixed-point version of tanh and tansig functions in Matlab. The complete list of functions that have fixed-point versions and are supported can be found here:
http://www.mathworks.com/help/hdlcoder/ug/fixed-point-run-time-library-support.html
Comment: Really appreciate it, but how can i use tansig on fixpoint values? I have to design my circuit with fixpoint values and tansig function.do i have to stimate tansig using mathematical equations?how?
Comment: I think that this link https://mathworks.com/help/fixedpoint/examples/calculate-fixed-point-sine-and-cosine.html could be helpful for you.


how to convert Taxonomy terms to nodes

Question: Short Question :

is there a way convert all of one vocabulary taxonomy terms to one
content type nodes ? And switch all term refrences in the database to
entity references to the converted term/nodes?

Details :

A long time ago, I have made a website for music and i used the core
terms for local singers and performers now i want to use entity
reference for a better content control user interface.
the website has one content type "Audio File" The content type
fields are :

Audio file : file upload
Performer : term reference of vocab "Performers"

The taxonomy term fields are -Vocab : "Performers:

Performer Name : title field.
Performer Portrait : Image upload field

the site is running and there is already more than 150 singers and over 1000 audio files. So doing this manually is almost impossible.
I think i should use migrate module but i don't know how to use it and it seems very complicated !
Thanks :)
Comment: Your use case is uncommon, you will need to code it yourself I'm afraid.
Answer: Export taxonomy using https://drupal.org/project/taxonomy_csv
Then use excelent https://drupal.org/project/feeds module and create node importer and map fields accoridingly.
Answer: I think there is not a "ready-to-use" waay to do this.
You could create a custom module. Supposing that you have already created and configured:

the new content type "performers" with all fields (with a field called "old id" there will have the "old" tid from the term
the "audio" content type with entity  reference to Performers

you could create a module that:

get all terms from the vocabulary
for every term you create a node "performer", with values from terms and using the tid for the field "old id"

After this you could:

get all nodes of type "audio"
for every node you get the "tid" value of the performer and with views or entity_query_field search for the "performer" node that has "old id" = "tid"
assign the nid of the performer to the entity reference in "audio"
save the "audio" node

These could be the "logical" process of the module.

how to convert Taxonomy terms to nodes


Textbook probability question - is this unrelated data to throw you off?

Question: 4.24 from Newbold 8th Edition:

The probability of a team winning a game is 0.45. What is the probability that the team will:
  a) win 2 games out of 5;
  b) win 10 games out of 25?

If the probability of winning a game, any game, at any time, is 0.45, and if we consider games independent events, then winning 2 games is 0.45*0.45 out of however many; and winning 10 games is 0.45^10.
Or is the idea that for 2 out of 5 games it's 1/5*1/4 and for 10 out of 25 games it's 1/25*1/24... etc? In which case what is the 0.45 doing in all this?
Comment: This sounds like it is a self-study question. Please look at [this information about self-study questions](https://stats.stackexchange.com/tags/self-study/info), add the `self-study` tag to the question, and say a bit more if possible about where you are stuck. Note, for example, that in your first suggested answer what you are looking at is winning N games _without losing one_. Think instead about how many ways you might be able to have five games total and win exactly two out of five.
Comment: @EdM, thanks for the comment, I didn't know about the self-study tag. Also thanks for the comment about 'N games without losing', I hadn't realised that!
Answer: No, as the number of games increases, the number of games that you win is expected to increase as well because you get more chances.
For example, let's say we want to find the probability of winning $2$ games out of $3$ games. The possible situations are $WWL,WLW,LWW$, where $L$ denotes losing and $W$ denotes winning.
The probability of the first situation is $$P(WWL)=P(W)P(W)P(L)=0.45\times0.45\times0.55$$
Similarly, you can find $P(WLW),P(LWW)$, and sum them to get the final answer. And, you can then generalise this idea to answer your questions.
Note also that these can be answered using Binomial Distribution as well.
Comment: It never hurts to spend time thinking. :D Thank you for always helping me here. :)
Comment: "So, the probability of winning 2 games out of 5 is more than winning 2 games out of 10." is only true for some values of the win probability: if the chance of winning is low (specifically, less than $1 - (10/45)^{1/5} \approx 0.26$), you are more likely to win 2/10 than 2/5.
Comment: Thanks, @gunes, I understand it now, I'll "play it out". (And yes, the exercise is in a chapter titled 'Discrete Probability Distributions' - but before the section called 'Binomial Distributions' ...).
Comment: can I get back to "the probability of winning 2 games out of 5 is less than winning 2 games out of 10." , please? At 0.45 probability of winning 2 out of 5 is .337 while 2 out of 10 is only .076 ... what am I doing wrong?
Comment: good catch, it's *more* than.
Comment: Oh! :-D I spent about an hour this afternoon with a TI-83+ and books to try to figure it out! :)))))
Comment: @Mark Right, it wasn't a rigorous statement anyway. Removed it.


Managing libraries in Xcode 4

Question: I'm currently trying to import the facebook-ios-sdk into one of my projects.
My approach is to import my project and the project of the facebook-ios-sdk into one workspace, but my project can't find the header files of the facebook sdk. I thought that the files in one workspace will be shared isn't it? How can I import the facebook-ios-sdk to my project without copying the files directly into my project?
thanks
Answer: I hope to understand what you want. I'm using facebook-ios-sdk, and I added all files in directoctory src (.m and .h) in my project with right click, "add files to…"
Comment: this is the way according to the readme on github, but I manage the facebook sdk as a submodule in GIT and if new files will be added, Xcode cant recognize that, isn't it?
Comment: White font on a black background. You must be missing the VT220 and 3270 terminals badly...
Comment: @Codo White font on a black background is so soothing no ?…
Answer: Try step 3 of this answer: "lexical or preprocessor issue file not found " in Xcode 4

3 - Create a group call "Indexing headers" in your project and drag the
  headers to this group, DO NOT add to
  any targets when prompted.
Comment: I want to be independent from the imported framework. So I think just adding the headers would not be the best way

Managing libraries in Xcode 4


How to perform CCA with block design in R

Question: Following example and data are completely fabricated:
Suppose I am studying grooming behaviour in apes. I have four cages, 8 apes in each (4 females +  males). For 24 hours I did an observations with aim to record the number of events when females were grooming males.

I would like to know, whether I can explain the variability of grooming events [grooming]  with these 5 characteristics of males [m_char] (x1, x2,...x5).

My approach was to perform CCA (a.k.a. canonical correspondence analysis) as following:
library(vegan)
my.cca <- cca(grooming ~ x1 + x2 + x3 + x4 + x5,
              data = m_char,
              scale = TRUE)

and test this model by anova to obtain p-values for factors
anova(my.cca, by="terms", permutations=1000)

# Permutation test for cca under reduced model
# Terms added sequentially (first to last)
# Permutation: free
# Number of permutations: 1000
#
# Model: cca(formula = grooming ~ x1 + x2 + x3 + x4 + x5,
#            data = m_char, scale = TRUE)
#          Df ChiSquare      F   Pr(>F)
# x1        1    0.5327 1.1054 0.718282
# x2        1    0.6216 1.2899 0.359640
# x3        1    0.6341 1.3159 0.314685
# x4        1    0.6739 1.3984 0.191808
# x5        1    0.8782 1.8225 0.008991 **
# Residual 10    4.8188
# ---
# Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Although, x5 seems to have significant effect on grooming, when I look on plot...
plot(my.cca)

...apes from one cage seems to strongly group together.
I think that the structure of my data causes a problem to cca analysis, because, when you look on table with numbers of interactions...

...only zeros in yellow squares are "true" zeros (i.e. there is no interactions between apes), the rest of zeros outside yellow squares are just a consequence of being in different cage.

Is it possible to somehow tell the CCA to ignore "false zeros"? How to
  incorporate such data structure appropriately? My main aim is to find
  whether one or multiple characteristics of males can be used to
  explain the grooming rates.

Thank you very much for any suggestion!

"grooming" example data:
AF1 <- c(3,7,2,0,rep(0, times = 12))
AF2 <- c(8,0,0,3,rep(0, times = 12))
AF3 <- c(0,2,0,0,rep(0, times = 12))
AF4 <- c(4,0,1,0,rep(0, times = 12))
AF4 <- c(4,0,1,0,rep(0, times = 12))
BF1 <- c(rep(0, times = 4),4,1,5,0,rep(0, times = 8))
BF2 <- c(rep(0, times = 4),3,0,0,1,rep(0, times = 8))
BF3 <- c(rep(0, times = 4),0,2,0,0,rep(0, times = 8))
BF4 <- c(rep(0, times = 4),0,0,7,0,rep(0, times = 8))
CF1 <- c(rep(0, times = 8),4,0,4,0,rep(0, times = 4))
CF2 <- c(rep(0, times = 8),2,0,0,0,rep(0, times = 4))
CF3 <- c(rep(0, times = 8),0,3,0,4,rep(0, times = 4))
CF4 <- c(rep(0, times = 8),0,0,9,0,rep(0, times = 4))
DF1 <- c(rep(0, times = 12),0,2,0,0)
DF2 <- c(rep(0, times = 12),6,0,0,1)
DF3 <- c(rep(0, times = 12),0,0,1,0)
DF4 <- c(rep(0, times = 12),4,0,1,0)

male_id <- c("AM1", "AM2", "AM3", "AM4",
             "BM1", "BM2", "BM3", "BM4",
             "CM1", "CM2", "CM3", "CM4",
             "DM1", "DM2", "DM3", "DM4")

grooming <- data.frame(AF1,AF2,AF3,AF4,
                       BF1,BF2,BF3,BF4,
                       CF1,CF2,CF3,CF4,
                       DF1,DF2,DF3,DF4)
rownames(grooming) <- male_id

"m_char" example data:
x1 <- c(2,5,3,1,8,1,1,6,2,3,5,1,1,6,6,7)
x2 <- c(4,9,1,3,2,1,9,4,3,1,9,2,9,1,4,3)
x3 <- c(1,2,5,4,4,4,5,2,2,1,1,1,2,5,5,9)
x4 <- c(4,1,1,8,8,6,6,6,6,8,1,6,2,2,1,1)
x5 <- c(1,7,3,3,4,1,5,1,3,8,4,8,8,5,9,9)

m_char <- data.frame(x1, x2, x3, x4, x5)
rownames(m_char) <- male_id

Answer: I believe the issue is that the permutation test you are using is too liberal; it assumes a Null hypothesis in which all observations are exchangeable. From what you say, observations within a cage are exchangeable, but are not exchangeable between cages.
To use the more restrictive null in the permutation test we can use a restricted permutation design, in which we ask vegan to only permute observations within cages and never between cages. This is most easily done using a blocking factor.
Create the blocking factor:
m_char <- transform(m_char,
                    cage = factor(substring(rownames(m_char), 1, 1)))

Next, define the restricted permutation design (the defaults for how() mean we get randomisation within the levels of the factor passed to blocks)
ctrl <- how(nperm = 1000, blocks = m_char$cage)

Now fit the model and remove the between-cage variation, which is also required for these analyses with blocks
my.cca <- cca(grooming ~ x1 + x2 + x3 + x4 + x5 + Condition(cage),
              data = m_char)

Now do the restricted permutation test
set.seed(10)
anova(my.cca, by = "terms", permutations = ctrl)

This produces:
> anova(my.cca, by = "terms", permutations = ctrl)
Permutation test for cca under reduced model
Terms added sequentially (first to last)
Blocks:  m_char$cage
Permutation: free
Number of permutations: 1000

Model: cca(formula = grooming ~ x1 + x2 + x3 + x4 + x5 + Condition(cage), data = m_char)
         Df ChiSquare      F  Pr(>F)
x1        1   0.52470 1.4119 0.15185
x2        1   0.60901 1.6388 0.03397 *
x3        1   0.21703 0.5840 0.96503
x4        1   0.36739 0.9886 0.36563
x5        1   0.83984 2.2600 0.03497 *
Residual  7   2.60129
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

And the triplot shows different behaviour to that you obtained

Does this make sense now?


How can I manage Hyper-V Server 2012 R2 from Windows 7 with PowerShell

Question: I am tearing my hair out at the moment trying to do this. Just a couple of things to clear up:

I have Windows Hyper-V Server 2012 R2 freshly downloaded and Remote Administration enabled;
I have a Windows 7 Professional machine - up to date etc. etc.
I know you cannot manage Hyper-V 2012 R2 from Windows 7 using the GUI, that's why I want to use PowerShell;
I've been using PowerShell for a while but all this remote connection stuff is very new;

So with that out of the way, let's go.
I've used Connect-PSSession to connect to the PowerShell session on the Hyper-V server. No problem. Remote commands don't work (get-vm for example), I'm assuming because I don't have them installed locally. I tried to do import-pssession (which is what I use when I'm managing Office 365 with PS remotely) and that works but doesn't give me any hyper-v cmdlets to use. I have tried to import-module hyper-v and it doesn't exist.
So I'm stuck. I've been Googling for about 2 hours now with no luck. Plenty of very old articles about how to connect to Server 2008 ort 2012 from Windows 8 but nothing on how to connect to it from Windows 7.
Any help?
Comment: You need the module on your machine and imported otherwise no cmdlets you run will be found/execute. You can install the module, it's under Windows Features -> Hyper-V -> Hyper-V Module for Windows Powershell. Once you've installed it, run Get-Module -ListAvailable to confirm it's on your system, then import the module as normal. Once imported and connected to your Hyper-V host, you can use all the cmdlets in the module such as Get-VM.
Comment: Making no assumptions, I presume you've imported the Hyper-V module ?
Comment: Yeah, tried that. No valid module file found. (updated original question)
Comment: On which machine? Windows 7 doesn't have a Hyper-V option under features and the Hyper-V Server doesn't have a GUI.
Comment: You could try this library on Codeplex https://pshyperv.codeplex.com/, otherwise I don't know I'm afraid.
Comment: Cheers mate. That was last updated in 2011. Tried to install that earlier and it ended up with errors ('invalid root' being the latest)
Answer: Do this:

Create a new PSSession on your Hyper-V host

    $Session = New-PSSession -ComputerName [Hyper-V Host] -Credential (Get-Credential)

then enter it:

    Enter-PSSession $Session

Your PowerShell prompt will change to indicate you're connected to the remote machine.  Any powershell commands you run will be ran on the remote machine.
Try it, you'll find Get-Vm now works.


OpenVPN on a Netgear GS108 switch?

Question: I have a Netgear GS108 gigabit switch - can I flash OpenVPN on this?  My network is as follows
Internet <-> Motorola DSL Modem <-> NetgearGS108 <-> LAN
I'm guessing I can't since this is just a switch and there is no interface??  And I would need a router with an interface to be able to flash OpenVPN on it...
Answer: i very much doubt it. netgear GS108 seems to be cheap, unmanageable switch probably based on quite specialized realtek or broadcom switch-on-the-chip.
imho you are more likely to get openvpn running on your motorola dsl router/modem [ if you manage to find modified firmware for it ] than on your switch.
and obviously you can run openvpn on some box in your lan - on windows as well.. or on linux, and even as virtual machine.

OpenVPN on a Netgear GS108 switch?


Find latest version of file name from array using JavaScript

Question: I have string array, which contains filename with a combination of Year_Program_Version
Ex.
var fileNames = [
  "2021_Test_V1",
  "2021_Test_V2",
  "2021_Test_V4",
  "2021_Test_V3",
  "2020_Test_V11",
  "2020_Test_V10"
];

Looking for output array having: 2021_Test_V4, 2020_Test_V11
Comment: What have you tried? Is the version suffix **always** `_V`?
Comment: Yes, file name always ends with _V
Comment: My actual array might have more than 50000 records. So is it possible to reverse sort the array(using fileNames.sort().reverse()) and pick the top 1 record for a particular year_Program combination.

Ex. 2021_Test_V1
2021_Test_V2
2021_Test_V3
2020_Test_V11
2020_Test_V10

Output of fileNames.sort().reverse() will be:
2021_Test_V3
2021_Test_V2
2021_Test_V1
2020_Test_V11
2020_Test_V10

So, pick first record from the array and remove the other same year_program combination from main array (Using splice()) to reduce array length. Repeat above step for selecting second file name.
Answer: Build an object with all the year/programs as keys and their latest version as values, then map back to an array of file names:

const fileNames = [
  "2021_Test_V1",
  "2021_Test_V2",
  "2021_Test_V4",
  "2021_Test_V3",
  "2020_Test_V11",
  "2020_Test_V10"
];

const latestFileNames = Object.entries(fileNames.reduce((a, v) => {
  const [yp, version] = v.split(/_V(?=\d+$)/);
  a[yp] = a[yp] && +a[yp] >= +version ? a[yp] : version;

  return a;
}, {})).map(([yp, version]) => `${yp}_V${version}`);

console.log(latestFileNames)
Answer: A slightly different solution, working off the following assumptions.
Assumptions:

format is fixed and delimited by underscore (underscore isn't used in the year / program / version).
sorting by version ascending (OP wants the largest version).
version is numeric (excluding preceding "V" and has no leading zeros).
code does not rely on fileNames sorting.

Explanation:

parse the string to get year / program / version (numeric)
check if an existing value exists for "<year>_<program>"

if value doesn't exist, then this is the latest version.
if value does exist, check if this version is larger than the existing version.

code.js

var fileNames = [
  "2021_Test_V1",
  "2021_Test_V2",
  "2020_Test_V11",
  "2021_Test_V4",
  "2021_Test_V3",
  "2020_Test_V10"
]

/* get latest version (grouped) by year + program */
const latestVersion = fileNames.reduce((accu, curr) => {
  let [year, program, version] = curr.split('_')
  version = parseInt(version.substring(1))
  const key = `${year}_${program}`
  const prevVersion = accu[key]
  if (typeof prevVersion === 'undefined' || version > prevVersion) accu[key] = version
  return accu
}, {})

// convert back to array of filenames...
console.log(Object.keys(latestVersion).map(k => `${k}_V${latestVersion[k]}`))

Returns:
["2021_Test_V4", "2020_Test_V11"]
Answer: I'd start by creating a map holding the filename prefixes and the latest version (numerically).
You can then map those entries back into their complete filenames.
For example

const fileNames = [
  "2021_Test_V1",
  "2021_Test_V2",
  "2021_Test_V4",
  "2021_Test_V3",
  "2020_Test_V11",
  "2020_Test_V10"
]

const fnRegex = /(.+)_V(\d+)$/

const versionMap = fileNames.reduce((map, fn) => {
  let [_, prefix, version] = fn.match(fnRegex)
  let maxVersion = Math.max(version, map.get(prefix) || 0)
  return map.set(prefix, maxVersion)
}, new Map())

const latestVersions = Array.from(versionMap,
    ([prefix, version]) => `${prefix}_V${version}`)

console.info(latestVersions)
Answer: One possible solution (maybe not so good in performance) is to use Array.filter() with a nested Array.some() to keep only the elements meeting the expected condition. This also assumes that all years uses the four digit format.

var fileNames = [
  "2021_Test_V1",
  "2021_Test_V2",
  "2021_Test_V4",
  "2021_Test_V3",
  "2021_Test_V10",
  "2020_Test_V11",
  "2020_Test_V10",
  "2019_Test_V1"
];

let res = fileNames.filter((str, i, arr) =>
{
    let [year, app, version] = str.split("_");

    return !arr.some(s =>
    {
        let [y, a, v] = s.split("_");
        return y === year && +v.slice(1) > +version.slice(1);
    });
});

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Comment: The problem with lexicographic sorting is that "V2" would show as larger than "V10". Try adding `"2020_Test_V2"` to your data
Comment: @Phil Yea, is O(n^2). Just an alternative, I revised in relation to the first comment, missed that, sorry!
Answer: Based on Robby Cornelissen answer, but for ECMASCRIPT3, I known it's old, but it's, as far as I known, the only version that's Adobe Animate CC 2019 JS programming API understand :-(.
With the help of Closure:
java -jar closure-compiler\closure-compiler-v20200406.jar --language_in ECMASCRIPT_2015 --language_in ECMASCRIPT3 --js test.js --js_output_file test_es3.js --compilation_level BUNDLE

Result code:
var fileNames = [
  "2021_Test_V1",
  "2021_Test_V2",
  "2021_Test_V4",
  "2021_Test_V3",`enter code here`
  "2020_Test_V11",
  "2020_Test_V10"
];

function e(a) {
  var b = 0;
  return function() {
    return b < a.length ? {done:!1, value:a[b++]} : {done:!0};
  };
}

function f(a) {
  var b = "undefined" != typeof Symbol && Symbol.iterator && a[Symbol.iterator];
  return b ? b.call(a) : {next:e(a)};
}

// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
if (!Object.keys) {
  Object.keys = (function() {
    'use strict';
    var hasOwnProperty = Object.prototype.hasOwnProperty,
        hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
        dontEnums = [
          'toString',
          'toLocaleString',
          'valueOf',
          'hasOwnProperty',
          'isPrototypeOf',
          'propertyIsEnumerable',
          'constructor'
        ],
        dontEnumsLength = dontEnums.length;

    return function(obj) {
      if (typeof obj !== 'function' && (typeof obj !== 'object' || obj === null)) {
        throw new TypeError('Object.keys called on non-object');
      }

      var result = [], prop, i;

      for (prop in obj) {
        if (hasOwnProperty.call(obj, prop)) {
          result.push(prop);
        }
      }

      if (hasDontEnumBug) {
        for (i = 0; i < dontEnumsLength; i++) {
          if (hasOwnProperty.call(obj, dontEnums[i])) {
            result.push(dontEnums[i]);
          }
        }
      }
      return result;
    };
  }());
}

Array.prototype.getLastVersion = function(){
    var filenames = this.toString();
    var g = Object.entries(filenames.split(",").reduce(function(a, b) {
        var c = f(b.split(/_V(?=\d+$)/)), d = c.next().value;
        c = c.next().value;
        a[d] = a[d] && +a[d] >= +c ? a[d] : c;
        return a;
    }, {})).map(function(a) {
        var b = f(a);
        a = b.next().value;
        b = b.next().value;
        return a + "_V" + b;
    });
    return g;
}

console.log(fileNames.getLastVersion());


How to fill checkout form fields with values from a previous custom form?

Question: Basically I have a few landing pages with forms with fields that are a subset of the checkout page form fields. I'd like for the user to submit the form and be redirected to the checkout page with the form values already filled.
I'm using Übercart and I think it's this function here that controls it:
function uc_checkout_pane_delivery($op, &$arg1, $arg2) and the values of $arg1 needs the be set by the previous form. My question is how? What would be an appropriate method for populating the checkout form fields? Thanks.
Answer: I think you could get away with this by using hook_form_alter (checkout is still a form) and just setting #default_value on the required field. The previous form could save it in $_SESSION somewhere.
Comment: I just changed the form action to `shop/checkout` and used the $_POST values to insert the data in the checkout form. It works, but I'm not sure it's very safe/good coding.


Finding the best possible $\delta$ for a continuous function.

Question: I am trying to understand the following problem... I understand half of it, but I get confused with something. First of all, I was wondering if there is a relation between $\delta$ and $\epsilon$ other than the one stated in the question (I think it was $\delta < 1/\epsilon$ or something like that, but I can't find it in my notes). Thanks a lot in advance!
Question: Consider $f:\mathbb{R}\to\mathbb{R}$ given by $f(x)=x^2$. We know that it is continuous at $a$ for all $a\in\mathbb{R}$. So, for every $a$, for every $\epsilon>0$ there is a $\delta>0$ such that $|x-a|<\delta$ implies $|f(x)-f(a)|<\epsilon$. For $a>1$ and $\epsilon=1$ find the best possible $\delta$. Is this best possible $\delta$ independent of $a>1$.
Solution: Our $\delta$ will be the best one such that $x\in(a-\delta,a+\delta)$ implies that $x^2\in(a^2-1,a^2+1)$, that is, $x\in((a^2-1)^{1/2},(a^2+1)^{1/2})$. Clearly very small $\delta$'s are fine, until either $a-\delta$ hits $(a^2-1)^{1/2}$ or $a+\delta$ hits $(a^2+1)^{1/2}$. So we have to work out $a-(a^2-1)^{1/2}$ and $(a^2+1)^{1/2}-a$ and our best $\delta$ will be whichever is the smaller of these two numbers.
So I understand everything up to here, but I get lost now. How do you get these 2 values?
The first is $\frac{1}{a+(a^2-1)^{1/2}}$ and the second is $\frac{1}{(a^2+1)^{1/2}+a}$, of which $\frac{1}{(a^2+1)^{1/2}+a}$ is the smaller.
And I also don't see how one works and the other won't work :/
So any $\delta\le\frac{1}{(a^2+1)^{1/2}+a}$ will work, and any $\delta\ge\frac{1}{(a^2+1)^{1/2}+a}$ won't work.
Thus we clearly cannot find a $\delta$ which works uniformly for all $a>1$. The best $\delta$ goes to $0$ when $a$ gets larger and larger.
Answer: You have:
$\displaystyle a-(a^2+1)^{\frac{1}{2}}=\frac{a+(a^2+1)^{\frac{1}{2}}}{a+(a^2+1)^{\frac{1}{2}}}(a-(a^2+1)^{\frac{1}{2}})=\frac{a^2-a^2-1}{a+(a^2+1)^{\frac{1}{2}}}=\frac{-1}{a+(a^2+1)^{\frac{1}{2}}}$
It's by $(x+y)(x-y)=x^2-y^2$.
Answer: It is a well-known technique using the difference of two squares identity to show, say, that $$\frac{1}{a+(a^{2}-1)^{1/2}}=\frac{(a-(a^{2}-1)^{1/2})}{(a-(a^{2}-1)^{1/2})(a+(a^{2}-1)^{1/2})}=\frac{a-(a^{2}-1)^{1/2}}{a^{2}-(a^{2}-1)}=a-(a^{2}-1)^{1/2}$$
Can you see now why one of your quantities is bigger than the other?
Now, our best $\delta$ should obviously be in $[a-(a^{2}-1)^{1/2},(a^{2}+1)^{1/2}-a]$, since that was how we found those two quantities in the first place. Notice that if we choose a $\delta$, and it works for some $x_{0}\in(x-\delta,x+\delta)$, then it also works for all of $(x_{0},x+\delta)$.
Now what if we chose $\delta=(a^{2}+1)^{1/2}-a$?. Then when $x=a+\delta$, $x^{2}=a^{2}+1$ as required. But when $x=a-\delta$, $x^{2}=(2a-(a^{2}+1)^{1/2})^{2}>a^{2}-1$, so we are 'missing' some of our interval.
Comment: Not quite $|a-x|<\delta$ means $-\delta<a-x<\delta$, which rearranges to $a-\delta<x<a+\delta$. This is the same as $|x-a|<\delta$, as we should expect.
Comment: Thanks a lot! I am a little confused though... I thought $|x-a|<\delta$, which is equivalent to $x-a<\delta<a-x$. However, we can also write the inequality as $|a-x|<\delta$, in which case it would be $a-x<\delta<x-a$, so I guess this is the one that has been used to solve this exercise, am I right?


How do I add a layer to a neural network in Matlab?

Question:
I have the above Layer Recurrent Neural Net from Matlab. I wanted to know, just how do I add an extra Hidden layer to this? Am I not understanding this correctly or is there only one layer here - with 3 neurons and 1 feedback loop? Could someone please rectify this for me?
Answer: It's simple, did you see the Hidden part in the graph above? copy the structure to form another Hidden layer, and let the output port of the first hidden neural unit to stream into the second hidden layer's first input port, with the second input point connected with the output port of itself. Then let the output port of the second hidden layout stream into the W port of Output unit.That's Okay now.
Comment: How do I do it Graphically? I did this simply using the command line stuff.
Comment: Can u just use the MATLAB Neural Network Tool Box? There's many recipe for u to handle this sort of problems, it's very easy, try to check the help document within MATLAB, like 'help bp' see if it pop up a window telling u how to use the tool box of ANN?


Classification groups of order 6 and 10

Question: I have this approach to classify groups of order $6$ and $10$. Let $G$ be a group with $|G|=n$
If $n=6$, then by Sylow there is an element $g$ of order $3$. Hence $N:=\langle g\rangle$ has index $2$ and is normal. Let $x \in G-N$ such that $G=N \cup xN$. Then $x^2\in N$ (otherwise $x^2 \in xN \Rightarrow x \in N $). If $x^2 \neq e$, then $\operatorname{ord}(x)=6$ since $x^3 \in xN$ and we find the cyclic group. If $x^2=e$, then the consider conjugation map $\gamma_x :N\longrightarrow N$ with $\gamma_x(g)=xgx^{-1}$. Now the step I'm going to ask about. Since $N=\{e,g,g^2\}$ it's either $g=xgx^{-1}$ or $g^2=xgx^{-1}$. In the first case $G$ is abelian (and cyclic by the Chinese remainder theorem) and in the second case isomorphic to the dihedral group.
What if $n=10$? I can proceed exactly as in the case $n=6$, but the conjugation map could now have many different images:
i) $\gamma_x(g)=xgx^{-1}=g$ (in this case $G$ is abelian)
ii) $\gamma_x(g)=xgx^{-1}=g^2$
iii) $\gamma_x(g)=xgx^{-1}=g^3$
iv) $\gamma_x(g)=xgx^{-1}=g^4$ (in this case $G\cong D_5$)
I don't see how one can lead ii) and iii) to any contradiction.
Comment: Please: Proper notation is $N:=\langle g\rangle,$ not $N:=.$ I edited accordingly.
Answer: The contradiction is as follows: as $x^2=e$, then $\gamma_{x^2}=\gamma_e$ should be identity. However, it's not:
$$g=ege=x^2gx^{-2}=x(xgx^{-1})x^{-1}=xg^2x^{-1}=xg(x^{-1}x)gx^{-1}=(xgx^{-1})(xgx^{-1})=g^2g^2=g^4\ne g$$
(in case (ii), and similarly in case (iii)).
Comment: This is also related to the possible semidirect products $N \rtimes_{\gamma} K$ you can obtain where $K = \langle x \rangle$. The automorphism group of $N$ is cyclic of order 4 and the possible semidirect products correspond to homomorphisms $\gamma:K \to N$. Cases (i) and (iv) correspond to the possible homomorphisms from $K$ to $N$ where as (ii) and (iii) are not homomorphisms since $x$ must be mapped to an automorphism of order 1 or 2.

Classification groups of order 6 and 10


Two highly correlated variables where both correlate with a third: Correlation and Causation

Question: My question is certainly quite basic for statisticians!
Let's suppose Var1 and Var2 are highly correlated with a poor $R^2$.
Var3 is another variable that we will use in a regression (standard linear model (Gaussian error distribution, OLS estimator)) as a response variable. Var1 and Var2 are the explanatory variables of this regression where the interaction effect is not computed. Let's call this regression regression1
Is it possible that Var1 affects Var3 (highly significantly) but not Var2 (not significant at all)?
Let's assume that the causation is the following: Var1 causes Var2 and Var3 Is it plausible that both Var2 and Var1 are associated with highly significant p-value in regression1?

For example:
In a given species of fish, there is a very significant relation between the size of the fishes and the color of the fishes. But the linear model that gives this very significant p-value does not explain much of the total variance in fish color and size.
When performing a regression of depth on fish size and fish color (without the interaction term), I get two highly significant p-values (for the two explanatory variables).
Can I infer that both the size of the fishes and the color of the fishes "influence separately" the depth at which the fishes are?
Or maybe depth has an effect on the color of the fishes (because the diet is different for example) and the color of the fishes influenced the size of the fishes (because fishes that are bright need be big to escape predators or something like that). In such case, the size of the fishes would be associated to a significant p-value (in the regression of depth) only because it is correlated to the other explanatory variable which is the color of the fishes.
Comment: what does it mean, "highly correlated with a poor R.square"?  R.square is a measure of correlation.  Either they are highly correlated with a high R.square, or weakly correlated with a poor R.square.
Comment: OLR sounds like a guess at OLS. Note that OLS does not characterise linear regression; OLS is an estimation method and linear regression a family of models.
Comment: @user31264 I meant that there is a very significant correlation between the two but the model explains not much of the total variance. Does it makes sense? Let me know how I should rephrase my question.
Comment: @NickCox Yes I knew that but made it wrong! Thanks for the remark, I corrected it. Let me know if it still sounds fuzzy.
Comment: Attempts at abstraction in this kind of question usually go in the wrong direction unless you want e.g. a formal proof. Presumably this grows out of real example(s). Better that you give one, ideally with data too.
Comment: I can't give you the data because my data table is too big and I don't quite know how to subset it so that the regression looks like the original regression ! But I added an example hoping that makes more sense! Thanks for your help @NickCox
Comment: "*the linear model that gives this very significant p-value does not explain much of the total variance in fish color and size.*" --- this may be explained by the large sample size.
Comment: @Glen_b Yes, indeed! My question is *Can I infer that both the size of the fishes and the color of the fishes "influence separately" the depth at which the fishes are?* Hope my question makes sense when reading the last paragraph.
Answer: The comment made by @user32164 still stands as I write: "highly correlated with a poor $R^2$" is contradictory. Regardless of what you consider as highly correlated, a high correlation means a high $R^2$.
I am assuming that you measured color somehow so that it may fairly be used as a quantitative predictor in a regression model. Whether that's so is an issue that people in your field might debate, but I'll take it as read.
We know what you mean, but language such as "very significant p-value" is a little loose. A low P-value indicates that an effect, difference, relationship, whatever is significant, but the P-value itself is an indicator of significance, not something that is itself significant.
Those small points aside, we need to distinguish different kinds of question here.

Statistical and causal inference Focusing on your example, whether fish color causes depth at which fish are seen, or vice versa, or both, is a biological question on which statistical people have little to say. They might help you design an experiment to test the underlying hypotheses, but  from the example as given the extent to regression can be used to infer causation (existence and/or direction of causal relationships) is very limited. There is an enormous literature on this, but I think there is consensus that predictive ability as shown by regression is not sufficient to infer causation.
Significance and strength of relationship You appear to be confusing significance of relationship and strength of relationship at a basic level. With moderate and especially large sample size, it is perfectly possible to get significant results (at conventional levels) that are only weakly predictive. Usually, a significant result underlines that some quantity of interest is not zero, but that itself doesn't make it major or substantial scientifically or practically.
Separate effects of predictors You can't infer that predictors have separate effects just from the evidence you cite. If you have some $x_1$ as predictor and then add $x_2$ as another, whether the coefficient of $x_1$ changes is one thing to look at. You should benefit from testing the interaction. You always benefit from thinking about what the underlying science indicates about possible relations between $x_1$ and $x_2$.


UIButton leaves white background behind button image and title

Question: I UIButtons with image and title on it. I am using appearanceWhenContainedInInstancesOfClasses: to change theme in the app. When I change the background and title colors of the UIButton depending on the theme I want, it leaves some white background behind the title and image of UIButton(Image below shows it).
How do I get rid of the white background behind the button label and image?
Answer: You could use the following code for your each button.
btn.backgroundColor = [UIColor clearColor];
btn.opaque = NO;

In Detail:
The root of your problem, the default background color of your buttons is white, therefore once you apply a background color/theme to your UIView where your buttons reside, then white color becomes visible and not looking good. Therefore I recommend to change btw color clearColor or UIView color to white.
Comment: I tried that but it doesn't work. The UIView has the color you see as default color. Does the image and button label on a UIButton has some uiview beneath it?. If it has how to access it?
Comment: You are adding button on the top of UIView. Therefore, on the z plane, Button on the top, UIView is under. If you change button background color to clear, then there will be no background color for the btn
Comment: I am setting white color for uiviews globally like this:`[[UIView appearanceWhenContainedInInstancesOfClasses:@[[GoogleAdsViewController class]]] setBackgroundColor:[UIColor whiteColor]];`. I discovered that this is causing the problem. Not sure how to solve this.
Comment: Try the following `[[UIView appearanceWhenContainedInInstancesOfClasses:@[[GoogleAdsViewController class]]] setBackgroundColor:[UIColor clearColor]];`
Comment: Tried that already but that spoils my other views since I am using this for a theme.
Comment: you have set image in button background image or simple image?
Answer: Either you might have set the image of button in background or your images themselves have white background.


Display images - c# / silverlight

Question: Experts,
I'm developing an application in Windows phone, Where i need to display images in screen in table format (2 images in row and columns will be growing as required).
Image count will be dynamic, which i will have the information at runtime.  I need to display all the images

can you please let me know how to proceed.. images will be from internet url.
Pavan
Comment: Will all images have the same width & height?
Comment: yes.. all images with same exact dimention
Answer: This is a perfect case for the use of the WrapPanel from Silverlight Toolkit.
It would basically do precisely what you need, with a single line of code.
Comment: I have used the WrapPanel before for text-items ordered in a same manner, and indeed the WrapPanel is what you're looking for! :)
Comment: I want to add images progrmatically, because i don't know how many images will be there..
Comment: And? Add them to a `ObservableCollection` and there's no problem at all.
Comment: Thanks Claus. Wrap Panel is the best solution
Comment: Any one looking for same kind of issue.. Please refer to this link http://www.kotancode.com/2010/12/29/wp7-presenting-listbox-items-inside-a-wrappanel/
Answer: The images will bind to an ItemsControl, and then you'll use an ItemsPanel to control the layout of each item.
Check out this link for a guide. http://www.windowsphonegeek.com/tips/working-with-itemspanel-in-wp7
Answer: I am a kind of beginer but I did it with 4 images and a full screen form. I havent try with C# for Mobile.
Try with this :) code, It will put you only 4 images on anny type of screen Form1 set to start @ center of screen and add set it to full screen mode. After you add 4 imageBox to form and set their image or load it this will set 1 image to 1/4 of full screen.  :
public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Left, Screen.PrimaryScreen.WorkingArea.Top);
            this.Size = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            pictureBox1.Size = new Size(this.Width - this.Width / 2, this.Height - this.Height / 2);
            pictureBox1.Location = new Point(0, 0);
            pictureBox2.Size = new Size(this.Width - this.Width / 2, this.Height - this.Height / 2);
            pictureBox2.Location = new Point(this.pictureBox1.Width,0);
            pictureBox3.Size = new Size(this.Width - this.Width / 2, this.Height - this.Height / 2);
            pictureBox3.Location = new Point(0, this.pictureBox1.Height);
            pictureBox4.Size = new Size(this.Width - this.Width / 2, this.Height - this.Height / 2);
            pictureBox4.Location = new Point(this.pictureBox2.Width, this.pictureBox3.Height);
            // this.Controls.Add(pictureBox1);
        }
    }
}

Display images - c# / silverlight


New Table based on another Table values

Question: I want to create a new table in Power BI using values of another table. My Original table ARM DATA, has three columns Destination, Sales and Product. I want to create a new table with all the possible DEST and the Sales when the product equal "PHA".
This is my current DAX formula but I don't know how to add only sales for Pharma.
New Table =
SUMMARIZE(
    'ARM DATA',
    'ARM DATA'[Destination],
    "Sales", SUM('ARM DATA'[Sales])
)

Can this be done?
Answer: Can you please try this below-
New Table =
SUMMARIZE(
    FILTER('ARM DATA', 'ARM DATA'[Product] = "PHA"),
    'ARM DATA'[Destination],
    "Sales", SUM('ARM DATA'[Sales])
)

Comment: You can check the data type of column "calendar year". The way you are applying the filter, it should must work if the data type is number.
Comment: This works thank you! What if you want to add two conditions, so not only PHA but also Year = 2023. I am using this formula but it is not working
NewTable =
SUMMARIZE(
    FILTER('ARM DATA', 'ARM DATA'[Product] = "PHA" && 'ARM DATA'[Calendar Year]=2023),
    'ARM DATA'[Agent Group Name],
    "CWT", SUM('ARM DATA'[Sales])
)

New Table based on another Table values


MongoDB no Azure

Question: Há um tempo atrás eu tive uma surpresa desagradável em minha fatura no azure por conta de um banco de dados MongoDB que eu possuía para acesso de uma aplicação.
Criei, por exemplo, os documentos:

Cliente
Produto
Pedido

Fiz toda a programação de forma relacional (obviamente contra os padrões no-sql, mas...) no fim das contas a azure me deu uma conta absurda para pagar pois considerava cada documento criado como se fosse uma base de dados. Assim, cobrava por uso individual dos documentos.
Contornei essa situação, utilizando apenas um documento para armazenar clientes produtos e pedidos. Claro que cada um com um campo "type" especificando o que era, para poder obtê-lo posteriormente.
Minha dúvida: Não consigo acreditar que isto está correto, porém, não penso em outra forma para resolver.
Hoje eu já descontinuei a aplicação, então isso é simplesmente uma dúvida mesmo.
Qual a melhor forma para se modelar estes tipos no mongodb nesta situação?
Cria-se realmente um documento para cada tipo de objeto?
Cria-se um atributo especificando o tipo do objeto para posterior utilização?
Alguém pode dar uma luz?
Obs.: Minha aplicação foi desenvolvida com c#.
Comment: Isso é um absurdo, banco de dados é uma coisa, documento é outra.No mundo relacional o documento seria a linha de uma tabela, então não há motivos para você ser cobrado como cada documento representar um banco de dados. A não ser que a Azure esteja te cobrando pelo n° requisições e não pelo banco em si. Neste caso, poderia então ter uma conta alta se tem muitas requisições.
Comment: Eu uso o mongodb atlas, la dentro você consegue um plano gratuito para o banco, porém essa opção só está disponível para o AWS.
Comment: Entendo. Mas na realidade, esta não é a questão. É mais um caso de modelagem e experiência também
Comment: Infelizmente, não tenho mais os fontes. Mas posso dar um exemplo aqui, onde teria uma tabela produtos, uma clientes e uma orçamentos. Pelo que entendo deveria modelar um documento para cada correto? Se não, neste contexto do AZURE, como faríamos?
Answer: O caso Cliente, Produto e Pedido não são documentos, muito menos bancos de dados eles são coleções, a forma a qual está fazendo está certa (Caso realmente estiver os criando como coleções) o único problema na sua modelagem é seguir a estrutura relacional que na verdade só deixa o MongoDB lento...
Houve realmente um problema na sua fatura e eles não deveriam ter te cobrado por diversas bases já que provavelmente você tinha 1 base e 3 coleções.
Caso houver dúvidas de criação e você ainda tiver o Script de criação das bases utilize os comandos a seguir para confirmar o que eu disse:
<code>show dbs //Mostra todas bases
show collections // Mostra as coleções
</code>
Importante: o MongoDB ao ser instalado já cria 2 bancos de dados chamados Admin e Local, você podia estar pagando por eles em adição ao seu.

MongoDB no Azure


Why did Listz and Hanon use the word "transcendent" to describe piano exercises?

Question: The middle set of piano exercises by Hanon is described as "transcendent".

'Transcendent Exercises for Preparing the Fingers for the Virtuoso Exercises.
  Practise the exercises in Part II, like those in Part I, with the metronome at 60; similarly practise all the following piano exercises where the tempo is not indicated, and gradually'...

Franz Liszt wrote "Transcendental Etudes". Having grown up in the era of Transcendental Meditation I find this an unusual use of the word. Does anybody know what they intended by it?
Comment: The Liszt might be better translated as "transcendent" (see https://en.oxforddictionaries.com/definition/transcendent 1.1) to match the French title: "Études d'exécution transcendante''). Hanon wasn't a piano teacher but a marketing guy, so in his case it didn't matter what the word meant so long as you bought the product!
Answer: The German wikipedia offers the explanation, that Liszt used this term as an ironic reaction to a statement by Fétis, that Liszt could be considered as eminent representative of a school, which came to an end, but without founding a new school [my translation].
Considering, that Latin transcendere simply means to leave one thing and move to another, its meaning is not so exclusive as the word sounds and could be simply replaced by something like exceeding (which would also easily be applied to the difficulty).


symfony ApiTestCase to tests post method

Question: I tried to make a simple post test api with ApiTestCase with symfony.
I tried two methods to pass the post data
$response = static::createClient()->request('POST', '/task/create',
        [
            'body' =>  [
                'name' => 'test',
                'description' => 'The Handmaid\'s Tale',
            ]
        ]
    );

    $response = static::createClient()->request('POST', '/task/create', ['json' => [
        'name' => 'test',
        'description' => 'The Handmaid\'s Tale',
    ]]);

For both exemples I got this message error

An exception occurred while executing a query: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null

I know  what it is but the issue here it is like the data  wasn't sent or seen by the request, how can I resolve this issue, Thanks.
The controller to get all data in body :
$data = $request->request->all();

Comment: Were you able to resolve the issue with empty `body`/`json`? Struggling for 4 hours already
Answer: I believe you've already resolved it but apprarently your setter is not accepting null
I resolved this by changing
/**
     * @param string $name
     * @return $this
     */
    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

to this
/**
     * @param string|null $name
     * @return $this
     */
    public function setName(?string $name): self
    {
        $this->name = $name;

        return $this;
    }

The API testing part of Symfony is really poorly documented and contains only most primitive examples