Como usar @Html.ActionLink para criar links para uma Rota de vários seguimentos?

Question: Eu gostaria de usar o @Html.ActionLink para criar o seguinte link:
http://localhost:59278/video/categoria/new-movies/3

Sendo que meu controle é:
[Route("video/categoria/new-movies/{page?}")]
public async Task<ActionResult> Index(int? page)
{

}

Eu sei usar o @Html.ActionLink passando parâmetros, mas no caso o parâmetro page é parte da rota.
Answer: Você está utilizando o Attribute Routing, então lembrando apenas que você deve chamar o método MapMvcAttributeRoutes() seu RouteConfig com a seguinte linha:
routes.MapMvcAttributeRoutes();

Feito isso, basta adicionar o atributo em seu controller, da mesma forma que você está fazendo.
[Route("video/categoria/new-movies/{page?}")]
public async Task<ActionResult> Index(int? page)
{

}

Até essa parte eu suponho que você já possui, então agora vamos ao seu ActionLink().
@Html.ActionLink("TEXTO","Index","CONTROLLER",  new { page = 3 }, null)

Lembrando que seu actionLink "trabalha" da seguinte forma:
MvcHtmlString HtmlHelper.ActionLink(
    string linkText,
    string actionName,
    string controllerName,
    object routeValues,
    object htmlAttributes
)

A "grosso modo", em primeiro lugar você passa o texto, depois a Action, o Controller, os valores de rota e atributos html.

Como pode ver, no ActionLink "você não se preocupa" com as rotas, chame apenas a Action e o Controller, lembrando de passar os parâmetros necessários.
Comment: Funcionou, agora, quando eu coloco uma variável a mais no controle , `string sort` e uma a mais no HTML.ActionLink `new { page = 3, sort = "newest" }` ele gera a url assim: `http://localhost:59278/video/categoria/new-movies/3?sort=newest`.. Não deveria gerar assim: `http://localhost:59278/video/categoria/new-movies/3/newest`? O que fiz de errado?
Comment: Se você mudar somente no `ActionLink` ele irá adicionar como queryString. Para evitar isso, você deve alterar a sua rota, mais ou mesmo assim: `[Route("video/categoria/new-movies/{page?}/{sort}")]`
Comment: Pois é, eu fiz isso tb... esqueci de colocar `        [Route("video/categoria/{categoria}/{page?}/{sort?}")]` mas ele não funcionou não... Estranho
Comment: Repare que você está passando a categoria como parâmetro `{categoria}`, e não como valor fixo `/categoria/`.
Comment: Putz, to alterando o metodo errado, deu certo, obrigado!


Pretty urls Apache

Question: I have a site where URL looks like www.abc.com/abc.php?id=10, now i want to change these to pretty URL like www.abc.com/abc/10, is it possible without rewriting the code if yes then how can i do that and any possible way without htaccess .
Comment: use htaccess for redirection and rewrite the urls in new format
Comment: Hi @donald123. i forgot to mention in my question that i don't wanna use htaccess. is it still possible without that ?
Answer: U can simply use rewrite url within htaccess file.
URL Rewrite
And if you want to rewrite url without using htaccess then you can refer this post
Answer: Create file .htaccess in your public_html or www and add the following code into file .htaccess
RewriteEngine On
RewriteRule ^abc/([^/]*)$ /abc.php?id=$1 [L]

After doing above process you can access you script by using www.abc.com/abc/10

Pretty urls Apache


Formatting numeric values to time in R

Question: I want to format my numeric sleep minutes in a data frame to time in R. For example, this is what the data frame looks like:
TotalMinutesAsleep 327

sleep.day.1$TotalMinutesAsleep <- hms(sleep.day.1$TotalMinutesAsleep)

I need a quick and easy solution.
Thx,
Comment: Thanks again, I done that and created a new data frame. Now, I am struggling with plotting this data. Mine is all over the place and most tutorials go over dates and not hours and minutes.
Answer: If these values are in minutes, convert to seconds and use seconds_to_period
library(lubridate)
period1 <- seconds_to_period(sleep.day.1$TotalMinutesAsleep * 60)

then, we may format it with
sprintf('%02d:%02d:%02d', period1@hour, period1@minute, second(period1))

Comment: Ahhh, library(hms), I will try that. Thank you!
Comment: sprintf? I will use it, do you have a link to explain?
Comment: @Baccara the `seconds_to_period` returns a `period` class object and `sprintf` is just doing the formatting on the extracted period elements with `@`
Comment: I have created a new data frame with everything formatted. I am struggling with graphing it. Is there a package that will help?
Comment: @Baccara you may post as a new question.  If the current solution works, please consider to accept solution
Answer: We coul use hms part of the tidyverse: A simple class for storing time-of-day values
library(hms)
hms(sleep.day.1$TotalMinutesAsleep*60)

output:
05:27:00

Formatting numeric values to time in R


Views-overriden taxonomy/term page returns not found

Question: I am trying to override the default taxonomy/term/xxx page with a page created by views.
My view: I have followed the usual instructions with using url taxonomy/term/%, gave it a contextual filter that is validated to a term name. In the preview results box of this view, I can use a term as an argument, and get the results correctly.
But when use the url in the real site, I get a 404. Regardless what the url alias pattern is for the default taxonomy term pages, when this view is enabled no term will return a page.
Turning my view off->term page urls work
Turning my view on ->term pages stop working.
I have no other view with the same URL enabled.
Answer: I was able to solve this only by duplicating the "taxonomy" view. This view's argument configuration makes it a viable solution.
After configuring/enabling this view, you can set the taxonomy url aliases to work in the same way.
A working example: http://www.indice.gr/portfolio/all shows "all" projects, wheras http://www.indice.gr/portfolio/mobile-application shows projects under the mobile-application term. Yay!


Translating Minimal Cover into 3NF

Question: I have the below functional dependencies in minimal cover, and I am looking to put them into 3NF lossless join and dependency preserving decomposition.
FD 1: {A} -> {B,C,D,E};
FD 2: {F} -> {G,H,I,J,K};
FD 3: {G,H,I,L} -> {M};
FD 4: {N} -> {O,P,F};
FD 5: {N,B} -> {Q,L};
Key: {A,N}
The key is A,N and are the determinants of FD1 and FD4, I am unsure whether my 3NF decomposition should contain and extra table that contains all of the attributes from the FD1 and FD4 so that I can preserve the key? or that they should not be merged so that I can reduce redundancy if they were to be merged?
Thanks in advance!
Answer: In general the 3NF is found through an algorithm that details all the steps that produce a correct decomposition. Such algorithms are described in all good books on databases. For instance, in your case, the so-called "synthesis" algorithm produces the following decomposition:
R1 {A B C D E}
R2 {B L N Q}
R3 {F G H I J K}
R4 {G H I L M}
R5 {F N O P}
R6 {A N}

Note that the relation R6 contains the key of the original relation, and this is necessary to guarantee the lossless join property.

Translating Minimal Cover into 3NF


Register nodes seen in a view as not "new"

Question: I have a view of nodes, the only place those nodes will be seen is in the view - never as individual entities. These are short "updates". When someone has seen an update, I no longer want it marked as "new" (as in drupal's 'content: has new content' functionality).
Is it possible to trigger whatever it is that makes entities 'read', but when that node is loaded into to a view on a page the user is viewing?
Comment: Do you want to "unmark" the node as "new" for all user after at least one user sees it? Or are you trying to keep track of the "seen status" for each individual user? (i.e. even after user B has seen the update, user A will still see the "new" marker for that update until he opens it)
Comment: Keep track of the seen status for individual users.

Just exactly as it currently works when viewing a node, but considering seeing it in a view as viewed,
Answer: The New or Updated mark is generated by a simple theme function (theme_mark) which can be overriden. Normally you would do that in your template.php but since this theme function is used in the admin theme, that's not gonna work.
A workaround for this is to add your own theme function to a custom module, like this:
/**
 * Implements hook_mark().
 */
function yourmodule_mark($variables) {
  // Always return an empty string.
  return '';
}

Now, we need to add this function to the theme registry like this:
/**
 * Implements hook_theme_registry_alter().
 */
function yourmodule_theme_registry_alter(&$theme_registry) {
  // Check if the default theme function of mark exists
  // and override it with our own theme function.
  if (isset($theme_registry['mark']['function']) {
    $theme_registry['mark']['function'] = 'yourmodule_mark';
  }
}

Clear your cache and your done.
You'll find the original theme function here in the Drupal docs.
Note that this code will permanently override the output of this function where ever it is used.


Using tokens with SSL VPN

Question: Could somebody explain how tokens fit into the VPN world? We currently use Citrix XenApp as our remote access solution and it works very well. But we're considering adding an additional layer of security with tokens. We're not in the SecurID price range but something like SafeWord looks good. To complicate matters, we're also looking at establishing a VPN to allow both direct network access and Citrix. I understand how VPN works in theory and for us, this box looks ideal:
http://www.netgear.co.uk/ssl_vpn_concentrator_ssl312.php
But not sure if this solution would fit in with a token system. I suppose I'm asking what are all the bits in a token based VPN solution? What boxes and bits of software usually make up the blend?
Cheers, Rob.
Answer: A minor correction to "radius": most of the "big name" (and quite a lot of the not-so-big) VPN vendor support the RSA SecurID protocol natively. That means integration with SecurID is (mostly) a case of configuring the VPN device with the necessary information to locate the SecurID servers (that's contained in what RSA calls the "sdconf.rec" file).
You load it up in the VPN box and off you go.
Of course, using RADIUS is also an option, but you don't have to stand-up a separate Radius server, as the Authentication Manager server comes bundled with a cut-down Radius server precisely to be able to "talk" radius with the devices that don't support the SecurID protocol natively (other times it's been called ACE or SID).
For more information and detailed configuration guides, RSA publishes guides to all certified products (ie, those that have gone through a certification process, but many more are working with SecurID fine), in the site http://www.rsasecured.com
Hope this helps
Answer: For SecurID you have to install a Radius server, then just to configure your VPN concentrator to use this Radius server.
I guess that SafeWord is working in the same,I don't see how it could work is another way.
As the spec of the concentrator say that it support RADIUS "Supports multiple backend user repositories, including Microsoft Active Directory, LDAP & RADIUS" it should be OK.
Just ask SafeWord is they do use a Radius server

Using tokens with SSL VPN


Problemas SDK no Fedora Workstation 24

Question: A poucos dias instalei o Fededora 24, com tudo concluído instalei o Ionic e Cordova, e logo depois o JDK. Ao dá o seguinte comando ionic build android eu verifiquei que faltava o SDK, instalei normalmente, porem ao executar o comando novamente eu obtive o seguinte erro:

You have been opted out of telemetry. To change this, run: cordova telemetry on.

Running command: /home/omestre/IonicProjects/ionicTask/hooks/after_prepare/010_add_platform_class.js /home/omestre/IonicProjects/ionicTask

add to body class: platform-android

Error: Failed to find 'ANDROID_HOME' environment variable. Try setting setting it manually.
Failed to find 'android' command in your 'PATH'. Try update your 'PATH' to include path to valid SDK directory.

Já tentei altera o meu arquivo bashrc e nada resolve, segue como está o arquivo:

# .bashrc

# User specific aliases and functions

alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'

# Source global definitions
if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi

export NVM_DIR="/root/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"  # This loads nvm

export PATH=$PATH:/Android/Sdk/tools:/opt/Android/Sdk/platform-tools:/Android/Sdk/tools/bin
export PATH=/usr/lib64/qt-3.3/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/home/omestre/.local/bin:/home/omestre/bin:/Android/Sdk/tools:/An$
export PATH=/usr/lib64/qt-3.3/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/home/omestre/.local/bin:/home/omestre/bin:/Android/Sdk/tools:/An$
export PATH=/usr/lib64/qt-3.3/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/home/omestre/.local/bin:/home/omestre/bin:/opt/Android/Sdk/tools$
export PATH=/usr/lib64/qt-3.3/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/home/omestre/.local/bin:/home/omestre/bin:/Android/Sdk/tools:/op$
export PATH=$PATH:/opt/Android/Sdk/tools:/opt/Android/Sdk/platform-tools:/opt/Android/Sdk/tools/bin
Answer: A solução foi, no terminal da o seguinte comando:
nano ~/.bashrc
Substitui as quatro ultimas linhas por:
export ANDROID_HOME=/<installation location>/android-sdk-linux
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

Ctrl + x para salvar e reiniciar a sessão para as novas configurações serem reconhecidas

Problemas SDK no Fedora Workstation 24


Comparativo entre IDEs para java

Question: No próximo semestre terei que escolher entre duas IDEs: NetBeans e Eclipse.
Precisarei desenvolver aplicativos para desktop, e estou com dúvidas em relação a:

Ferramentas para interface gráfica
Requisitos de Hardware para um desempenho considerável
Compatibilidade com SGBD (PostgresSQL)

Levando em consideração a configuração do meu notebook, o fato do uso ser para estudo (Faculdade),levando em consideração o programa padrão, sem plugins e extensões, o que preciso saber sobre um ou outro?
Comment: Essa pergunta é baseada em **religiões**. Várias perguntas boas geram algum grau de opinião baseadas na **religião** de **evangelistas**...
Comment: Baixe os dois. Ambos suportam Maven.Você pode usar o melhor de cada IDE (e.g., editor de UI do Netbeans e suporte a OSGI do Eclipse). Ninguém vai conseguir te dizer qual o melhor IDE para o seu caso além de você  (todos fazem o básico - code completion, refactoring, navegação, depuração, etc - muito bem). Leveza, responsividade e organização de funcionalidades é questão de gosto.
Comment: Eu acho que algumas edições e indicações de terceiros estão piorando a pergunta. Eu tenho minhas dúvidas se dá para salvá-la a não ser que mude radicalmente e foque em uma ponto específico. Enquanto ficar pedindo uma comparação geral sem critério não vai pra frente. Ele abriu discussão no meta: http://meta.pt.stackoverflow.com/q/2336/101
Comment: se tiver um computador mediano use eclipse, pois é mais leve porem se tiver um pc melhor use netbeans pois tem mais funcionalidades e você acaba sendo mais produtivo.
Answer: As diferenças entre o Netbeans e o eclipse são muito poucas, por isso este assunto rapidamente se transforma baseado em opiniões, contudo ficam aqui algumas especificações:
Link:http://development-software.findthebest-sw.com/saved_compare/Eclipse-vs-NetBeans

Sistema Operativo suportado:

Características:
Funcionalidades:

Recursos do editor:

Ferramentas de teste:

Plugins disponível:

Controle de Versão:

Bases de dados suportadas:

Total de download:

Mínimo de memória:

Como podes reparar as duas IDE's são muito parecidas, logo não optes por nenhuma e usa as duas, ambas servem para programar Java logo ambas vão servir para ti, ainda por cima vais usar a nível educacional, logo o que necessitas, é de ter alguma experiência não um "expert" da IDE, assim no futuro SE na empresa onde trabalhares usar uma ou outra estarás mais a vontade e ai sim passas a um expert da IDE com que a empresa trabalha.
Comment: Mas isso respondeu minha pergunta, pois não quero estar instalando plugins...
Comment: Ambos os IDEs são modulares. Isso é verdade para a Plataforma do NetBeans (com sistema de módulos próprios, caminhando em direção ao Apache Felix) e para a Plataforma Eclipse (em cima no Equinox). Por definição ambos os IDES são compostos de uma coleção de *plug-ins*. A principal diferença aqui é só o download inicial. A distribuição com tudo o que tem direito do Netbeans possui suporte a várias coisas que a distribuição padrão Java EE do Eclipse não contempla (e vice-versa); por outro lado não é difícil encontrar distribuições "all inclusive" do Eclipse como o MyEclipse.
Comment: O Eclipse também suporta outros controles de versão além do Git, mas para isso depende de plugins. E também suporta PostgreSQL (tem um driver JDBC para ele), mas do jeito que está escrito dá a impressão que somente o Netbeans é que suporta, o que não é verdade.
Comment: @Piovezan como pode reparar eu fui buscar a informação ao link que postei, nao é da minha autoria, contudo quanto ao "PostgreSQL" não tenho conhecimento mas acredito perfeitamente que funcione, agora quanto ao controle de versão está correto, como mesmo disseste " suporta outros controles de versão além do Git, mas para isso depende de plugins"

Comparativo entre IDEs para java


Prove that $\sqrt{ c} − \sqrt{c − 1} \geq \sqrt{ c + 1} −\sqrt{c}$ for all real $c \geq 1$.

Question: Prove that $\sqrt{ c} − \sqrt{c − 1} \geq \sqrt{c + 1} −\sqrt{c}$ for all real $c \geq 1$.
Can anyone provide some form of guidance? So far all I have been able to think of is writing $c$ as $x^2$ for some $x$, or eliminating the radical on one side...
Comment: The concavity of $\sqrt x$ means $$\sqrt c \ge \frac{\sqrt{c-1}+\sqrt{c+1}}2$$
Answer: We have:
$$
\sqrt{c}-\sqrt{c-1}≥\sqrt{c+1}-\sqrt{c}\iff\\
\\
\left(\sqrt{c}-\sqrt{c-1}\right)\frac{\sqrt{c}+\sqrt{c-1}}{\sqrt{c}+\sqrt{c-1}}≥\left(\sqrt{c+1}-\sqrt{c}\right)\frac{\sqrt{c+1}+\sqrt{c}}{\sqrt{c+1}+\sqrt{c}}\\
\\
\frac{1}{\sqrt{c}+\sqrt{c-1}}≥\frac{1}{\sqrt{c+1}+\sqrt{c}}\iff\\
\\
\sqrt{c+1}+\sqrt{c}≥\sqrt{c}+\sqrt{c-1}\iff\\
\\
\sqrt{c+1}≥\sqrt{c-1}
$$
and the last one is trivial.
Answer: To show
$\sqrt{ c} − \sqrt{c − 1}
\geq \sqrt{c + 1} −\sqrt{c}
$.
This is the same as
$\sqrt{c}
\ge \frac{\sqrt{c + 1}+\sqrt{c - 1}}{2}
$.
If
$f(x) = x^{1/2}
$,
then
$f'(x) = \frac12x^{-1/2}
$
and
$f''(x) = -\frac14x^{-3/2}
< 0
$
so
$f(x)$
is concave
which means that
$f(\frac{a+b}{2})
\ge \frac{f(a)+f(b)}{2}
$.
Answer: Hint:
study the variations of the function:
f(x) = (left hand side of your inequality)
this should then yield the answer very quickly
Answer: Note that $\sqrt{c+1}\geq \sqrt{c-1}$ and so $\frac{1}{\sqrt{c}+\sqrt{c-1}}\geq \frac{1}{\sqrt{c}+\sqrt{c+1}}$. Write $\sqrt{c}-\sqrt{c-1}=\frac{1}{\sqrt{c}+\sqrt{c-1}}$ and $\sqrt{c+1}-\sqrt{c}=\frac{1}{\sqrt{c}+\sqrt{c+1}}.$ Thus you have the result.
Answer: Consider $$B = \sqrt c - \sqrt{c-1},\quad D = \sqrt {c+1} - \sqrt{c}$$
By mean value theorem, there exist $$b\in (c-1, c),\quad d\in (c, c+1)$$ that satisfy
$$\frac1{2\sqrt b} = B,\quad \frac1{2\sqrt d} = D$$
and since $b\le d$, $$\begin{align*}
\dfrac1{2\sqrt b} &\ge \dfrac1{2\sqrt d}\\
\sqrt c - \sqrt{c-1} &\ge \sqrt {c+1} - \sqrt{c}
\end{align*}$$
Answer: Rewrite as: $$2\sqrt{ c} \geq \sqrt{ c + 1} +\sqrt{c-1}$$ and since both sides are nonegative it is equaivalent if we square it:
$$4c\geq c+1+2\sqrt{c^2-1}+c-1$$ or $$c\geq \sqrt{c^2-1}\iff c^2\geq c^2-1$$
which is true.


Granting permission for Windows service

Question: I am on yet another obstacle. I have a non-admin IIS identity account, to which I would like to grant permission to start, stop, restart, and read the status of one Windows Service. I followed the solution posted here. However, I would like to achieve this via PowerShell to automate, because I have so many servers. I was able to get SID of non-admin account, and get the output of command and save it under a variable. I converted to string, but cannot apply any functions such as StartsWith, split, insert, etc. Here is my code:
#Getting the SID for non-admin ISS identity account
$objUser = New-Object System.Security.Principal.NTAccount("non-admin")
$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$sid = $strSID.Value
#output retuned = S-1-5-21-2103278432-2794320136-1883075150-1000

#Storing the output of cmd prompt
$cmd = cmd.exe /c "sc sdshow <Service_Name>"
$test = $cmd | Out-String
#output returned = D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)

#Storing the value that needs to be inserted in $CMD
$str = "(A;;RPWPCR;;;$sid)"

I would like to insert $str just before "S:" in $test and I have been unsuccessful. I would like to achieve this by PowerShell and not SubInAcl. Any help would be appreciated. The final code should look like below:
sc sdset <SERVICE_NAME> "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)($str)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)"

Answer: Assuming that your $test variable contains D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD),  you could do:
$sid = "S-1-5-21-2103278432-2794320136-1883075150-1000"
$test = "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)"
$str = "(A;;RPWPCR;;;$sid)"

$newstring = $test -replace "S:","$($str)S:"

$newstring

returns:
D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;RPWPCR;;;S-1-5-21-2103278432-2794320136-1883075150-1000)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)

Comment: Thank you for the help @Cory Knutson. I had to replace `$str = "(A;;RPWPCR;;;$sid)S:"`  because `$str` should be after `S:`. However, I am trying to execute the command by passing in variable and I am getting errors in executing the final command.
Comment: **Update**:Thank you for the help @Cory Knutson. I had to replace `$str = "(A;;RPWPCR;;;$sid)S:"`  because `$str` should be after `S:`. However, I am trying to execute the command by passing in variable but this doesn't seem to grant permissions to the account. I am trying something like this `$arg="sc sdset  $newString"` and then `Powershell -command "Start-Process 'cmd' -Verb RunAS -ArgumentList '/c $arg' "`
Comment: What error do you get?
Comment: So, $args output is as follows `sc sdset ` and on new line `$newString` shows up. When this happens, CMD throws an error "[sc] Access is denied 5:".However, When I run the command manually in single line of code then the permissions were granted.
Comment: Are you running the Powershell console that you are trying this from as elevated for UAC?
Comment: I am a local admin on the Server and running it as same. Like I stated, I think the problem is that `$args` has two lines and this where it throws an error. I believe, if somehow, I am able to get `(sc sdset "$newString")` on one line of code instead of two then things would be more pleasant.Thanks
Comment: I don't understand how you are getting two lines. When I run the code I posted, it comes back with one line.
Comment: This is the output I am getting when I `echo $args`

`$args = "Sc sdset AppIDSvc `"$newString`" `

`Sc sdset AppIDSvc " \n
D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;RPWPCR;;;S-1-5-21-1985857054-386131273-3228901743-1010)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)
"`
I want it to be

`Sc sdset AppIDSvc "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;RPWPCR;;;S-1-5-21-1985857054-386131273-3228901743-1010)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)"`
Comment: \n is where I have blank spaces then followed by SDDL format
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/67591/discussion-between-cory-knutson-and-sid).
Comment: Thank you for your help @cory Knutson. I have marked this as an answer. I was able to fix it by changing this command `$test = [string]$cmd`

Granting permission for Windows service


Beginner Accordionist

Question: I am looking to begin learning the accordion. And I've narrowed my choices of first accordion based on research to two accordions that I can afford. They are both practically the same price, except, now it's between a 22 key accordion or a 31 key accordion. I'm curious if anybody can answer which is objectively better and if which one is easier to learn and master.
Comment: Welcome! Please read about [the topics covered here](https://music.stackexchange.com/help/on-topic) and [how to ensure objective answers](https://music.stackexchange.com/help/dont-ask). IMO this question ought to be valid, but it might attract close-votes since it's similar to questions like "What's the best model" (subjective) or "help me pick out my gear." I recommend editing to put more emphasis on the most answerable question, "which one is easier to learn and master." I doubt there's any way in which one is "better" except for that consideration.
Comment: I know very little about the accordion but this applies to any instrument. I highly recommend trying to find a local resource to help with your decision. If you plan on taking lessons (a good idea) speak with teachers in your area for advice on what type of instrument to buy. If there are no local resources reach out to a few dealers that specialize in accordions and ask them what would be a good choice within your budget and compare notes between them. This website seems to have some good general information to educate you: https://theaccordionshop.co.uk/advice/
Comment: As Andy said. Generally we want to avoid highly specific questions and rather have universal questions that may be useful for many people. So instead of asking "I've got a choice between these models, which is better?" I'd suggest you asking something like "I've got these choices, what things should I consider when buying a beginners instrument?". This way people with experience might give you information that is relevant to you which is currently not relevant to the question.
Answer: Assuming you are talking about a piano accordion, and the number of keys mentioned are on the treble side, the main difference is that you will have less range with the 22-key than the 31-key.  Both are smaller than a standard 41-key model.
What this means is that while trying to play some pieces, you might "run out of notes" at the top or bottom.
Also important to consider is whether the bass side has a full Stradella system  or if some chord buttons have been omitted.  You won't be able to learn to use the whole system if your instrument is incomplete.

Beginner Accordionist


If the median of $X$ is greater than the median of $Y$ then $\Bbb P(X>Y) \geq \frac14$

Question: The median value of a random variable $X$ is $m$ if $\Bbb P (X \geq m) \geq \frac12$ and $\Bbb P (X \leq m) \geq \frac12$. Let $X$ and $Y$ be independent real random variables. Show that if the median value of $X$ is larger than the median value of $Y$, then $\Bbb P(X>Y) \geq \frac14$.
Comment: With probability at least $1/2$, $X$ is $> m$ and with probability at least $1/2$, $Y$ is $\le m$. Conclude using independence.
Comment: @StiftungWarentest Try not to vandalise other people's work
Answer: Note $m_X$ and $m_Y$ the medians. One subset of the event $X>Y$ is $X>m_x>m_Y > Y$.
By independance, this event is the reunion of $Y<m_Y$ and $X>m_X$. Now we have, since $m_X>m_Y$:
$$P(X>m_x>m_Y>Y) = P(X>m_X) P(Y<m_Y). $$
Both of the terms equals $1/2$.
Then,
$$P(X>m_x>m_Y>Y) = 1/4.$$
Since $X>m_x>m_Y>Y$ is a subset of $X>Y$, you have the desire inequality.


Encontrar index de maior elemento da lista

Question: Estou montando um código que cria uma lista com 3 itens de compra, e dentro dessa lista algumas tuples com os nomes dos produtos e os respectivos preços. Eu quero encontrar o menor preço e exibir, junto com o nome do produto. Deve ser algum ajuste bobo, mas não consegui identificar como posso linkar o menor preço ao nome do produto correspondente. Podem ajudar?
    lista_de_compras = [
    (('Batata'), (float(input('Qual o preço da batata? R$ ')))),
    (('Cenoura'), (float(input('Qual o preço da cenoura? R$ ')))),
    (('Vagem'), (float(input('Qual o preço da vagem? R$ '))))
]

menor_valor_da_lista = min(lista_de_compras[0][1], lista_de_compras[1][1], lista_de_compras[2][1])

print(f'Você deve levar a **___** que custa R${menor_valor_da_lista}')

Answer: Escolha a estrutura de dados adequada
Você criou uma lista de tuplas, mas se a ideia é mapear cada produto com o seu respectivo preço, um dicionário me parece mais adequado.
Não só faz mais sentido para esse caso, como também facilitará muito a solução. Ficaria assim:
lista_de_compras = {}
for produto in ['batata', 'cenoura', 'vagem']:
    lista_de_compras[produto] = float(input(f'preço de {produto}, R$ '))

mais_barato = min(lista_de_compras, key=lista_de_compras.get)

print(f'Você deve levar {mais_barato} que custa R${lista_de_compras[mais_barato]:.2f}')

Para imprimir o preço, usei as opções de formatação, para imprimir sempre com duas casas decimais.
Ao usar min, eu indico que quero usar lista_de_compras.get, o que faz com que sejam comparados os preços em vez dos nomes. O resultado é o produto que tem o menor preço, e aí basta imprimi-lo.
Só que isso não resolve os casos de empate, quando mais de um produto for o mais barato. Nesse caso, bastaria percorrer o dicionário e imprimir todos que tem o mesmo preço:
mais_barato = min(lista_de_compras, key=lista_de_compras.get)

menor_preco = lista_de_compras[mais_barato]

print(f'produtos mais baratos, custam R${menor_preco:.2f}')
for produto, preco in lista_de_compras.items():
    if preco == menor_preco:
        print(produto)

A menos que você já receba a lista de tuplas daquela maneira, não há motivo para usá-la, pois um dicionário faz muito mais sentido para esse caso. A outra resposta até mostra que dá para resolver com a lista, mas fica desnecessariamente mais complicado, e tudo porque não é a estrutura de dados mais adequada para resolver o problema.
Escolher a estrutura de dados adequada é meio caminho andado para um código melhor.
Answer: Você pode utilizando a função map obter uma nova lista contendo os preços de cada produto. Basta passar no primeiro parâmetro uma função receba um item (tupla) e retorne o segundo elemento deste item (preço). Veja o código abaixo:
valores = list(map(lambda item: item[1], lista_de_compras))

Como você é iniciante e talvez o código acima ainda é um pouquinho avançado para você, aqui está um outro código que é equivalente, porém um pouquinho maior.
def obter_valores(lista):
    valores = []

    for item in lista:
        valores.append(item[1])

    return valores

Depois de ter obtido todos os valores precisamos saber qual o menor valor da lista certo? Para isso, podemos utilizar a função min que retorna o menor valor de um iterável.
min([5, 7, 8, 2, 9, 3, 4])  # Retorna o valor 2

Como o objetivo é obter o item por completo (tupla), podemos utilizar o método index da lista de valores para obter o índice do valor, índice este que será o mesmo do item na lista de compras.
indice_do_menor_valor = valores.index(min(valores))

Agora basta apenas obter o item através desse índice e pronto. Abaixo está o código completo:
valores = list(map(lambda item: item[1], lista_de_compras))
indice_do_menor_valor = valores.index(min(valores))

nome, valor = lista_de_compras[indice_do_menor_valor]
print(f'Você deve levar a {nome} que custa R${valor}')

Answer: Eu utilizaria um dicionário ao invés de uma tupla e deixaria o código assim:
lista_de_compras = {
    ('Batata'): (float(input('Qual o preço da batata? R$ '))),
    ('Cenoura'): (float(input('Qual o preço da cenoura? R$ '))),
    ('Vagem'): (float(input('Qual o preço da vagem? R$ ')))
}

menor_valor_da_lista = min(lista_de_compras, key=lista_de_compras.get)

print(f'Você deve levar a {menor_valor_da_lista} que custa R${lista_de_compras[menor_valor_da_lista]}')


Correlation coefficient of explanatory variables in D-optimal design

Question: In the D-optimal design of design of experiments, some books make the following claims.

The absolute value of the correlation coefficient becomes smaller

I understand that the covariance is minimized when there are two explanatory variables, that is, when the variance-covariance matrix is a 2 × 2 matrix.
On the other hand, is it obvious that "the absolute value of the correlation coefficient is minimized" when the explanatory variables are 3 or more?
Or is it possible to prove it mathematically?
Comment: From which book? Can you give more context, maybe a more complete quote?
Answer: Let us look at the problem of finding a D-optimal design for a linear regression problem with two predictors, so the model has the form
$$ Y_i = \beta_0 + \beta_1 x_{i1} +\beta_2 x_{i2} + \epsilon_i $$ where $i=1,2,\dotsc,n$,  and we have the usual assumptions of independence  and constant variance for the disturbance terms $\epsilon_i$.  Writing in  matrix form
$$ Y=\begin{pmatrix} 1 & x_{11} & x_{12} \\
                     1 & x_{21} & x_{22} \\
                      \ddots \\
                     1 & x_{n1} & x_{n2} \end{pmatrix} \beta + \epsilon $$ or more compactly $Y=X \beta +\epsilon$. Also write the three column vectors building the matrix $X$ as $1, x_1, x_2$.
Let us assume that $(x_{i1}, x_{i2})^T \in [-1,1]\times [-1,1]$, so the design space is a Cartesian product. This is not necessary, but is an often seen case. D-optimality consists in maximizing the determinant of $X^T X$. Write this out as
$$ X^T X = \begin{pmatrix}
n      & 1^T x_1 & 1^T x_2 \\
1^T x_1& x_1^T x_1& x_1^T x_2\\
1^T x_2& x_1^T x_2& x_2^T x_2\\ \end{pmatrix}
$$
Simple case where $x_1$ and $x_2$ are centered
Then $X^T X$ simplifies to
$$ X^T X = \begin{pmatrix}
n      & 0 & 0 \\
0 & x_1^T x_1& x_1^T x_2\\
0 & x_1^T x_2& x_2^T x_2\\ \end{pmatrix}
$$   Calculate its determinant by expanding along the first row:
$$ \vert X^T X \vert = n \cdot \left(x_1^T x_1 \cdot x_2^T x_2 - (x_1^T x_2)^2 \right) $$
It is clear that this is maximized by choosing $x_1$ and $x_2$ as orthogonal, and then maximizing the norm of each of them. The last is achieved by letting half of them bee equal to $+1$, the other half $-1$. Which is possible if $n$ is even. In this case, this explains why a D-optimal design tends to choose uncorrelated predictors, if the restrictions of the design permits that, or falting that, tends to minimize the correlation.
The general case
We will not try a direct attack on the determinant, but will utilize the Hadamard inequality or even more directly, its sibling the less known Fischer's inequality. Let us state the last (see the Wikipedia link for proofs).  Fisher's inequality gives an upper bound for the determinant of a positive semidefinite matrix in terms of the determinants of its principal diagonal blocks. Let
$$ M = \begin{pmatrix} A & B \\ B^T & C \end{pmatrix}
$$ then
$$ \vert M \vert \le \vert A\vert \cdot \vert C \vert $$
and if $M$ is positive definite then equality is achieved if and only if all the entries of $B$ are zero.
Apply this to our matrix $X^T X$, and identify the blocks as $A=n$ and so on. Again we see that to achieve the upper bound, we need the predictors centered, with correlation zero, and the norms of $x_1$ and $x_2$ maximized. Sometimes restrictions on our design problem will not permit this, but then any optimization algorithm will try to find a solution  approximating this ideal case, which explains the terminology tends to find solutions minimizing the correlation between the predictors.
To go deeper into this, the following paper might be useful: More subtle versions of the Hadamard inequality by Michał Różański, Roman Wituła  and Edyta Hetmaniok.
Comment: Thanks for the great answer. I clearly understand the general case by your answers.
Also, I would like to read the papers presented and deepen my understanding.


Are questions pertaining to investing in a specific country admissible?

Question: Suppose that I would like to invest in Ruritania. Suppose further that I am interested in learning about the risks involved — physical, sociological, regulatory, legal, etc — and that I do not trust most of the material available. Would it be admissible to post a question on Economics SE requesting authoritative references about the risks of investing in Ruritania?
Naively, to me, this falls under development-economics. However, since I do not know what the conventions and norms on Economics SE are, I figured it would be wise to ask here on Meta before posting my question.
Answer: If you really want to ask about the risks of investing in a country, try narrowing the question down to be relevant to this Stack. For example, you can ask about historical inflation rates and whether there are any sources on their movement, or you could ask about how central bank policy has influenced capital assets, or some other very specific question. When I say you would want to narrow down the question, I really do mean you would need to do a good job at making it more manageable.
When you ask about the "risks" of investing in a country, this is way too broad of a topic to just ask all at once. Are you interested in a specific industry? In the labor market? In creating a small business there? In major companies that are publicly traded in that country? Start from there and try to think of a very specific activity you are interested in. You are more likely to have a viable question to ask then.
Answer:
Questions about personal finance (e.g. managing/investing your money) belong to the Personal Finance and Money stack not economics stack (this is explained in our help center).

It is not development economics question. Development economics studies the transformation of emerging nations into more prosperous nations, the discipline has little to say about personal investment in developing countries.

You seem to want to ask multidisciplinary question. Such questions are often not well suited for SE format. You should consider splitting your question and asking about its separate parts in appropriate stack. For example, for legal questions you should use law stack exchange.
Comment: @RodrigodeAzevedo 1. I don't know why it was closed there but on this site personal finance is off topic. Sometimes question does not fit any SE. 2. I never said that knowing sociological and legal factors is not relevant. However, **SE is not very good place for multidisciplinary questions**. If you have multidisciplinary question you should break it into separate disciplines and ask them separately and then do a synthesis. 3. So? A developmental economics article can motivate non-developemental articles/question. For example, does microfinance help improve welfare of poor? is developemental
Comment: I asked on Money SE and it was closed.
Comment: How can one understand why a region is not more prosperous without understanding that region's sociological and legal environment?  How can one invest in a region without understanding that region's sociological and legal environment?  Obviously, I disagree with your 2nd point.  Interestingly, my question was motivated by a blog post written by a professor of economics at George Mason University on why a certain region he happened to be summering at was not more prosperous.
Comment: economics question. If the answer is yes some people will get *motivated* to set up microfinance companies in developing countries. How to set up microfinance company is question about business administration/entrepreneurship (separate disciplines). A run of a mill professor of developmental economics will have nearly zero knowledge of business administration/entrepreneurship and vice versa. There are some people who operate on boundary of two fields and publish in multidisciplinary journals, but SE does not have multidisciplinary stacks. If you dont want to break multidisciplinary question
Comment: down, try some other economics Q&A site or some forum. Stack Exchange is not a monopoly. Different sites have different formats, some are more strict about what can be posted on some sites anything goes.


Struts2 Action Regular Expression/Wild card for URL

Question: I am new to Struts2 but so far I have made decent progress using the API. However, I am stuck at something which I need to get out from. I am using Struts2 with Spring integration. I am writing my Action classes with annotation as like many of you I love annotations.
My requirement is that URLs will be in the following nature:
http://<DOMAIN>/program/program1.jspx
http://<DOMAIN>/program/program2.jspx
http://<DOMAIN>/program/program3.jspx

As you can see there is a certain pattern in the URL with program1, program2 and program3 varying and the rest are all static. I have very easily handled similar situation with Spring MVC (I don't have the option of using Spring MVC for the current project) like "/program/{program_name}.jspx" in my other project.
But when I use the same in struts2 I get the error. My Action class is as follows:
@Result(name="program", location="program", type="tiles")
public class ProgramAction extends ActionSupport {

   @Action("program/{programName}")
   public String getProgramPage() {
     // few more lines of code
     return "program";
  }
}

The error is
2013-02-28 15:46:35.591 WARN  [http-bio-8080-exec-3] CommonsLogger.java:60
Could not find action or result
com.opensymphony.xwork2.config.ConfigurationException: There is no Action mapped for namespace / and action name program1.
at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:189) ~[xwork-core-2.2.1.jar:2.2.1]
at org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61) ~[struts2-core-2.2.1.jar:2.2.1]
at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39) ~[struts2-core-2.2.1.jar:2.2.1]
at com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58) ~[xwork-core-2.2.1.jar:2.2.1]
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:475) ~[struts2-core-2.2.1.jar:2.2.1]
....
....

My struts.xml file is as follows:
<struts>
<constant name="struts.convention.default.parent.package" value="default"/>
<constant name="struts.action.extension" value="jspx" />
<constant name="struts.mapper.alwaysSelectFullNamespace" value="false" />
<constant name="struts.enable.DynamicMethodInvocation" value="true" />

<package name="default" extends="struts-default, json-default, rest-default" namespace="/">
    <result-types>
        <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult"/>
        <result-type name="json" class="org.apache.struts2.json.JSONResult"/>
    </result-types>
</package>
</struts>

Answer: You have a slash in your action name. struts by default does not like this to correct that add:
<constant name="struts.enable.SlashesInActionNames" value="true"/>

Comment: Thank you Quaternion!! Your answer helped me to resolve the issue. I really appreciate your help. Sorry if my question was too elementary.
Comment: No problem, it's an easy mistake. Look into the conventions plugin, if you haven't already.
Comment: Also if this helped resolve the issue, and the issue is now fully resolved. Make the answer as "accepted" the green check mark. Also please do this for any other resolved questions you might have, SO rewards you with 2 rep, each time you find your answer. Not a bad deal.
Answer: This is because you defined the action annotation on method. Try <s:a namespace="/" action="program/program1" method="programPage" /> in the JSP.
Comment: Hi Roman, the JSP comes into the picture only when the Action class completes and forwards the request to the JSP. So I am not sure whether I am following your intructions.
Comment: I know, you are not mastering JSP right? Put it into JSP and browse to it, then open page in the source view and look at the rendered HTML. Sure you can easily find link with the anchor tag. Look at the href attribute you'll see how should you call your action.
Comment: I did that in other JSP and I got the following . However when I call http:///program/program1!programPage.jspx I still get the same error!


Call to a member function label() on a non-object in entity module

Question: I created an entity type using Entity API and made it exportable. The export link works properly but on Import I have this error:

Fatal error: Call to a member function label() on a non-object in [...]\sites\all\modules\entity\entity.module on line 903

I couldn't find any reason.
Here's my hook_entity_info():
$return = array(
  'event' => array(
    'label' => t('Event'),
    'entity class' => 'EventClass',
    'controller class' => 'EventController',
    'base table' => 'calendar_events',
    'fieldable' => TRUE,
    'entity keys' => array(
      'id' => 'eid',
    ),
    'load hook' => 'events_load',
    'view modes' => array(
      'full' => array(
        'label' => t('Default'),
        'custom settings' => FALSE,
      ),
    ),
    'label callback' => 'entity_class_label',
    'uri callback' => 'entity_class_uri',
    'module' => 'events',
    'access callback' => 'event_access',
    'exportable' => TRUE,
    'admin ui' => array(
      'path' => 'admin/structure/events',
      'file' => 'events.admin.inc',
      'controller class' => 'EventsUIController',
    ),
  ),
);

Tell me if you need more information.
[EDIT]
I figured that the error has been occurred in entity_class_label($entity) in sites/all/modules/entity/entity.module:903. I printed the content of $entity and it seems it is NULL!
Why is it NULL?
Comment: To add to Clive's solution, you may have better luck posting in the Entity API issue queue instead for support on this. Issues with modules and themes are considered out of scope for this site.
Comment: You would get far with a `debug_backtrace` call
Comment: I was having this same problem, and debug_backtrace helped find the problem.  In my case, I changed the menu paths for my entity from contact/%id to news/contact/%id, but forgot to change the page arguments position from 1 to 2.
Answer: It looks like this is a bug in the Entity API module.
An issue with exactly the same error message was reported here to do with the Profile2 module (which uses Entity API pretty heavily).
The upshot of that post is that the problem is an Entity API bug, details of which you can see at: Load reference field when building contents.
As you can see from the above there are patches available to fix the problem. The most recent patch that passed testing was on the 16th November 2011.
When you look at the Entity API module's latest stable release you can see it's date sas the 10th November 2011. This means that the patch probably hasn't made it into the stable version yet, so won't have been fixed in your version of the module.
There are two things you can do:

Upgrade to the dev version of the Entity API module (of course the usual amount of caution should be taken and you probably won't want to do this for a live site).
Apply the patch to the entity.controller.inc file that seems to have solved the problem for other users.
Comment: Thanks for reply. I tried both ways but neither worked!
Comment: Neither worked for me as well.


Is there a layer in Caffe that can get an arbitrary sub block in a blob?

Question: Is there a layer in Caffe that can get an arbitrary sub block in a blob?
Comment: haha...frequently asking
Answer: AFAIK there is not a completely general slicing layer in caffe.
If you want to extract sub-blocks that are specific channels of a blob, you can use "Slice" layer.
Depending on your requirements, you might find "Crop" layer sufficient for your needs.
If you need more flexible access to sub-blocks, you might want to consider using a "Python" layer.

An example using "Crop" layer
As you pointed out "Crop" layer expects two "bottom"s but since the second one is only used for reference shape, you can produce it using "DummyData" layer.
Suppose you want to select x[:,:,3:20,5:40], this is a 17x35 crop
layer {
  name: "ref_shape_17x35"
  type: "DummyData"
  top: "ref_shape_17x35"
  dummy_data_param { shape { dim: 1 dim: 1 dim: 17 dim: 35 } }
}
layer {
   name: "crop_x"
   type: "Crop"
   bottom: "x"
   bottom: "ref_shape_17x35"
   top: "crop_x"
   crop_param {
     axis: 2  # do not crop the first two dimensions
     offset: 3
     offset: 5
   }
 }

I did not try it myself, but it should work (let me know if it doesn't).
Comment: But the crop layer must have two input, mustn't it?


Unable to update or select value from SQLite in android Application

Question: i'm working on android application and i'm using  Sqlite db and i created bunch of methods to add tables and insert and all of them are working correctly except of 2 methods
the first is Update methods the value of field to 1
public void UnlockNextLevel(String lvlname ,int num){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(SchemClass.LetsCode2.COLUMN_NAME_LEVELSTATUS,num);
    db.update(SchemClass.LetsCode2.SECOND_TABLE ,cv, SchemClass.LetsCode2.COLUMN_NAME_LevelName +" = "+lvlname,null );
}

and when i run it , it causes a run time exception
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.a96653.LetsCode, PID: 3392
    android.database.sqlite.SQLiteException: no such column: Ploto (code 1 SQLITE_ERROR): , while compiling: UPDATE LEVEL SET LevelStatus=? WHERE LevelName =  Ploto

The other method is select method from db :
public int returnQuestionAnswer (int Qnum){

    SQLiteDatabase db = this.getWritableDatabase();
   int lnum=100;
   String query = "SELECT "+SchemClass.LetsCode2.COLUMN_NAME_QANSWER +" FROM "+SchemClass.LetsCode2.TABLE_AUESTION +" WHERE "+SchemClass.LetsCode2.COLUMN_NAME_QNUM +" = "+Qnum;
   Cursor recordSet=db.rawQuery(query,null);
    recordSet.moveToFirst();

    while (!recordSet.isAfterLast()){
        lnum=recordSet.getInt(recordSet.getColumnIndex(SchemClass.LetsCode2.COLUMN_NAME_QANSWER));
    }
    db.close();

   return lnum;
}

When i want to display the integer value in textView it causes runtime exception
The last Exception i wasn't able to post it so i'll post it here:
java.lang.NullPointerException: Attempt to invoke virtual method
'java.io.File android.content.Context.getDatabasePath(java.lang.String)'
on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2843)

Comment: The last Exception i wasn't able to post it so i'll post it here java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2843)
Answer: Issue 1
The update is failing because the value to be compared is enclosed in quotes and is therefore considered as an identifier (column name in this case), rather than a literal value. To fix this use :-
db.update(SchemClass.LetsCode2.SECOND_TABLE ,cv, SchemClass.LetsCode2.COLUMN_NAME_LevelName +" = '"+lvlname + "'",null );

Or better still use :-
db.update(SchemClass.LetsCode2.SECOND_TABLE ,cv, SchemClass.LetsCode2.COLUMN_NAME_LevelName +"=?",new String[]{lvlname} );

using the ? placeholder in conjunction with an argument is considered better as it protects against SQL Injection and automatically encloses the value ensuring that it is treated as a literal rather than an identifier.

Issue 2
There is insufficient information to determine the second issue but in all likelihood the Context is null and that this is because you have something like
your_DBHelper = new DatabaseHelper(this);

in the activity's class definition, when you should be declaring the the DatabaseHelper object and then instantiating it in the onCreate method
e.g. something like
public class YourActivity extends AppCompatActivity {

    DatabaseHelper myDBHlpr;
    //DatabaseHelper myDBHlpr = new DatabaseHelper(this); <<<<<<<<<< NULL POINTER EXCEPTION

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myDBHlpr = new DatabaseHelper(this); //<<<<<<<<< instantiates the DatabaseHelper Object
    }
}

Note names of objects/activity would have to be changed according to your code.
You may not have AppCompActivity, this has been used for demonstration but the same principle applies.
Comment: I did these changes and i did not cause run time exception but the update method  it did not reflect in the database
Comment: Check the value returned by the **update** method if it's 1 or more then rows are being update, if not then there isn't a row with the value **Ploto** assuming that is the value that lvlname resolves to.
Comment: @AlbtoulAlmuhanna that's good, could you tick the answer if you believe that the answer helped you solve the problem.


TXT record for multiple email providers not working

Question: The main domain is configured with google account so we are using sub-domain: mail.fairwaytoursuae.com for sending mail via Mailgun. Everything is done as in the docs but still, one TXT record is showing the main domain record value.
In mailgun :

In the server:

Is there anything wrong in the records? Are they need to combine together?
Comment: Your TXT record is exactly what they specified it should be. Wait four hours and check again.
Comment: @MichaelHampton : it's worked after adding CNAME record(TXT records added befor two days)
Comment: @MadHatter : mailgun is not detecting the record added
Answer: I think I see what you're asking, but let me restate your problem, to be clear.  You currently have mail working happily from fairwaytoursuae.com via google, and you want to add a new bulk email system using mailgun.  You have been advised to set a new SPF record, and don't quite understand what's going on.
The missing datum is who you are sending mailgun mails from; that is, what fully-qualified domain name (FQDN) appears in the host portion of the envelope-From field.  I'm going to assume it's fairwaytoursuae.com, not mail.fairwaytoursuae.com.
The issue here is that mailgun has advised you to advertise an SPF record for mail.fairwaytoursuae.com, but their web system shows an SPF record already existing which is not for that FQDN.  Instead, their web system is showing you the current SPF record for the parent domain, fairwaytoursuae.com, even though the interface suggests this is not so.
I suspect what it actually wants is for you to publish a single, combined record for the parent domain.  Something like
fairwaytoursuae.com.   IN   TXT   v=spf1 +a +mx +ip4:18.104.22.168 include:_spf.google.com include:mailgun.org ~all

Even if my guess is right, there are several potential problems with such a record.  One is that you are likely to be getting perilously close to the limit of ten DNS lookups which represents the maximum the evaluation of an SPF record may require  (another is that it's completely useless, like all SPF records that don't end -all.)  SPF isn't really intended for people who have a highly-distributed email infrastructure, and in starting with gmail you've started with one of the biggest on the planet, and are trying to make it bigger.
Comment: @PranavCBalan yes, you may.
Comment: Thanks for the detailed answer... finally it's detected the TXT record after adding cname record for mailgun.
Comment: @PranavCBalan no worries, I'm glad things are working, and thanks for accepting an answer.  Do please consider `-all`; SPF really isn't any use without it.
Comment: Can I use different MX record for main domain and it's sub domain ? For eg : google provider for main.com and mailgun provider for mail.main.com


Laravel upload via FTP prevent overriding live logs

Question: I am updating my laravel project via FTP.
I set override all files, where edit date changed.
Problem:
It overrides the live logs with the dev logs, because the name of the log file is the same.
I wanted to change log names (could save it in .env, because live project has its own .env), but I have not found a way to do it.
Any other ideas?
Answer: Just exclude logs file/dir when copying files instead of overriding it?
Answer: Here is my solution.
Go to logging.php and edit this condig:
'single' => [
    'driver' => 'single',
    //'path' => storage_path('logs/laravel.log'),
    'path' => storage_path(env('LOG_PATH')),
    'level' => 'debug',
],

'daily' => [
    'driver' => 'daily',
    //'path' => storage_path('logs/laravel.log'),
    'path' => storage_path(env('LOG_PATH')),
    'level' => 'debug',
    'days' => 14,
]

Because the live project has a different .env, you can define a different folder or filename and it will work.


Fade In Main Activity

Question: I'm a complete newbie to Android. How can I fade in the main activity? Basically after I open the app I want the screen to be black and then fade in an image. I have been trying to do this for the last 2 hours and I can't seem to find a solution.
This is my code:
package com.example.radu.gladiators2;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

/**
 * Created by Radu on 8/8/2016.
*/

public class Splash extends AppCompatActivity {

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash_screen);
}

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    View decorView = getWindow().getDecorView();
    if (hasFocus) {
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);}
    }
}

And this is the XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/splash_image"
    android:id="@+id/imageView"
    android:scaleType="centerCrop" />

Comment: here's an example http://stackoverflow.com/questions/18475826/fade-in-animation-on-activity-transition
Comment: I tried to adapt it to my problem but it doesn't seem to work on a main activity.
Answer: Try this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layoutAnimation="@android.R.anim.fade_in" >

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/splash_image"
    android:id="@+id/imageView"
    android:scaleType="centerCrop" />

Fade In Main Activity


How to prove that $e^x$ is convex?

Question: I need a help with proving convexity  of $e^x$ function. $f(x)$ is a convex function, If it satisfies following condition.
$$f(c\cdot x_1+(1-c)\cdot x_2) ≤ c\cdot f(x_1)+(1-c)\cdot f(x_2), \quad    0 ≤ c ≤ 1$$
Comment: The second derivative of $e^x$ is $e^x$ which is greater than $0$ for all $x$
Comment: Or just the first derivative which is increasing.
Comment: Can this be proved just by using definitions and not using second derivatives
Answer: A continuously differentiable function $\mathrm{f}$ is convex on an interval $I$ if, and only if
$$\mathrm{f}(x) \ge \mathrm{f}(y)+\mathrm{f}'(y)\cdot(x-y)$$
for all $x,y \in I$. In your case $\mathrm{f}(x) = \mathrm{e}^x$ and $I = \mathbb{R}$. Hence, we need to show that
$$\mathrm{e}^x \ge \mathrm{e}^y + \mathrm{e}^y \cdot(x-y)$$
for all $x,y\in \mathbb{R}$. This inequality can be rearranged to give
$$\mathrm{e}^{x-y} \ge 1+x-y$$
This is equivalent to $\mathrm{e}^z \ge 1+z$ for all $z \in \mathbb{R}$. Since $\mathrm{e}^z > 0$ for all $z \in \mathbb{R}$ it is clear that $\mathrm{e}^z \ge 1+z$ for all $z \le -1$. It remains to prove that $\mathrm{e}^z \ge 1+z$ for all $z \ge -1$.
The Taylor Series of $\mathrm{e}^z$ is
$$\mathrm{e}^z = 1+z + \frac{z^2}{2!} + \frac{z^3}{3!} + \cdots$$
If $z > 0$ then all of the terms $\frac{z^k}{k!}$ are positive and hence
$$ \mathrm{e}^z = 1+z + \frac{z^2}{2!} + \frac{z^3}{3!} + \cdots \ge 1 + z$$
If $-1 \le z \le 0$ then $z^2+z^3 \ge 0$, $z^4 + z^5 \ge 0$ and, in fact, $z^{2k}+z^{2k+1} \ge 0$ for all positive integers $k$. It follows that $\frac{z^2}{2!}+\frac{z^3}{3!} \ge 0$, $\frac{z^4}{4!}+\frac{z^5}{5!} \ge 0$ and, in fact,
$$\frac{z^{2k}}{(2k)!} + \frac{z^{2k+1}}{(2k+1)!} \ge 0$$
Since the Taylor Series for $\mathrm{e}^z$ is absolutely convergent for all $-1 \le z \le 0$ (the exponential function converges on the entire complex plane, and power series converge absolutely within their radius of convergence) it follows that
$$ \mathrm{e}^z = 1+z + \frac{z^2}{2!} + \frac{z^3}{3!} + \cdots \ge 1+z$$
for all $-1 \le z \le 0$.
Comment: That's great and actually does not rely on derivative arguments: A function $f$ is convex if for every $x$ there exists $c$ such that for all $y$ it holds $f(y) \geq f(x) + c(y-x)$. You showed that $c=e^x$ works. This does not only show that $f$ is convex but also that $e^x$ is a subgradient of $\exp$ at $x$.)
Comment: @Dirk Thank you for your kind words :-)
Comment: Well done, although I would be a little more careful in the region $[-1,0]$.
Comment: @Arkamis You're right. I'm just trying to edit that now.
Comment: @Arkamis I think I've fixed it. Do you agree?
Comment: Looks good to me!
Answer: The second derivative describes where a function is concave or convex. $(e^x)'' > 0$ for all $x$ so $e^x$ is convex everywhere.
Answer: A function of real variable is convex on an interval if it has nonnegative second derivative on this interval. This is a simplification of the Hessian condition for convexity to the case  $\mathbb{R}\rightarrow \mathbb{R}$. The second derivative of $e^{x}$ is $e^{x}$, and this is of course nonnegative on the entire real line.

How to prove that $e^x$ is convex?


Bootstrap-treeview with Ajax ASP.NET Core

Question: Im using ASP.NET Core and trying to populate a bootstrap treeview from a ajax call. I can get the response from the server but the tree view doesnt create a tree on the view.
I have installed the package via npm and linked to the css and script. Here is the view:

function getTree() {

            $.ajax({
                type: 'GET',
                url: '/Home/GetTreeNodes',
                dataType: "json",
            })
                .done(function (response) {

                    $("#treeview").treeview({ data: response })
                    console.log(response);
                })
                .fail(function (response) {
                    console.log(response);
                });
        }

        getTree();

And here is the Json action in my controller:
 [HttpGet]
    public JsonResult GetTreeNodes(string query)
    {
        // Tree nodes from db
        List<TreeNodes> treeNodes;
        // Tree nodes view model
        List<TreeNodesViewModel> treeNodesViewModel;

        treeNodes = _context.TreeNodes.ToList();

        if (!string.IsNullOrWhiteSpace(query))
        {
            treeNodes = treeNodes.Where(q => q.Name.Contains(query)).ToList();
        }

        treeNodesViewModel = treeNodes.Where(l => l.ParentId == null)
                .Select(l => new TreeNodesViewModel
                {
                    Text = l.Name,
                    Id = l.Id,
                    ParentId = l.ParentId,
                    @Checked = l.Checked,
                    Children = GetChildren(treeNodes, l.Id)
                }).ToList();

        return Json(treeNodesViewModel);
    }

private List<TreeNodesViewModel> GetChildren(List<TreeNodes> nodes, int parentId)
    {
        return nodes.Where(l => l.ParentId == parentId).OrderBy(l => l.OrderNumber)
            .Select(l => new TreeNodesViewModel
            {
                Text = l.Name,
                Id = l.Id,
                ParentId = l.ParentId,
                @Checked = l.Checked,
                Children = GetChildren(nodes, l.Id)
            }).ToList();
    }

The only thing that shows up on the view is the root node:

Any help would be greatly appreciated, been searching the net for examples and help but not managed to find anything that descibes why im getting this problem.
Answer: Just in case somebody in the future stumbles across this i figured it out. My code was fine, i had to change the structure of the viewmodel with text first and also change the name of children to nodes then it worked fine.
On a side note, i have tried running this with bootstrap 4 alpha 6 and it doesn't show the checkboxes. So use it as stated on the site with bootstrap <= 3.


Inject Value into JPA-Table-Annotation

Question: I have an JPA Entity which I Would like to use for 2 Tables.
<code>@Entity
@Table(name="table_name_should_be_injected")
class MyEntity{
  // Implementation goes here
}
</code>
So I would like to inject the table name with Spring.
Is this possible?
Answer: Please don't pursue this line of design. It will add a completely unnecessary level of complexity to your solution, it goes against the JPA specification and intention and it will leave anyone else looking at your solution scratching their heads.
The proper way to accomplish this in JPA is with an abstract base-class and <code>@Inheritance(strategy=TABLE_PER_CLASS)</code> (see @Inheritance).

Inject Value into JPA-Table-Annotation


Adding a property in an array of objects in a separate array of objecs by id

Question: I have these two array, and I want to push the second array to its parent as an extra property by comparing the parent id to child parentsId, i've been spending hours to get my desired output, help would be very much appreciated
first array
const parent = [
      {
        id: 1,
        name: 'john',
        age: 32,
      },
      {
        id: 2,
        name: 'jane',
        age: 44,
      },
    ];

second array
const child = [
      {
        parentId: 1,
        name: 'mike',
        age: 5,
      },
      {
        parentId: 2,
        name: 'michelle',
        age: 6,
      },
      {
        parentId: 2,
        name: 'morgan',
        age: 7,
      },
    ];

This is the result that I wanted, so basically the child will be populated to its parent by using parentId
  const parent = [
      {
        id: 1,
        name: 'john',
        age: 32,
        children: [
          {
            parentId: 1,
            name: 'mike',
            age: 5,
          },
        ],
      },
      {
        id: 2,
        name: 'jane',
        age: 44,
        children: [
          {
            parentId: 2,
            name: 'michelle',
            age: 6,
          },
          {
            parentId: 2,
            name: 'morgan',
            age: 7,
          },
        ],
      },

Comment: You can try `child.reduce((p,c) => doSomethingWithPandC(p,c), parent)`
Comment: @Redu my javascript is not that great, im sorry
Answer: You can use a combination of .map(), .filter() and spread syntax:

const parent = [{ id: 1, name: "john", age: 32 }, { id: 2, name: "jane", age: 44}];
const child = [{ parentId: 1, name: "mike", age: 5}, { parentId: 2, name: "michelle", age:6}, { parentId: 2, name: "morgan", age: 7}];

const result = parent.map(person => ({
  ...person,
  children: child.filter(({ parentId }) => parentId === person.id)
}));

console.log(result);

EDIT: I'm not sure exactly why your question was closed. I wouldn't say that it lacks 'focus'. Perhaps it's because you didn't provide info about how you tried to solve the problem, or what errors you ran into. Next time, please provide more information.
Comment: awesome! appreciated!


Sending E-mails

Question: I am trying to send e-mails with VB.net and I have a template for the code but I don't understand a few lines.
SmtpServer.Credentials = New Net.NetworkCredential("email@example.com", "password")
mail.From = New MailAddress("firstname.lastname@example.com")
mail.To.Add("TOADDRESS")

As far as I understand, mail.From is the sender's name, and mail.to.add is the person I am sending to. What does smtpServer.Credentials do?
I deduce that SmtpServer.Credentials is the only one that requires a password so that will be the account the e-mail will be sent from. But then what is the point of mail.From? What happens if I put different e-mails in credentials and mail.From.
Thanks for the help in advance!
Answer: SmtpServer.Credentials must be used only if your provider needs authentication to send email.
You can read it here

Some SMTP servers require that the client be authenticated before the
  server will send e-mail on its behalf. To use your default network
  credentials, you can set the UseDefaultCredentials to true instead of
  setting this property. If the UseDefaultCredentials property is set to
  false, then the value set in the Credentials property will be used for
  the credentials when connecting to the server. If the
  UseDefaultCredentials property is set to false and the Credentials
  property has not been set, then mail is sent to the server
  anonymously.

From is used by receiving client as the address to send replies to.
Comment: So if I authenticate the credentials using my E-mail address and password. But then in mail.From write email@example.com, what is stopping me from spoofing Bill's e-mail?
Comment: @PejmanPoh: Nothing if receiving client has not something that warns user. Remember anyway that when you receive an email you can check headers: in this case you see that email is sent from your real account and not from Bill Gates one!!
Answer: mail.From is used for display purpose. When the receive hit Reply it will add mail.From in the display name and SmtpServer.Credentials in the email address. You can alternatively also set the Reply-To address.
Answer: Yes...SmtpServer.Credentials will take the login credentials that it sends the email from that id-password...but it also provides the feature that you can add any email id in mail.From so that will be shown in the From part (Display purpose) of the mailbox. so it only shows that id in From part but the actual mail comes from the one you define in credentials.
I think this will be helpful to you..!!

Sending E-mails


Tags do JSF2 não funciona dentro de uma tag do Bootstrap

Question: Criei um projeto Java Web que está usando JSF2 + Bootstrap, tanto o arquivo CSS quanto o Bootstrap estão corretamente configurados no meu projeto, e em projeto anteriores Web Java sempre era responsável pela parte de Back-End, somente agora estou começando a aprender a parte de Frond-End, e estou tendo uma dificuldade que tem me acompanhado já faz 3 semanas.
Toda tag de JSF que fica fora das tags do Bootstrap funciona normalmente utilizando o link do arquivo CSS, porém quando eu coloco uma tag do JSF dentro de uma tag do Bootstrap ele passa a não funcionar, as tags de JSF somente funcionam quando eu aplico as configuração do CSS direto na pagina XHTML, e isso não é uma boa prática de desenvolvimento Frond-End como vê abaixo;
Modelo que está funcionando:
<h:graphicImage library="images" name="carolina.jpg" style="margin-left: 50px;"/>

O que eu preciso é saber porque isso acontece,  as configurações deveriam ser essas abaixo, sendo que elas não funcionam.  será que estou criando os códigos de forma errada na pagina?
Isso é na pagina:
<h:graphicImage library="images" name="carolina.jpg" styleClass="foto_carolina"/>

Isso está no arquivo CSS:
@CHARSET "UTF-8";

.foto_carolina{
        margin-left: 50px;
}

Eu até tentei desta forma, sendo que também não funcionou:

Essá é minha pagina completa:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <h:outputStylesheet library="css" name="bootstrap-theme.css" />
    <h:outputStylesheet library="css" name="bootstrap.css" />
    <h:outputStylesheet library="css" name="sistema.css" />

    <h:outputScript library="js" name="jquery-2.1.4.min.js" />
    <h:outputScript library="js" name="bootstrap.js" />

</h:head>

<h:body>

                    <h:graphicImage library="images" name="logotipoK.png" />

Inicio

O PLano

Loja Virtual

Contato

                    <h:graphicImage library="images" name="legumes.png" />

                    <h:graphicImage library="images" name="plano_carolina.png"
                    style="margin-left: 50px;" />
                    <h:graphicImage library="images" name="carolina.jpg" styleClass="foto_carolina/>

</h:body>

Aceito sugestões.
Se por acaso ficar a postagem não ficou muito clara, por favor me façam pergunta para eu poder esclarecer as duvidas pra que assim vocês possam me ajuda.
Estou a toda disposição, e aguardando ansiosamente ajuda.
Comment: A tag de imagem não exibe a imagem ou o estilo não é aplicado?
Se apresentar alguma mensagem de erro no console ou na tela printa ela.
Comment: respondendo sua pergunta, não é aplicado, e outra, não apresenta mensagem de erro.
Answer: Na verdade o problema é que preciso estudar mais como funcionar a estrutura do BooTstrap, eu vou colocar a resposta, mas quem me deu o resultado da resposta foi um companheiro da comunidade do FaceBook do AlgaWorks chamado Maike Meneguetti.

                    <h:graphicImage library="images" name="plano_carolina.png" styleClass="img-responsive"/>

                    <h:graphicImage library="images" name="carolina.jpg" styleClass="foto-carolina img-responsive img-rounded"/>

É o arquivo CSS ficou assim;
@CHARSET "UTF-8";

body {
    width: 80%;
    margin: 0 auto;
    padding-top: 40px;
}

.foto-carolina{
        max-width: 60%;
}

Coloquei a resposta porque acredito que tenham outras pessoas com duvidas, e gostaria que o pessoal da comunidade do fórum não fiquem chateados comigo pelo fato de ter colocado o mérito para a comunidade do AlgaWorks do FaceBook, porque além do mais passou 4 dias e ninguém teve a disponibilidade de pelo manos tentar me ajudar.
Comment: Por favor, marque a sua resposta com *certa* se isso realmente resolve o problema.
Comment: você deveria saber que eu mesmo não posso marcar minha resposta como certa, o sistema do fórum não permite.
Comment: Pelo contrário. Tente clicar ao lado da sua pergunta, abaixo dos votos. Mova o mouse e deve aparecer um check verde. Caso não consiga, peça ajuda no chat ou aqui mesmo. Eu mesmo já fiz isso.
Answer: esta faltando umas " para fechar
    styleClass="foto_carolina"/>

Comment: O problema não é esse.


how to put item cheked in a listview?

Question: I have a listview , i would like to put some position preselected; in fact i have some values that i would like to put them selected. this is my code
for (int i = 0; i < checked.size(); i++) {
                // Item position in adapter
                int position = checked.keyAt(i);
                // Add sport if it is checked i.e.) == TRUE!
                if (checked.valueAt(i)) {
                    selectedItems.add(adapter.getItem(position));
                }
            }

            String[] outputStrArr = new String[selectedItems.size()];

            for (int i = 0; i < selectedItems.size(); i++) {
                outputStrArr[i] = selectedItems.get(i);
            }

My selectedItems  firstly is not empty; i would like to put its value as selected.
Answer: Pass your selectedItem list to your custom adapter and inside getView() method compare position. If it is available in seloectedItem list change the background of view.
Answer: Use a custom adapter and pass the list inside there and render it on getView() by inflating the item.xml layout and use a static class viewHolder to create a viewholder that transfers the data from your list into the appropriate widgets.
Make sure you check if the convertView has been created previously as you do not want to create the view every time android hits getView from your adapter as it will slow your listView UI.
Good luck

how to put item cheked in a listview?


Projecting a new entry onto the two largest eigenvectors of a PCA model

Question: I have a bit of problems understanding how PCA and SVD works, as most materials focus on calculating the factors rather than the classification of new entries. In order to provide some context of my questions, let us first consider the following model:
I have some data set $X$ with $p$ features and $n$ rows (i.e. observations). Now suppose I use the first two factors $f_{1}$ and $f_{2}$ to create the following model $y=\beta_{0}+\beta_{1}\cdot f_{1} + \beta_{2}\cdot f_{2}$. Now suppose I get the following row vector $r^{*}$. How can I project $r^{*}$ onto $f_{1}$ and $f_{2}$?
A second question, as far as my understanding goes if we do SVD on matrix $X$ we get: $X=U\Sigma V^{*}$, but which are actually the eigenvectors? And are those eigenvectors the same as what I got with $f_{1}$?
Thank you for helping me understanding.
Answer: The model you define is somewhat inaccurate unless $y$ is of dimensions $p \times 1$. Is it?
Having said that assuming the eigenvectors $[f_1 f_2]$ define a $p \times 2$ matrix you simply do the multiplication: $[f_1 f_2]^T r^*$ to get the new scores. This is equivalent of projecting $r^*$ to the axial system defined by $f_1$ and $f_2$.
Both $U$ and $V^*$ are unitary matrices. If the matrix $X$ was symmetric $U$ would equal $V^*$. If you want the eigenvectors that are the same as the ones returned by PCA you are looking to use $V^*$.
Please see the post by the user @amoeba found here regarding the relation between SVD and PCA. I believe it will aid your understanding a lot.


Question about asymptotic notation with logs of different bases

Question: For the two functions f(n) and g(n), where $f(n) = n^{1/2}$ and $g(n) = 2^{(\log_2 n)^{1/2}}$, I am trying to determine whether $f$ is asymptotically bound below by $g$, i.e find whether there exists an N1 and a k1 > 0 such that:
$ f(n) >= k1 * g(n)$, for all n >= N1.
By taking the log of both $f(n)$ and $g(n)$ I got:
$f(n) = n^{1/2} = logn^{1/2} = 1/2*logn$.
$g(n) = 2^{(\log_2 n)^{1/2}} = log(2^{(\log_2 n)^{1/2}}) = (\log_2 n)^{1/2}log2$.
In trying to solve this I have:
$1/2logn >= k1 * (\log_2 n)^{1/2}log2$
Setting k1 to 1/2:
$1/2logn >= 1/2 * (\log_2 n)^{1/2}log2$
Dividing both sides by 1/2:
$logn >= (\log_2 n)^{1/2}log2$
Subtracting $(\log_2 n)^{1/2}log2$ from both sides:
$logn - (\log_2 n)^{1/2}log2 >= 0$
I can probably figure out whether there is any N1 such that the above is true for all n >= N1 by substituting values. However, I was wondering if there is any way to further simplify the above expression. In particular is there any way to get rid of the $(\log_2 n)^{1/2}$ entirely? I would prefer all the logs in the inequality to have the same base. Any insights are appreciated.
Comment: In my answer that you've accepted, I made a mistake which I've now corrected. In particular, I used $\log(ab) = \log(a) \log(b)$, which is what you've used as well, instead of the correct $\log(ab) = \log(a) + \log(b)$, when you take logarithms of both sides of the original inequality. I'm sorry for my mistake, but as you can see it does't change the overall result.
Answer: You could finish your work using $\log$, I assume to base $e$ but, in answer to your request of

I would prefer all the logs in the inequality to have the same base.

since $g(n)$ uses a base of $2$ and has a $\log$ to the base of $2$ in the exponent, it would likely be simplest & easiest to instead take the logs of both sides to base $2$ so you're then comparing the exponents of $f(n)$ and $g(n)$ to that base. As such, this would change trying to prove that there exists an $N_1$ and a $k_1 \gt 0$ such that
$$f(n) \ge k_1 \, g(n) \; \forall \; n \ge N_1 \tag{1}\label{eq1}$$
to finding, by taking $\log_2$ of both sides, a $k_2 = \log_2{k_1}$ such that
$$\log_2{f(n)} \ge k_2 + \log_2{g(n)} \; \forall \; n \ge N_1 \tag{2}\label{eq2}$$
Note that
$$\log_2{f(n)} = \log_2{n^{\frac{1}{2}}} = \frac{1}{2} \, log_2 n \tag{3}\label{eq3}$$
$$\log_2{g(n)} = \log_2{2^{(\log_2 n)^{\frac{1}{2}}}} = (\log_2 n)^{\frac{1}{2}} \tag{4}\label{eq4}$$
Substituting \eqref{eq3} and \eqref{eq4} into \eqref{eq2} gives
$$\frac{1}{2} \, \log_2 n \ge k_2 + (\log_2 n)^{\frac{1}{2}} \; \forall \; n \ge N_1 \tag{5}\label{eq5}$$
In this case, consider values of $m$ where $\frac{1}{2}m^2 \ge m$. Multiplying both sides by $2$, moving $2m$ to the LHS and factoring gives $m\left(m - 2\right) \ge 0$. This is true for all $m \ge 2$. In this case, if we let $m = (\log_2 n)^{\frac{1}{2}}$, we can see that having $k_2 = 0$ and since $(\log_2 16)^{\frac{1}{2}} = 2$, we can use $N_1 = 16$. I believe you should be able to finish the rest.
Note if you had used your original idea of, I assume, the natural logarithm, it would just involve an extra factor by the change of logarithm base formula, i.e., $\log_a{x} = \cfrac{\log_b{x}}{\log_b{a}}$ to give in this case that $\log_2{n} = \cfrac{\log_e{n}}{\log_e{2}}$. Also, as I show, you would need to add the constant, not multiply by it. After that correction, this just results in an extra factor being used for $\log_2{n}$, plus you also have the $\log_e{2}$ factor, so it might change the $k_2$ constant you determine to use (but not necessarily the $k_1$ constant) and/or the value of $N_1$, as these values are not uniquely determined.


getting error on facebook catalog batch api on using app token

Question: api works for user token but does not when i put app token
https://graph.facebook.com/v9.0/<my-catalog-id>/batch?access_token=<my-app-token>&requests=[{"method": "UPDATE","retailer_id": "retailer-id","data":{"availability": "in stock", "price": "10", "currency": "USD"}}]
{
    "error": {
        "message": "Unsupported post request. Object with ID '********' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api",
        "type": "GraphMethodException",
        "code": 100,
        "error_subcode": 33
    }
}

Answer: If the id in ****** is your catalog id then your app must be missing permission. To access catalog, your app should have catalog_management and ads_management permissions. For better understanding you can refer this url. This document has example of real estate listings.
Comment: There does not seem to be an URL or link in your post.
Answer: If the id in ****** is your catalog id then your app must be missing permission. To access catalog, your app should have catalog_management and ads_management permissions. For better understanding you can refer this url. This document has example of real estate listings.


How to display Vue-Dropzone response on browser?

Question: I need to render vue-dropzone response to my users. How do i do that?
The file uploads well, i only need to show to notify the user it is uploaded via an alert box or message.
<template>

                <vue-dropzone ref="myVueDropzone" id="dropzone" :options="dropzoneOptions" vdropzone-success=""></vue-dropzone>

</template>

Comment: From what I see in the docs you can hook onto the `vdropzone-success` event or the `vdropzone-success-multiple` event.
Answer: You can add a listener handler to listen the vdropzone-success event of vue-dropzone component.
This code should be working.
<vue-dropzone ref="myVueDropzone" id="dropzone" :options="dropzoneOptions"
    v-on:vdropzone-success="uploadSuccess"></vue-dropzone>

methods: {
   uploadSuccess: function(file, response) {
      your_function(file, response);
   }
}

Hope this helps to you.


angularjs correct row is not being deleted from table

Question: I have been struggling with a couple of issue so I thought I would reach out for help after doing much searching. I'm using AngularJS.

My first problem is that checkbox is not working properly when I use ng-repeat, it will only check the first box in the table code snippet below. I'm using a custom checkbox which I coded with css is the reason for the label.
My second issue is when I click on the check box it should delete any row I want but it deletes the row before it if I start from the bottom of the table up, but if I start from the top of the table down it works as expected except for the box being checked code snippet.  I tried many ways to set the index but it still does not work.

$scope.removeRow = function(type) {
var index = -1;
var myArr = eval( $scope.contacts );
    for( var i = 0; i < myArr.length; i++ ) {
       if( myArr[i].type === type ) {
           index = i;
           break;
             }
      {
if( index === -1 ) {
        alert( "Something gone wrong" );
      }

    $scope.contacts.splice(index, 1);
};

Comment: You have a break in the for loop when it matches, so it will stop after it hits the first match. That's most likely why it's only checking the first box in the table
Answer: First off, don't use eval($scope.contacts).  If that variable is a string and contains javascript it will run that javascript. if myArr isn't defined using myArr = $scope.contacts you can use myArr = JSON.parse(JSON.stringify($scope.contacts) or use angular.copy method.
I don't see your html, so I can't tell you why your checkbox doesn't work.  But regarding your second problem, if it's deleting a row above when you hit splice, why not change that code to :
$scope.contacts.splice(index + 1, 1)


MinGW GCC in Windows 7 x64 does not create an executable

Question: I'm having a similar, or possibly the same issue as a few others I have seen, but I am not sure. I am using mingw's copy of gcc directly from the windows command prompt on files in my personal directory, and I have edited the PATH to include C:\MinGW\bin
The following:
gcc -o print print.c

Grants me no output file, or so I thought.
I opened up a file browser and sat there while gcc ran, and saw the file appear, and shortly after gcc finished, disappear. I receive no error.
Just running
gcc print.c

yields nothing as well as
mingw32-gcc print.c

Here is my PATH (Cleaned up to fit my screen better):
C:\Program Files (x86)\AMD APP\bin\x86_64;C:\Program Files (x86)\AMD APP\bin\x86;
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;
C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;
C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\WindowsPowerShell\v1.0\;
C:\Program Files\Broadcom\Broadcom802.11;C:\Program Files\Broadcom\Broadcom 802.11\Driver;
C:\Program Files (x86)\QuickTime\QTSystem\;C:\MinGW\bin

This happens with multiple source files, but here is the source of the one I am working on in case you think that might be the issue:
#include <stdio.h>
int main(void) {
    for (;;) {
        int i;
        i = 0;
        int num;

        printf("Please enter a number:\n");
        scanf("%d", &num);
        printf("\n");

        if (num <= 0) {
            return 0;
        }

        while (i <= num) {
            printf("%d\n", i);
            i++;
        }
    }
}

Yes, I know it is really simple, I am just getting started on learning C.
Any ideas?
I'm downloading Code::Blocks right now, and will update if I find out that it works correctly there.
Edit:
Requested output ahead
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=c:/mingw/bin/../libexec/gcc/mingw32/4.8.1/lto-wrapper.exe
Target: mingw32
Configured with: ../gcc-4.8.1/configure --prefix=/mingw --host=mingw32 --build=m
ingw32 --without-pic --enable-shared --enable-static --with-gnu-ld --enable-lto
--enable-libssp --disable-multilib --enable-languages=c,c++,fortran,objc,obj-c++
,ada --disable-sjlj-exceptions --with-dwarf2 --disable-win32-registry --enable-l
ibstdcxx-debug --enable-version-specific-runtime-libs --with-gmp=/usr/src/pkg/gm
p-5.1.2-1-mingw32-src/bld --with-mpc=/usr/src/pkg/mpc-1.0.1-1-mingw32-src/bld --
with-mpfr= --with-system-zlib --with-gnu-as --enable-decimal-float=yes --enable-
libgomp --enable-threads --with-libiconv-prefix=/mingw32 --with-libintl-prefix=/
mingw --disable-bootstrap LDFLAGS=-s CFLAGS=-D_USE_32BIT_TIME_T
Thread model: win32
gcc version 4.8.1 (GCC)
COLLECT_GCC_OPTIONS='-v' '-mtune=generic' '-march=pentiumpro'
 c:/mingw/bin/../libexec/gcc/mingw32/4.8.1/cc1.exe -quiet -v -iprefix c:\mingw\b
in\../lib/gcc/mingw32/4.8.1/ print.c -quiet -dumpbase print.c -mtune=generic -ma
rch=pentiumpro -auxbase print -version -o C:\Users\kyle\AppData\Local\Temp\ccBlz
Ym1.s
GNU C (GCC) version 4.8.1 (mingw32)
        compiled by GNU C version 4.8.1, GMP version 5.1.2, MPFR version 3.1.2,
MPC version 1.0.1
GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
ignoring duplicate directory "c:/mingw/lib/gcc/../../lib/gcc/mingw32/4.8.1/inclu
de"
ignoring duplicate directory "c:/mingw/lib/gcc/../../lib/gcc/mingw32/4.8.1/../..
/../../include"
ignoring duplicate directory "/mingw/include"
ignoring duplicate directory "c:/mingw/lib/gcc/../../lib/gcc/mingw32/4.8.1/inclu
de-fixed"
ignoring duplicate directory "c:/mingw/lib/gcc/../../lib/gcc/mingw32/4.8.1/../..
/../../mingw32/include"
ignoring duplicate directory "/mingw/include"
#include "..." search starts here:
#include <...> search starts here:
 c:\mingw\bin\../lib/gcc/mingw32/4.8.1/include
 c:\mingw\bin\../lib/gcc/mingw32/4.8.1/../../../../include
 c:\mingw\bin\../lib/gcc/mingw32/4.8.1/include-fixed
 c:\mingw\bin\../lib/gcc/mingw32/4.8.1/../../../../mingw32/include
End of search list.
GNU C (GCC) version 4.8.1 (mingw32)
        compiled by GNU C version 4.8.1, GMP version 5.1.2, MPFR version 3.1.2,
MPC version 1.0.1
GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
Compiler executable checksum: 767202a405449496e68a54c4eee91a28
COLLECT_GCC_OPTIONS='-v' '-mtune=generic' '-march=pentiumpro'
 c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/as.exe -v -o C:\U
sers\kyle\AppData\Local\Temp\cc3cEZAy.o C:\Users\kyle\AppData\Local\Temp\ccBlzYm
1.s
GNU assembler version 2.24 (mingw32) using BFD version (GNU Binutils) 2.24
COMPILER_PATH=c:/mingw/bin/../libexec/gcc/mingw32/4.8.1/;c:/mingw/bin/../libexec
/gcc/;c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/
LIBRARY_PATH=c:/mingw/bin/../lib/gcc/mingw32/4.8.1/;c:/mingw/bin/../lib/gcc/;c:/
mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/lib/;c:/mingw/bin/../lib/
gcc/mingw32/4.8.1/../../../
COLLECT_GCC_OPTIONS='-v' '-mtune=generic' '-march=pentiumpro'
 c:/mingw/bin/../libexec/gcc/mingw32/4.8.1/collect2.exe -Bdynamic c:/mingw/bin/.
./lib/gcc/mingw32/4.8.1/../../../../mingw32/lib/crt2.o c:/mingw/bin/../lib/gcc/m
ingw32/4.8.1/crtbegin.o -Lc:/mingw/bin/../lib/gcc/mingw32/4.8.1 -Lc:/mingw/bin/.
./lib/gcc -Lc:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/lib -Lc:/m
ingw/bin/../lib/gcc/mingw32/4.8.1/../../.. C:\Users\kyle\AppData\Local\Temp\cc3c
EZAy.o -lmingw32 -lgcc -lgcc_eh -lmoldname -lmingwex -lmsvcrt -ladvapi32 -lshell
32 -luser32 -lkernel32 -lmingw32 -lgcc -lgcc_eh -lmoldname -lmingwex -lmsvcrt c:
/mingw/bin/../lib/gcc/mingw32/4.8.1/crtend.o

Edit:
I get the same issue in Code::Blocks.
Comment: The output looks normal. Could a virus scanner on your machine have deleted the executable?
Comment: Run `gcc -v print.c` and copy the output in your question.
Answer: I had similar issue where no output files were created.
The following packages were installed at the time : mingw-developer-toolkit, mingw32-gcc-g++, msys-base
To resolve the problem, i installed mingw32-base
Answer: Your first command gcc -o print print.c creates an executable named print, not print.exe. Use gcc -o print.exe print.c to get an executable that you can run easily from the command prompt.
The second and third commands produces an executable named a.exe. You can type a on the command prompt to run this executable.
Comment: Unfortunately, no. a.exe is never created in the other two, and I should get an executable named print in the first example, that I can rename print.exe, but I do not. Thank you, though.
Answer: I hit the same problem but with MinGW-64. The solution was to start mingw64.exe shell and to run compilation process there, but not in msys2.exe shell.


Running another program in console

Question: Is it possible to run another console application in running console. Lets say I got program that write hello world, i got her as exe file. Now I am running another program, can i run the other one in the second one? i want to run the hello world in the second program, its like running a process but in this console.
I want to run the code and then continue the program that called it.
Is it possible some how?
I didn't find the answer anywhere... My idea is to write scripts and shell for them which will run them. If you got another idea i would like to hear it to.
I want it in C# so cygwin or any other shell (which is not c#) won't help me.
Comment: @I4V as far as I understand OP is asking to run another process but in same console
Answer: You should use System.Diagnostics.Proces class to run the secondary process More details here
Comment: Correct me if im wrong but this open the other process in another console. Can i open it in the console that is already open?
Answer: What do you mean by same console? you want to run a program and get the result,
If you don't want it to run in the background, the use:
<code>Process p = Process.Start("exe fullname");
p.WaitForExit();
if (p.ExitCode == 0)
{
    //everything is good
}
else
{
    //the program wasn't successful
}
</code>
If however, you want it in the background, then you need to use a
Task.
Here is a complete article regading tasks
Note: If it's another Console application, and you want to use the result, then use ProcessStartInfo

Running another program in console


How to test output/input in java

Question: I am aware that this might be a duplicate (forgive me if that is the case), any one of these two could be a duplicate to what I'm searching for, but as I have no idea if they do answer my problem I'll ask it here anyway.
JUnit test for console input and output,
JUnit test for System.out.println()
My assignment (school):
We're to write a simple compiler that tracks the colour of a pencil and movement across the x- and y-axis. i.e.
Input:

% This is a comment
  % Now we're making a square
  DOWN.
  FORW 1. LEFT 90.
  FORW 1. LEFT 90.
  FORW 1. LEFT 90.
  FORW 1. LEFT 90.

Output:

#0000FF 0.0000 0.0000 1.0000 0.0000
  #0000FF 1.0000 0.0000 1.0000 1.0000
  #0000FF 1.0000 1.0000 0.0000 1.0000
  #0000FF 0.0000 1.0000 0.0000 0.0000

My problem:
To get a passing grade our code is subjected to a rigorous series of tests, many of these give you no clue as to what went wrong. i.e.

"A random generated program on 1215 bytes, with 1 syntax error"

So I feel that a great part of this assignment is to learn how to write good test-code, I've been thinking about trying to use JUnit (or perhaps I should use something else?). My input comes from System.in and the output goes through System.out.println().
Hopefully there is a way to do this by using existing textfiles (went through some difficulties earlier with assertEquals and super long strings full of \n). To clarify: I want to test I/O (through text-files) of my Java-program and I can't find any good clear explanation on how I can do this.
Answer: The most important part writing unit tests is separating the code you want to test from boilerplate/well-tested code out of given frameworks - so you might create classes which create the output but separate the part of reading the input from System.in and writing it to System.out from your business logic to concentrate on the "serious" parts.
Answer: I came against this problem when refactoring some legacy code recently. I extracted input/output into new classes and made them dependency of my program. Using dependency injection I inserted mocks/fakes so I could define what will be the input and what the output should be.
public class InputReader {

    private static final Scanner SCANNER = new Scanner(System.in);

    public String nextLine() {
        return SCANNER.nextLine();
    }

}

public class OutputPrinter {

    public void println(String string) {
        System.out.println(string);
    }

}

And then the test using mockito:
public class MainProgramTest {

    private final InputReader inputReader = mock(InputReader.class);
    private final OutputPrinter outputPrinter = mock(OutputPrinter.class);

    @Test
    public void playsSimpleGame() {
        when(inputReader.nextLine())
                .thenReturn("hello")
                .thenReturn("help")
                .thenReturn("exit");

        MainProgram mainProgram = new MainProgram(inputReader, outputPrinter);
        mainProgram.run();

        InOrder inOrder = inOrder(inputReader, outputPrinter);
        inOrder.verify(inputReader).nextLine(); // -> "hello"
        inOrder.verify(outputPrinter).println("\"hello\" is not recognised command, type \"help\" for known commands");
        inOrder.verify(inputReader).nextLine(); // -> "help"
        inOrder.verify(outputPrinter).println("This is help, the only known commands are \"help\" and \"exit\"");
        inOrder.verify(inputReader).nextLine(); // -> "exit"
        inOrder.verify(outputPrinter).println("Goodbye");
        verifyNoMoreInteractions(inputReader, outputPrinter);
    }

}

How to test output/input in java


Find the equation of the line tangent to the curve of the function $e^{x^2}$ in the point with coordinates $x=1$,$y=e$.

Question: Find  the equation of the line tangent to the curve of the function $e^{x^2}$ in the point with coordinates $x=1$,$y=e$.
I found that tis equation is $y=2ex-e$ Is this wrong?
Comment: you're absolutely right!!!
Comment: Yes/no questions such as these can also (and perhaps should) be asked in the chat: http://chat.stackexchange.com/rooms/36/mathematics
Comment: When $y= e^{x^2}$ you must have  $\frac{y-e}{x-1}=y'(1)$ so you are right because you have well calculated $y'(1)$.
Comment: i am sorry about my question
Answer: Line tangent to a curve in the point $(x_0, y_0)$:
$$y = f'(x_0) (x-x_0)+f(x_0)$$
where $f'(x)$ is the derivative of $f(x)$ and $f(x_0)=y_0$. Then, since in this case $f(x) = e^{x^2}$, we get $f'(x)= 2x e^{x^2}$. Therefore the equation of the tangent line is:
$$y=2e(x-1)+e=2ex-2e+e=2ex-e$$
So the answer is yes, you are right
Answer: here dy/dx=2xy
at(1,e) , dy/dx=2e
therefore equation of tangent line at (1,e)
y-e=2e(x-1)
y=2ex-e
Thanks