Removing Windows Logon screen through a service

Question: I am trying to remove the windows logon screen (winlogon) from an executable launched from a service. The service would start automatically with windows and wait for commands from another computer. When it receives a command, it will launch an exe which will start cmd.exe under a particular username.
The service is already present. I have the job of writing this executable. Currently, I have written the executable (CmdLogin) which starts cmd.exe under a different user through calls to LogonUserW, ImpersonateUser and CreateProcessWithLogonW. I specify lpDesktop as "WinSta0\Default". The only catch is that the service must run under an administrator account (but that is a different problem).
This works perfectly fine when called from a command prompt (even on Windows 7). This also works when called from the service when a user has logged on and viewing his desktop (like I do when debugging on the same machine). However, like I said above, my real requirement is for this to work even when the windows logon screen is displayed. Currently, the exe gives a proper exit code but the window does not appear. However, when the user logs in, he sees the cmd window on the desktop.
One solution I found was to use "WinSta0\WinLogon" for lpDesktop instead of Default. I am yet to try this. However, this looks like it will show the cmd window right over the login screen. What I really need is to actually emulate the user login to winlogon and show his actual desktop (and the cmd window).
I looked around and found GINA and Winlogon Notification Packages. They seem like an overkill and I am not sure if that will even solve the purpose here. Moreover, these are deprecated in Windows Vista which makes me think there is a better and neater method to solve this.
Any suggestions on what should I use to achieve this? For the record, the executable is in C# with API calls using P/Invoke. I am open to using a C dll that I can call from this C# application too.
Thank you,
Husain
Comment: Well, the reasoning for this is that my client needs an application where he can give out different usernames and passwords to people to access a Windows workstation without giving the actual username and password. The service running on the workstation will login the user for him remotely and the user will continue working on the workstation through a VNC client.

This seemed a little odd to me as it is as good as giving access to the Windows user (almost). However, this is what my client wants.
Comment:  Never keep things simple when you can do it the hard way... :-)  Anyway, your client wants to access the local system through a VNC connection? Way too complex. There should be easier methods to restrict the user.
Comment: Maybe you should explain the "weirdness" of this design to your client (sounds a bit like a semi-techie manager with a fixation on some technique they read about).

A standard Windows login, with "Change password on next login" set, was designed for this sort of thing. The account can also have an expiry, restricted workstation list, limited file system permissions etc. and then just use RDP/VNC. Easy.
Answer: GINA has been superceded in Vista/2008 by Credential Providers (not available in managed code).
I don't know how to do what you need, but perhaps this is a clue to go further down the trail.
And for the record, this seems like the wrong way to address the problem.  I just don't see how you would need to run a command prompt under an auto login...   Why not write a service to do your tasks, and have it run under a set of service specific credentials?
I don't have the background on your problem, but this description makes me shudder.  :-)
[Update]
Well, in response to your comment.    I would say that writing a GINA replacement for <= Windows 2003, or a custom credential provider for Vista/2008+ would look to be your best option.
You can provide custom authentication against his credential store, then allow or deny the login as you see fit.


Finding value in column of data frame corresponding to two values in another column

Question: Consider the following.
d=pd.DataFrame([[1,'a'],[1,'b'],[2,'c'],[2,'a'],[3,'c'],[4,'a'],[4,'c']],columns=['A','B'])

I want to find values in column A that correspond to 'a' and 'c' in column B ({2,4}). So I wrote the following query.
d[d.A.isin(set(d[d.B=='c'].A)) & d.B=='a'].A

My logic is that since
set(d[d.B=='c'].A

returns all values in A that have 'c' associated with them it should return {2,3,4} and it does return that. I then consider all the rows starting with {2,3,4}, and of these rows choose the ones that have 'a' associated with them in B so that I get all the values in A that have 'c' and 'a associated with them. But my query returns an empty set. It should return {2,4}. Can someone help debug? Thank you.
Answer: We can use filter
d.groupby('A').filter(lambda x : pd.Series(['a','c']).isin(x['B']).all()).A.unique()
Out[213]: array([2, 4], dtype=int64)

Comment: What does x['B'] mean? What is the actual value of x in lambda x:pd.Series...?
Comment: @user2371765 groupby A, check is all a or c in B , and keep that group
Answer: Use DataFrame.groupby
to check if the unique values in A have associated the value 'a' and the value 'c' in B:
new_df=d[d.groupby('A')['B'].transform(lambda x: x.eq('a').any()&x.eq('c').any())]
print(new_df)

   A  B
2  2  c
3  2  a
5  4  a
6  4  c

unique_values=new_df['A'].unique()
print(unique_values)
#[2 4]

Details:
You want to find what values in A have associates in B both 'a' and 'c'. Then you can use groupby('A') to perform operations on dataframe based on the unique values in row A:
d.groupby('A')

It allows to operate in groups based on the values in A:
   A  B
0  1  a
1  1  b

2  2  c
3  2  a

4  3  c

5  4  a
6  4  c

Now for each group using groupby.transform we check if 'c' and also 'a' is in column B:
d.groupby('A')['B'].transform(lambda x: x.eq('a').any()&x.eq('c').any())

0    False
1    False
2     True
3     True
4    False
5     True
6     True
Name: B, dtype: bool

Series.any is used to check if any value in Series B for
each group is 'c' or if any value in Series B is 'a'
Series.eq here is similar than use '=='

This series is used to perform a Boolean indexing.
new_df=d[d.groupby('A')['B'].transform(lambda x: x.eq('a').any()&x.eq('c').any())]
print(new_df)

   A  B
2  2  c
3  2  a
5  4  a
6  4  c

Finally using Series.unique
we access the unique values of A of the dataframe new_df:
unique_values=new_df['A'].unique()
print(unique_values)
#[2 4]

Comment: Sorry for not explain.Solution updaed. See section : Details.
Do not hesitate to ask if you have any doubt:)
Comment: d.groupby ('A) [' B '] means that for each group generated from column A, column B is selected. Then x in `.transform (lambda x: x.eq (' a '). any () & x.eq ('c'). any ()) `represents the values of B for each group.
Comment: That is, for each group the values of the Series B are transformed according to the function defined by: `lambda x: x.eq ('a'). Any () & x.eq ('c'). Any ()`
Comment: What is the issue with my query? Thank you.
Comment: You forget `()`. `d[d.A.isin(set(d[d.B=='c'].A))&(d.B=='a')].A` or `d[d.A.isin(set(d[d.B=='c'].A))&d.B.eq('a')].A` is correct
Comment: & takes precedence over ==. Thank you. I was perplexed for a long time because I was sure the logic was right.


C++ Convert SQLVARCHAR to string

Question: I need to convert from a SQLVARCHAR to a string data type
Variable definitions as follows:
string strFirstName;

SQLVARCHAR rtnFirstName[50];

Want to be able to accomplish the following:
if (strFirstName.empty()) strFirstName = rtnFirstName;

Gives an error that the binary '=': no operator found which takes a right-hand operand of type 'SQLVARCHAR[50]' (or there is no acceptable conversion)
Answer: What database API are you using? All the Google hits I can find for SQLVARCHAR say it's an unsigned char, so you can do something like this:
strFirstName = reinterpret_cast<char*>(rtnFirstName);

C++ Convert SQLVARCHAR to string


Folder permission in asp.net

Question: I have an asp.net application. There is a folder in the project that users upload images and files to that folder.
I want to restrict users, that each user sees only his files. How can I do this?
Because files are uploaded in folder, users may access them by browsing file urls.
Comment: How about using asp.net membership to control access. I think that is the "right" way.
Answer: One way is you could store the files inside the username of a folder, and your parameter which allows you specify a path always assumes you are talking about after the username...much like how shared web hosting must work.
Regardless, you should secure each folder for each user if there was some flaw in your code or whatever...
e.g. the physical file structure with each users files
C:\TheProject\Uploads\UserA\Images
C:\TheProject\Uploads\UserB\Images
C:\TheProject\Uploads\UserC\Images

your web app's url where you show the files for the currently logged on user. If UserA is logged on, show the files inside the appropriate folder etc
Happy paths:
http://example.com/browsefiles/?path=images
http://example.com/browsefiles/?path=docs

Unhappy paths:
http://example.com/browsefiles/?path=../UserA/images
http://example.com/browsefiles/?path=../../web.config

So obviously put some very tight checking around what input you accept...perhaps even a whitelist instead...if the query by the user doesn't match the whitelist, block it. In this scenario, you'd probably want to err on the side of blocking a legitimate request than allowing a malicious one.
Edit
If users can access the files without going through your web application (can we assume Intranet app here???) perhaps through a file share/network share/ftp then you could try a couple of options

Each user in your app is a user on the server (local user) so they would have a username and password on the server (which your app would need to authenticate against) but would allow you to set permissions on each folder/file on the server to a local user, OR
This might be easier if you have Active Directory setup and can use Windows Authentication and that way you could both impersonate your web app and secure the files/folders using the user's active directory account.

You might need to consult http://serverfault.com if you need help with Active Directory or Accounts on Windows servers
Comment: i want to acess files directly, not by a asp.net page and querystring. thanks
Answer: You have to create web.config in image folder and use FormsAuhentication
in web.config :
  <authorization>
  <deny users="?"/>  // anonymous user
  </authorization>

Comment: This doesn't limit that a user only sees his own files.

Folder permission in asp.net


Busca por intervalo de data ngFor

Question: Preciso de ajuda de alguém, procurei bastante mais não consegui achar. Tenho dois campos DataInicio e DataFim e preciso fazer um filter no ngFor para filtrar pelas datas selecionadas. Exemplo *ngFor="let order of opportunities | dateRange:'forecast':startDate:endDate; let i=index". Pesquisei e isso faz com PipeTransform...mas não tenho nem idéia de como fazer.
Answer: Olá!
No seu caso, eu criaria apenas uma função no próprio componente que filtrasse o seu array, para evitar ficar executando o código do pipe diversas vezes.

filtrarItens(arrayOriginal, startDate, endDate) {
  this.opportunities  = arrayOriginal.filter(item => {
    return this.inRange(item.forecast, startDate, endDate);
  });
}

/**
 * Verifica se a data está entre a data inicial e a data final
 */
inRange(data, startDate, endDate) {
  return startDate <= data && endDate >= data;
}

Mas para você ficar por dentro sobre pipes, abaixo eu dei uma pequena explicação sobre sua utilização.

O que é o pipe?
O PipeTransform é um mecanismo do Angular para tratar dados antes de exibi-los na DOM. O próprio Angular possui seus próprios pipes como DatePipe que formata uma data para a qual você seja, UpperCasePipe para tornar letras maiúsculas, CurrencyPipe para formatar moedas, etc.
Como utilizar o pipe do angular?
A utilização de um pipe é bem simples.
{{ dado | nomePipe : PARAMETRO1 : PARAMETRO2 : PARAMETRO3 }}
O dado é o elemento que você deseja formatar. Depois vem essa barrinha ( | ) para informar ao Angular que será aplicado um pipe chamado nomePipe. E por fim, separado por dois pontos, são passados todos os parâmetros necessários para o pipe.

Porém tome bastante cuidado em utilizar Pipes dentro de *ngFor, pois toda vez que o Angular detectar uma mudança ele executará o pipe novamente, e dependendo da complexidade pode deixar sua aplicação bastante lenta.

Criando um pipe:
Você pode criar os seus próprios pipes. Pelo que entendi você deseja uma função que passe o array de itens para filtrar e mais 3 argumentos, que são:

atributo (forecast) - seria o atributo do objeto com a data para comparar
startDate - a data inicial.
endDate - a data final.

Você pode criar um pipe pelo comando ng generate pipe dateRange que irá gerar um arquivo com a função transform, ela que será executada para tratar o seu dado. Abaixo eu fiz uma implementação para filtrar as datas.
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'dateRange'
})
export class DateRangePipe implements PipeTransform {

  transform(value: any, atributo: string, startDate: Date, endDate: Date): any {
    if (!value) {return value };

    return value.filter(item => {
      return this.inRange(item[atributo], startDate, endDate);
    })
  }

  /**
   * Verifica se a data está entre a data inicial e a data final
   */
  private inRange(data, startDate, endDate) {
    return startDate <= data && endDate >= data;
  }

}

Fiz um exemplo no stackBlitz de um projetinho, você pode ver melhor como funciona.

Links legais:

Transforming Data Using Pipes
O que são pipes no Angular 6
Angular 5 — Como usar Pipes
Comment: Bruno, é bem por aí que eu precisava. Fiz algumas e estou conseguindo exibir somente os registros do mês (exemplo 09-2020), mas quando tento filtrar ele não está buscando os registros. Segue exemplo do que estou fazendo https://pastebin.com/g2rnBLLd
Comment: Aparentemente a comparação que está fazendo entre as datas está incorreta. O "format()" retorna uma string e não um tipo "moment" que facilite a comparação. O que vc pode fazer é converter o startDate e endDate para o tipo moment assim: https://momentjs.com/docs/#/parsing/string/.... e depois comparar se a data está entre os dias: https://momentjs.com/docs/#/query/is-between/. Veja se dará certo, qualquer coisa só falar

Busca por intervalo de data ngFor


Problema navbar bootstrap no Wordpress

Question: Um cliente pediu para eu aumentar o tamanho da navbar, até aí tudo bem.
Aumentei e não tive problema, porém, quando eu desço a pagina e subo novamente, a navbar vai para trás do slider.
Comment: Coloque o código na pergunta.
Comment: Link do site: http://novosite.analubi.com.br/
Answer: Problema com z-index.
Deixe assim o seu navbar que vai funcionar.
<code>.navbar {
    border-bottom: 0px solid #d1d1d1;
    padding-top: 20px;
    z-index: 3;
}
</code>
Comment: Caramba, perfeito, era isso mesmo! Muito obrigado!
Comment: Se a resposta funcionou, marque ela como "resposta". :D

Problema navbar bootstrap no Wordpress


Passenger + nginx: application doesn't run in production mode

Question: I'm using Passenger + Nginx to run a Rails app. If i use "rails_env development;" the application works fine.
But if i run in production mode, i get "We're sorry, but something went wrong.".
I did ran db:migrate for production and i can access the database normally.
The strange thing is that i don't get any new entries in logs ( nginx and rails one ) and i made sure nginx user could write on them.
If i run rails console production, it works fine:
# rails console production
Loading production environment (Rails 3.2.0)
1.9.3-p125 :001 >

Any ideas of what might be happening? What else should i check?
----Edit----
After @BenLee suggestion of adding passenger_debug_log_file to nginx.conf i started to get this error for both development and production:
# /etc/init.d/nginx restart
nginx: the configuration file /opt/nginx/conf/nginx.conf syntax is ok
nginx: [alert] Unable to start the Phusion Passenger watchdog: it seems to have crashed during startup for an unknown reason, with exit code 1 (-1: Unknown error)
nginx: configuration file /opt/nginx/conf/nginx.conf test is successful
Parando o nginx:                                           [  OK  ]
Iniciando o nginx: nginx: [alert] Unable to start the Phusion Passenger watchdog: it seems to have crashed during startup for an unknown reason, with exit code 1 (-1: Unknown error)
                                                           [  OK  ]

I searched about this error but i still haven't found a solution. Watchdog seems to exist and is in the right place:
# ls -lh /usr/local/rvm/gems/ruby-1.9.3-p125/gems/passenger-3.0.11/agents/
total 7,8M
drwxr-sr-x 2 root rvm 4,0K Fev 22 23:34 nginx
-rwxr-xr-x 1 root rvm 4,6M Fev 22 23:35 PassengerLoggingAgent
-rwxr-xr-x 1 root rvm 3,3M Fev 22 23:34 PassengerWatchdog

If i remove passenger_debug_log_file it starts normally. But the original problems comes back, application does not run in production mode.
Comment: what does `rails server -e production` do?
Comment: It starts normally, listening on port 3000.
Comment: If you find that the Rails logs aren't being written to, check the error log of nginx (/var/log/nginx/error.log). They should have something in there that should give you a clue as to why this is happening.
Comment: I find that the important log file to check to debug this kind of problem is `passenger.log`, not `error.log`
Comment: Sorry but here isn't anything on error_log. Only "cache: [GET /] miss".
Comment: @BenLee where can i find passenger.log? Is it create inside nginx logs folder?
Comment: @Fernando, look at your `nginx.conf` for a line that looks like `passenger_debug_log_file`. That will tell you where the log file is.
Comment: Thanks @BenLee. I have updated the question with more information. I'm not sure, but i haven't seem anyone with this exact error code. Maybe it's time to fill in a bug report.
Comment: @Fernando, I have some ideas, but I need more info. Can you post your full nginx.conf? (just erase any sensitive information)
Comment: Also, please post the output of this command on the server machine: `ls -la /tmp | wc -l` (this will tell you how many files are in the /tmp directory)
Comment: Fernando, with your recent edit, you say, "application does run in production mode." Do you mean, "application does NOT run in production mode"? That was your original problem, right?
Comment: Also, can you post the nginx vhost configuration for your site? Not necessarily the whole `nginx.conf` file, but the `server` block for your production site.
Comment: @BenLee Sorry for the delay. My nginx.conf is available here http://pastebin.com/BcN4EQD1
Comment: @pjmorse That is correct. It was a typo in my last edit. I've fixed it. See my previous response to BenLee with my nginx conf.
Comment: @BenLee My tmp folder contains 31 files at this moment.
Comment: @Fernando, none of my ideas were right :(. I'm out of ideas about what's going wrong, it really looks like some file just got corrupted somehow. If I were in your shoes at this point, I'd try re-installing all the agents by copying them from a standalone installation. Do you know how to do that? If not, I'll post it as an answer (because it may solve your problem).
Comment: you should check for conflicting versions of ruby, and also that your log file folders have the right permissions. No logs is a sign that the daemon doesn't have permissions.
Comment: @BenLee I'm not sure about how to do that. If you can add this as an answer i would appreciate.
Answer: Even though Fernando seems to have solved the problem through updating the agents I had a similar issue but another solution.
I also had this behavior with a rails app when using passenger and nginx. Everything worked fine when setting rails_env development; in nginx.conf. However when changing development to production it did not work anymore and the connection was refused when trying to connect from the browser. Anyway, the problem was in the production.rb file and the line
config.force_ssl = true

When I commented that out, the application worked in production. And instead of configuring ssl in the rails app I did it in nginx.conf.
Hope this might help someone else setting up a rails app with passenger and nginx.
Answer: This looks like it could be some sort of file corruption, possibility located in one of the agents. One thing that may help is to reinstall fresh versions of the agents. You can do this via the passenger standalone package.
To do this, first SSH in to the server and then, in any directory (in the examples below, I'm going to assume your home directory, but any directory will do), run:
passenger package-runtime

This will seem to do a lot of downloading and configuration and installation, but don't be alarmed. All that will do is install the passenger standalone version in a subdirectory called passenger-standalone. After running this command, you should see a file structure like this (assuming you ran the command in your home directory):
+ /home/you
    + passenger-standalone
        + 3.0.11-....
            nginx-x.y.z.tar.gz
            support.tar.gz

So it's just a tree with two tar.gz files in it (note the 3.0.11-... is not literal, but will start with that string -- the full name is system dependent; similarly the x.y.z in one of the tar.gz files will actually be a version number). Next, untar the support.tar.gz, doing something like this:
cd passenger-standalone/3.0.11-....
tar xzvvf support.tar.gz

This will extract to the current directory. Among many other things, it will create an agents subdirectory with two new files:
+ /home/you
    + passenger-standalone
        + 3.0.11-....
            + agents
                PassengerLoggingAgent
                PassengerWatchdog

The idea is to copy these agent files over your original system ones, to fix any corruptions that may be present in the system version. But first, set the permissions appropriately. Following from where the commands above left off, run:
cd agents
sudo chown root:rvm Passenger*

Next, backup your original agents:
cd /usr/local/rvm/gems/ruby-1.9.3-p125/gems/passenger-3.0.11/agents
sudo cp PassengerLoggingAgent PassengerLoggingAgent.backup
sudo cp PassengerWatchdog PassengerWatchdog.backup

Finally, move the fresh versions from the standalone package here.
sudo mv /home/you/passenger-standalone/3.0.11-..../agents/Passenger* .

Then, restart nginx. If for some reason you need to undo this, just restore the backup copies and restart nginx again.
As an optional cleanup step, you don't need those standalone files any more, so you can remove them like this:
rm -rf /home/you/passenger-standalone

Comment: Thanks for all the help. I was able to fix the problem following your answer.


Como chamar uma variável que está em outro arquivo?

Question: Tenho um arquivo "Y.php" que retorna em um dos inputs, o cálculo resultante de outros inputs dentro deste mesmo arquivo, faço isto usando Jquery e está funcionando 100%.
Porém, gostaria de usar o resultado deste cálculo que está armazenado na variável "X" em uma outra input contida no arquivo "Z.php". Ou seja, quero usar o valor desta input (contida em "Z.php") como resultado de outra input contida no arquivo "Y.php".
Como faço isso com JavaScript?
require ('apNaoCirculantes.php'); //arquivo onde está a input na qual desejo pegar o valor
            var totaldeparred; // é o variável da input
            var campo16; // já estou no arquivo Z.PHP
            campo16 === totaldeparred;
            $("#depreciacao1").maskMoney('mask', totaldeparred); //minha input #depreciacao1 recebe o valor contido em totaldeparred

É isso?
Comment: Vc pode fazer isso via include ou Ajax? Sua pergunta ficou meio distante.
Comment: Tanto faz, posso testar a solução que for mais simples?
Comment: Então a forma mais fácil é fazer um include. Assim o input com o valor que vc quer pegar vai estar na mesma página e pode pegar esse resultado com  JS.
Comment: Pode citar um exemplo deste include?
Comment: `require('pagina.php');`
Comment: Pelo que entendi, vc quer abrir a página Z.php e pegar o valor contido num input da página Y.php, é isso?
Comment: sim, quero o valor da input que está em Y.php e colocá-lo na input contida em Z.php.
Comment: Isso eu entendi. Mas a página que vc quer abrir é a Z.php?
Comment: Sim, exatamente.
Comment: Vou elaborar uma resposta com o conceito disso, já que não tem código exato, aí vc testa.
Answer: Faça um include do arquivo Y.php no início do  página Z.php:
<?php require('Y.php'); ?>

Em seguida pegue o valor do <input> pelo id (se o input tem um id) desejado vindo da página Y.php e coloque no <input> da página Z.php:

Comment: Funcionou perfeitamente. obrigado.


Integração Java JSON, Socket ou RMI

Question: Na empresa onde eu trabalho, precisamos integrar nosso sistema desktop, o qual possui um banco de dados local com um sistema que estará rodando em um servidor cloud. O primeiro pensamento foi utilizar JSON, mas ouvindo e lendo algumas coisas, acabei vendo que boa parte do processamento de um servidor acaba indo por causa dos parse e como alternativa cheguei a pensar em utilizar algumas outras possibilidades de integração, como Socket ou RMI. Pensar em outra alternativa foi devido não ter muitos recursos as máquinas e querer ter um desempenho melhor. Esta seria uma boa escolha ou não?
EDIT
Cenário da integração:
Nos clientes possui um sistema desktop rodando, sendo ele um sistema gerenciador (retaguarda com cadastro de produtos, clientes, contas a pagar e tudo mais que existe) e também um frente de caixa e que possui um banco de dados MySQL no cliente. A integração terá um integrador, por assim dizer, que ficará pegando os dados do banco de dados e enviando para esta nova estrutura na nuvem, onde terá uma aplicação rodando para receber estas informações e persistir no banco de dados, no caso preparada para trabalhar com JSON, RMI ou Socket.
Então vou ter controle nas duas partes, tanto na que envia, como na que recebe. Como falei, a primeira alternativa seria JSON, mas após ouvir um case de uma empresa, acabei voltando a pensar no que utilizar, já que eles pararam de utilizar o mesmo devido o grande custo/tempo de processamento com o parse e partiram para RPC, no caso o RMI no Java.
A princípio esta integração será para poucos clientes, mas vamos dizer que pode chegar daqui algum tempo para cerca de 2000 clientes.
Dados que irá integrar: Tudo, desde cadastros (cliente, produtos, endereços, telefones e muito mais até movimentações como venda, pagamentos, transferências e etc.)
Quantidade de comunicações: A princípio não muitas, mas com tendência a aumentar para cerca de 2000 clientes, os quais cada um terá um integrador e irá enviar os dados para esta estrutura.
Outros sistemas irá integrar? Nesta entrada de dados do integrador não.
Comment: Que tipo de dados precisará integrar?
Serão muitas comunicações? Muitos dados?
Mais algum sistema precisará integrar com o servidor em cloud?
Talvez respondendo estas perguntas fica mais fácil de te ajudar.
Comment: Só para contextualizar e lhe dar uma ideia, o tempo de interpretação do JSON é completamente insignificante na esmagadora maioria dos casos, a não ser para grandes volumes de dados ou talvez para sistemas de "tempo real", nos quais você pode obter vantagens em suar formatos binários ou mais compactos, porém humanamente ininteligíveis.
Comment: Bem-vindo ao [pt.so]! Reforçando o que o Murillo disse acima, é quase impossível dizer o melhor formato para uma integração sem ter uma noção do tipo, do tamanho, da frequência de transmissão e do tempo de resposta esperado. Por favor, edite sua pergunta com esses detalhes, se possível com exemplos. Abraço!
Comment: @MurilloGoulart desculpe pela falta de informação na pergunta. Adicionei o cenário que será a integração e mais algumas informações.
Comment: @utluiz Muito obrigado! Já realizei as modificações e coloquei como será o cenário mais ou menos. Em relação ao parse do JSON pensei devido aos objetos terem outros objetos acoplados, como Venda, que possuo uma lista de produtos vendidos, que nesta lista possuo um produto, que neste produto possui diversas outras informações... Então  pensei nestas alternativos como RMI e Socket.
Comment: Eu queria só dizer que é uma falácia comum desenhar um sistema tendo por base que ele vai ser enviado em determinado protocolo e em determinado formato. Em vez disso desenhe o seu sistema para resolver o problema em questao e pense que os dados podem ser enviados através de qualquer protocolo e em qualquer formato. A empresa onde eu trabalho atualmente sofre por nao ter respeitado este principio...
Comment: Olá @BrunoCosta no caso o sistema que irá rodar na nuvem já se tem uma ideia, faltando apenas realizar as integrações dos dados que existem nos clientes com o servidor na nuvem, no caso restando esta dúvida em adotar umas destas tecnologias.
Comment: Alguma resposta resolveu o que estava em dúvida? Precisa que algo mais seja melhorado?
Comment: @MurilloGoulart creio que minha dúvida foi solucionada com a ajuda de todas as respostas. Obrigado.
Answer:
[...] O primeiro pensamento foi utilizar JSON, mas ouvindo e lendo algumas coisas, acabei vendo que boa parte do processamento de um servidor acaba indo por causa dos parse e como alternativa cheguei a pensar em utilizar algumas outras possibilidades de integração, como Socket ou RMI. [...]

Isso daqui é falacioso por vários motivos:

Você está misturando coisas. Socket é um canal de comunicação para transportar um monte de bytes de um lado a outro. JSON é um formato de estruturação de dados. Fazendo uma analogia com o mundo real, vamos supor que você queira viajar da cidade A à cidade B, então o socket seria equivalente ao portão de uma garagem ou a uma plataforma de trem e o JSON seria a bagagem que você está levando contigo. Não há sentido em dizer que você escolhe um em detrimento do outro.
Supondo que você use socket para transportar algo que não é JSON, ainda assim, para montar pacotes com esses dados, enviá-los de um lado a outro e interpretá-los corretamente, você provavelmente vai acabar inventando um parser com isso e esse parser pode ser mais simples ou mais complexo do que usando JSON.
RMI é uma tecnologia que permite você a trabalhar mais rápido na integração e deixa os detalhes do transporte de objetos mais transparente. Entretanto, o protocolo RMI é significativamente complexo e pesado, bem mais complicado do que o HTTP.

Há também outros aspectos a se considerar:

RMI não é muito amigável a firewalls.
Inspecionar o conteúdo de mensagens trafegadas via RMI, fazer log e medir o tráfego são tarefas complicadas.
Serialização é algo bem chato de se lidar com o RMI, especialmente quando o você tem clientes com diferentes versões do aplicativo que usam classes incompatíveis entre si e o servidor tem que dar suporte a ambos. Esse cenário é bem mais fácil de se lidar usando REST + JSON.
Tudo isso usa sockets no fim das contas. Se quiser usar os sockets diretamente, muita coisa ainda vai depender do que você está utilizando neles. Entretanto, sem ter mais detalhes de qual é o formato dos dados trafegados, fica difícil avaliar essa solução.
Existem outras alternativas além dessas. Nada te impede de enviar por meio do HTTP, FTP, SOAP, e-mail, ou o que quer que seja, um monte de bytes com a estrutura que você preferir: XML, JSON, imagens, binário, TXT ou o formato que você quiser.

Ah, e nem sempre desempenho é um quesito tão importante ou que pode ser medido de forma simples. Por exemplo, vejamos os seguintes cenários:

Você tem um grid computacional distribuído triturando números para fazer simulações quânticas de comportamentos de partículas.
Você vai fornecer streaming de vídeo ao vivo de alta resolução para dezenas de milhares de pessoas.
Você tem que processar imediatamente milhares de pedidos de compra simultâneos originados de redes de lojas com milhares de filiais.
Você tem um crawler que vasculha a internet ou plataformas sociais para buscar, ordenar e filtrar informação.
Você tem uma rede social na qual vários clientes/usuários estão interagindo uns com os outros, postando e recebendo um monte de conteúdo.

Cada um desses cenários é otimizado de um jeito diferente. Uma solução considerada de alta performance em um desses cenários pode ser completamente inadequada em um outro.
O seu cenário se aproxima mais do 3, e acho que o que você vai querer otimizar será o tempo de resposta da requisição, o que é diferente do conceito clássico de desempenho que é apenas quantidade de instruções processadas por unidade de tempo (que faz mais sentido no caso 1). Com isso, você vai ter que medir ou estimar:

(A) Quanto tempo ele demora para receber a requisição.
(B) Quanto tempo ele demora para fazer o parse dos dados da requisição.
(C) Quanto tempo ele demora para fazer algum serviço com esses dados (transformar em outros dados, salvar no banco de dados, enviar para um outro serviço, etc).
(D) Quanto memória é gasta com esse processo.

Se ao medir ou estimar esse processo, o tempo gasto for dominado por qualquer coisa que não seja o B, então otimizar o tempo de parse não vai te trazer muitos ganhos reais, pois provavelmente não seria aí que estaria o seu gargalo. Na maioria dos casos reais que vejo, o maior gargalo está no item C, e não no item B. Aliás, no caso de JSON, que tem uma estrutura bem simples, quase sempre o item B acaba sendo insignificante.
Um outro aspecto importante, é o se você vai usar requisição síncrona ou assíncrona. O modelo assíncrono é muito mais escalável, e é uma das razões por trás do sucesso de sites como Amazon, Twitter e Facebook, que lidam com um volume monstruoso de requisições. A ideia aqui é tão logo o passo A acima seja completado, que os dados recebidos sejam armazenados na memória, no disco ou no banco de dados com o mínimo possível de processamento a fim de dar uma resposta logo ao cliente. Essa resposta ao cliente não diz se a requisição foi bem sucedida ou não, ela apenas diz que ela foi recebida e será processada mais tarde. Com isso, você pode mover essas informações recebidas para outros servidores e processá-las sem ter que manter a conexão com o cliente aberta, incluindo nisso o item B e a maior parte dos itens C e D. Mais tarde o cliente faz uma requisição ao servidor perguntando se o processo já terminou e se teve sucesso ou erro, e caso o processo já tenha sido finalizado, o servidor pega o resultado já pronto e devidamente formatado e o entrega.
Por fim, você deve separar duas coisas: Uma coisa é especificar qual o formato dos dados, outra coisa é especificar como eles saem da origem e chegam no destino. Tecnologias como o RMI, o CORBA e o EJB unem as duas coisas, mas as tendências mais modernas na arquitetura de computadores estão indo no sentido contrário.
De qualquer forma, eu já eliminaria de cara o RMI. Gerenciar o RMI é difícil, e ele só funciona bem quando há uma rede disponível de alta disponibilidade, alta confiabilidade e alta velocidade, que não é o seu caso. O RMI seria uma solução viável para o caso 4 delineado acima e talvez o caso 1, mas para o caso 3, isso não funciona tão bem. O RMI só funcionaria legal (talvez) se você tiver um conjunto de servidores formando um grid, e mesmo assim se ele ficar restrito apenas ao ambiente dos servidores. Mas de todas as formas, não vejo o RMI como uma boa alternativa para conversar com os clientes.
Comment: Realmente, no meu cenário RMI e Socket não se encaixaria muito bem devido a vários fatores e o parse dos JSON não é o problema que eu esteja pensando que vou ter. Vou continuar com a estratégia do JSON e trabalhar em cima. Muito obrigado pelo esclarecimento e pleo seu tempo Victor.
Answer: Como o Victor já disse na resposta dele, provavelmente o parser de JSON não será o gargalo da sua aplicação, a não ser que, por alguma razão, haja um número excessivo de mensagens.
Antes de mais nada, você precisa estimar a quantidade de mensagens por minuto (use a unidade adequada para seu caso) esperada quando migrar para o novo sistema. Talvez você precisa instrumentalizar o sistema atual para logar a quantidade de escrita e leitura no banco e então fazer alguma estatística com esses dados.
Multiplique o resultado pelo crescimento máximo que você espera na base clientes nos próximos 5 anos (só um exemplo).
Suponha que você chegou a um valor de 500 mensagens/transações por minuto.
A partir daí, a nova arquitetura terá que responder como ela vai aceitar 500 requisições por minuto, processar a entrada, aplicar regras de segurança, regras de negócio, alterar o banco de dados e gerar uma resposta.
Percebe como parsing de JSON praticamente some no meio disso tudo?
Um sistema na nuvem geralmente deve ser escalável, no sentido de permitir adicionar ou remover mais nós num cluster sob demanda e continuar funcionando normalmente. Por exemplo, você pode chegar à conclusão de que para atender 500 transações por segundo, você precisa de 5 instâncias da aplicações em diferentes 5 nós. Neste caso, o parsing de JSON some ainda mais.
Enfim, a não ser que haja realmente fortes e concretas razões para você acreditar que parsing será um gargalo, é uma má ideia fazer uma escolha tão cedo.
Reflita se o case que você ouviu sobre o desempenho do JSON tem algo a ver com o seu case. Pondere ainda a confiabilidade da informação, pois infelizmente muitas pessoas usam a tecnologia de forma inapropriada. Existem várias implementações de JSON e várias formas de usar cada uma. Para alguém falar com propriedade sobre o desempenho do JSON, teria primeiro que demonstrar que foi feita uma comparação e a melhor estratégia disponível estava sendo usada.
Finalmente, existem alternativas equivalentes ao JSON que prometem ser mais rápidas e estruturadas, como o Protobuf do Google. Como no seu caso você vai trafegar dados estruturados de negócio, talvez seja uma boa ideia avaliar tal ferramenta pois ela permite a definição mais estrita dos tipos de dados num formato mais compacto, mas legível.
Comment: A aplicação do case eu tenha visto realmente é um pouco diferente e não é o mesmo cenário, então acho que viajei um pouco em relação a isto sobre JSON e caso eu precise de mais processamento a alternativa seja esta que você falou, criar um cluster e o parse do JSON nem irá aparecer. Muito obrigado.
Answer: Para integrações de dados entre frente de caixa e servidor, onde a frente de caixa deve funcionar mesmo quando perde totalmente o acesso com o servidor, já vi serem aplicadas com sucesso as seguintes abordagens:

Integração direta entre bancos de dados via jobs: O banco local comunica com o servidor para sincronizar os cadastros e enviar os novos movimentos; Mais fácil de implementar, não exigindo processo externo ao banco de dados;
Integração com EDI: O frente de caixa sincroniza os cadastros a partir da leitura de arquivos disponibilizados pelo servidor, como TXT com formato fixo, ou XML/JSON. Desta mesma forma grava os movimentos e disponibiliza em arquivos para o servidor em local compartilhado na rede ou envia por algum protocolo de transferência de arquivo (FTP?);

Acredito que com RMI, e ainda mais com Socket, a complexidade da implementação aumentará drasticamente, além de precisar de processos externos, como um servidor robusto para aceitar conexões, inclusive sendo mais um recurso para ser administrado na sua arquitetura.
Comment: No caso o nosso sistema no cliente não terá em certo momento dependência mesmo do sistema que estará na nuvem, onde este sistema servirá apenas para consultas de informações e geração de relatórios. Sobre a integração direta de bancos talvez não seja possível, já que queremos normalizar/distribuir algumas informações que estão embaixo na parte de cima. Você acha que com socket ou RMI eu precisaria de um servidor mais robusto do que realizar a integração via Web Service com JSON ou XML?

Integração Java JSON, Socket ou RMI


Azure Cosmos DB - Delete entire partition

Question: I am very new to cosmos Db and have a requirement of deleting a complete partition. On performing a brief research I found that drop partition is not a thing. Consequently i stumbled on the following link which is a stored procedure for bulk delete
https://github.com/Azure/azure-cosmosdb-js-server/blob/master/samples/stored-procedures/bulkDelete.js
I created this stored procedure on my collection and clicked 'Execute'. I got the following prompt

I entered the partition key and input parameter to 'select * from c'. However, I can see that only 38 documents are deleted at a time and the query completes successfully. Are there any setttings that are forcing the stored procedure to stop prematurely?
Comment: Hi,your link and your image are gone.Please fix them so that we could get more details.
Comment: Thanks. I have updated the image. The problem is described in the last two lines. I am using the stored procedure from the first link.
Comment: Have you checked the number of the retrieved documents by sql and the number of deleted documents.Are they equal? No any error occurred? You could use console.log() to locate my question.
Comment: Hi,any progress?
Comment: It depends on the RUs allocated. You need  a continuation token to keep re-trying
Comment: In the meantime Microsoft is actively working on a way to delete data based on a partition key. For a private preview you can apply via https://aka.ms/cosmosPkDeleteSignup
Answer: As you mentioned in the comment, your situation is depends on the RUs allocated.I provide you with below sample stored procedure code.You could refer to it.
<code>function deleteSproc(query) {
    var collection = getContext().getCollection();
    var collectionLink = collection.getSelfLink();
    var response = getContext().getResponse();
    var responseBody = {
        deleted: 0,
        continuation: ""
    };

    // Validate input.
    if (!query) throw new Error("The query is undefined or null.");

    tryQueryAndDelete();

    function tryQueryAndDelete(continuation) {
        var requestOptions = {
            continuation: continuation,
            pageSize: 10
        };

        var isAccepted = collection.queryDocuments(collectionLink, query, requestOptions, function (err, documents, responseOptions) {
            if (err) throw err;

            if (documents.length > 0) {
                tryDelete(documents);
                if(responseOptions.continuation){
                    tryQueryAndDelete(responseOptions.continuation);
                }else{
                    response.setBody(responseBody);
                }

            }
        });

        if (!isAccepted) {
            response.setBody(responseBody);
        }
    }

    function tryDelete(documents) {
        if (documents.length > 0) {
            var requestOptions = {etag: documents[0]._etag};

            // Delete the document.
            var isAccepted = collection.deleteDocument(
                documents[0]._self,
                requestOptions,
                function (err, updatedDocument, responseOptions) {
                    if (err) throw err;

                    responseBody.deleted++;
                    documents.shift();
                    // Try updating the next document in the array.
                    tryDelete(documents);
                }
            );

            if (!isAccepted) {
                response.setBody(responseBody);
            }
        }
    }
}
</code>
Furthermore, as I know, stored procedure has 5 seconds execute limitation. If you crash into the timeout error, you could pass the continuation token as parameter into stored procedure and execute stored procedure several times.
Any concern, please let me know. Thank you.
Comment: I tried using this stored procedure and I am always getting (429) Too Many Requests. How can I fix this issue?
Comment: @DevMJ you need to increase throughput for your container. Your requests are being throttled that's why 429
Answer: If you are creating the above stored procedure then make sure while execute you will give the Value of partition key not the name of partition key column.
Also Cosmos DB stored procedure will run only in one partition at a time and it will be the same which you are passing in Input (partition key value).
Answer: We can now delete items by partition key. The feature is currently in public preview with Java and .NET SDK support also available in preview packages.


Friendly URLs - caching wrong route

Question: I am using ASP.NET Friendly URLs with a C# asp.net 4.5.1 website on a Windows 2012 Server with IIS implementation.
(this simply and automatically converts aspx pages into nice URLs - eg mydomain.com/mypage.aspx - into mydomain.com/mypage). If a page isn't found the site then falls back to looking for routes. My RouteConfig.cs looks like this...
<code>var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;

// Firstly Friendly URL's are enabled
routes.EnableFriendlyUrls(settings);
routes.Ignore("{resource}.axd/{*pathInfo}");

// Now a regular root is looked for
routes.MapPageRoute("route1", "{myroute}/{myroutename}", "~/routepage.aspx");
</code>
I tried accessing mydomain/testpage when testpage.aspx DIDNT exist. It routed to mydomain.com/thispage.
I then created testpage.aspx - but now if I try and access mydomain/testpage it still goes to the old route like the page doesn't exist. I've tried restarting the website in IIS, reuploading the RouteConfig.cs file - it still routes wrong.
I've tested on multiple browsers (Chrome & FF on Mac) - all fail. I've tried typing mydomain/testpage.aspx - still routes wrong.
I created a new subdomain for testing - and the page works fine in that.
It's like it's cached somewhere. How can I 'force a refresh' - ie get the newly uploaded page to work?
thanks
Answer: Ensure you are uploading the bin folder - this fixed it.

Friendly URLs - caching wrong route


Proof that this equation is correct

Question: Using a truth table I had no problems to proof, that this equation is correct.
But how can I transform the first part to get to the second?
I tried using de morgan but I never made it.
Can anyone give me advice?
Comment: What does it mean for two truths to be equal?  The truths "usually grass looks green," and "the Earth revolves around the sun", I think, have the same truth value.  But do those truths stand as equal?
Answer: The contrapositive of the first one is $\lnot r\to\lnot(\lnot p\land q)$, which equals the second expression.
Answer: $$\neg p \wedge q \rightarrow r =$$
First we know that $A\rightarrow B$ is equivalent with $\neg A\vee B$ thus.
$$\neg(\neg p \wedge q) \vee r  =$$
Now use de morgan:
$$ (p \vee \neg q) \vee r =$$
Switch place between $r$ and $(p \vee \neg q)$ and notice that $r$ is equivalent with $\neg \neg r$.
$$\neg \neg r \vee (p \vee \neg q) =$$
Now again use that $A\rightarrow B$ is equivalent with $\neg A\vee B$ and we reach our conclusion.
$$\neg r \rightarrow (p \vee \neg q)$$

Proof that this equation is correct


Impact on probability distribution when introducing new information

Question: Consider a context in which $f(X)$ is a probability density function for a given random variable $X$, with domain comprised in $[l,u]$ ($l$ = lower bound, $u$ = upper bound).
Now, consider that someone (e.g., an oracle) gives me additional information regarding the domain of the given p.d.f. $f(X)$. That is, someone says to me that the p.d.f. should be located between $[l',u']$ instead of $[l,u]$ with:

$l'\geq l$
$u' \leq u$

This in some way is equivalent to state that the variable $X$ now cannot assume values in the interval $[l,l']$ and/or in the interval $[u',u]$ (as suggested by the rough information I had before this oracle spoke).
How does this new information affect the p.d.f. $f(X)$? Is there a way of "cutting away" part of the distribution so as to reshape it in the new interval?
EDIT: I would like now to condition on the fact that $X$ can only take values on $[l',u']$.
Thank you so much for your help.
Comment: Are you trying to suggest that your variable was never capable of taking values outside of $[l',u']$, or that you are now __conditioning__ it on only taking values in $[l',u']$? In the former case, your PDF hasn't changed; in the latter, this is merely a statement about conditional probability.
Comment: The second one. I would like to condition it to the new collected information.
Answer: To condition on the knowledge that $X$ is in $A$, where $A$ is such that $P[X\in A]\ne0$, replace the density $f_X$ of $X$ by the density $f_{X\mid A}$ defined as
$$
f_{X\mid A}(x)=\frac{f_X(x)\mathbf 1_A(x)}{P[X\in A]}.
$$
That is, $f_{X\mid A}(x)=0$ if $x$ is not in $A$ and, if $x$ is in $A$,
$$
f_{X\mid A}(x)=\frac{f_X(x)}{P[X\in A]}.
$$
The case you describe is when $A=[\ell',u']$.


Appending element to a 3-dimensional list

Question: I have a problem with appending a new element to a 3-dimensional list. Instead of appending a new element in one place (threeDimList[1][1]), it appends it in the whole row (threeDimList[1][0], threeDimList[1][1], threeDimList[1][2]) Here is my code:
threeDimList = [[[]]*(3) for i in range(3)]
threeDimList[1][1].append(1)
print(threeDimList)

which gives me:
[[[], [], []], [[1], [1], [1]], [[], [], []]]

instead of:
[[[], [], []], [[], [1], []], [[], [], []]]

Comment: Possible duplicate of [How to add elements to 3 dimensional array in python](http://stackoverflow.com/questions/15448594/how-to-add-elements-to-3-dimensional-array-in-python)
Comment: Although the question being asked is a duplicate the problem encountered is different.
Comment: @ncfirth we could still relate to the marked duplicate question and the answer provided here is similar the marked question.
Answer: The problem is that [[]] * 3 basically creates a list containing three references to the same [].
You can do something like:
>>> a = [[] for i in range(3)]
>>> a[0].append(1)
>>> a
[[1], [], []]
>>> b = [[]] * 3
>>> b[0].append(2)
>>> b
[[2], [2], [2]]

In the a case, given list comprehension, [] is evaluated three times, so you get a new empty list object in memory for every evaluation.
In the b case, [] is evaluated once, wrapped as [[]], and then that is replicated.
Comment: Thanks. So basically the problem was with creating the list. My solution to this problem is as follows: `threeDimList = [[[] for i in range(3)] for i in range(3)]`


Persist console with winrm and powershell

Question: I just started working with powershell to automate a process, and now I'm stuck with win remoting.
I enabled remoting on the machine I want to connect to and can execute a singleline command easily, e.g.
winrs -r:http://$servername:5985 -u:$user "dir c:\"

And after that command is executed the remote shell is done and i need to write winrs -r... again everytime I need to execute a command.
Is there any way to stay in the remote computer's console, like when I'm telneting or connecting with ssh?
Answer: In PowerShell try:
Enter-PSSession -ComputerName $servername

Comment: Wow! Works great :D I don't even need to send my credentials with this method. Thanks a lot for the quick response.
Comment: One thing to keep in mind, the session is destroyed once you exit the session (type Exit-PSSession or 'exit'). To keep it running and connect to it later on - create a session. Take a look at the help for the New-PSSession cmdlet.
Comment: Thanks again. Just one thing I noticed: When entering the wmi cli with wmic, winrs works better for me, since the session stays active.
Entering wmic in Enter-PSSession mode, does not allow me to work in the wmi cli.
Comment: I've never worked with wmic inside a remoting session but everything it can do the Get-WmiObject (and related wmi cmdlets) can do as well. Give it a try.


How to Update a Row with an existing Row?

Question: I have a product table. I have some empty rows. I want to fill these rows with an existing row. For example, if I have
Product
-----------------------------------
ID   Name  Desc  ---------------
1     A     A1   ---------------
2     B     B1   ---------------
3     C     C1   ---------------

I want to copy all the items of ID=1 into ID = 3 row.
Tried this but getting error, Ambigious
UPDATE [Products]
SET DP.[Name] = SP.Name
    ,DP.[Desc] = SP.DESC
FROM    [Products] DP
       INNER JOIN [Products] SP ON SP.ID = 3
WHERE DP.ID = 1

Comment: [What have **you** tried??](http://www.whathaveyoutried.com)
Comment: Duplicate - http://stackoverflow.com/questions/2334712/update-from-select-using-sql-server
Comment: @Thanks Deepak. I have seearched but havent found any
Comment: please post the complete error. it might contain hints about what the problem was with the query
Comment: The [`MERGE` statement](http://technet.microsoft.com/en-us/library/bb510625.aspx) in SQL Server 2008 and later is great for bulk updates.
Comment: @pete can you give an example how to do the above with Merge statement
Answer: You need to use alias - either DP or SP in UPDATE and not Products itself because it's ambiguous between the two.
UPDATE DP
SET DP.[Name] = SP.Name
    ,DP.[Desc] = SP.[DESC]
FROM    [Products] DP
INNER JOIN [Products] SP ON SP.ID = 3
WHERE DP.ID = 1


Error 504 Gateway timeout

Question: I would like to know if an error 504 Gateway timeout always come from the load balancer or it can also be originated from Apache and the PHP code it's running ?
Thanks
Answer: It usually happens when the load balancer is waiting for a response from apache and apache is not giving a response within the timeout period of load balancer. So it returns a 504 gateway timeout. About what causes apache to not respond is something only you can say as you have not given much background information on what apache is serving. Look at apache logs to know more details . usually access logs and error logs. Increase the timeout value of loadbalancer, to see if it helps. It is always good to have clustering on apache so you dont get 504 because of a dead apache instance. I think mod_proxy allows you to achieve software clustering. I am not sure check out on apache site.
Answer: Usually from balancing because Apache(mod_php) or PHP(FastCGI) down or busy.
Answer: Sure it can be from php. If php script is in some loop and wont 'spit' out the content connection will eventually time out and balancer will report gateway timeout.
That 'loop' does not necessarily need to be loop, it can be waiting on connection to some service to read data from like mysql/memcache or something...
Comment: Not entirely true, @ooshro, PHP can set headers with header().. but I'm not entirely sure that's appropriate in this instance.
Comment: The OP says " from Apache and the PHP code it's running" Assuming some kind of mechanism between apache and PHP.  One that is capable of handling header()
Comment: You're wrong. PHP it's not web-server and can't send any HTTP response.
Comment: @Tom You're wrong. PHP need use socket to send any network message. header() need mod_php, CGI or FastCGI.

Error 504 Gateway timeout


NativeScript - How to receive custom file content from other apps

Question: I want to create a couple of file extensions that can be used y my app such as:.coin.mrh,.key.mrh.,.tkn.mrh.
The files will contain JSON content. My questions are:
How do I make my NativeScript App default app to open the files?
How do I handle the files?
Comment: This topic has been discussed in this StackOverflow thread - https://stackoverflow.com/questions/3465429/register-to-be-default-app-for-custom-file-type
Answer: Are u asking can a file be opened by extantion type ??
Comment: This is not an answer.


Como remover mascara no Delphi de um MaskEdit

Question: Estou precisando remover o ponto e o traço de um MaskEdit no Delphi.
A mascara é ##.###-#
Answer: Se você estiver montando a máscara assim: ##.###-##;1;_

Quer dizer que ele está salvando os caracteres literalmente.
Para impedir isso, utilize o zero no lugar do 1, assim: ##.###-##;0;_

Dessa forma apenas os números serão considerados.


Mysql: if condition not gives unexpected value for float value

Question: My mysql query is like this
select if(brand_name="royal", b.multiplier, 1) as multiplier from brand;

my database have below record
brand_name = royal,
multiplier = 1.06 (type: float(5,2))

in result multiplier value should be 1.06 but it give value in result as : 1.0599999427795
Please can you tell me how I can resolve this issue ?
Comment: Isn't that how floats work? If you want a decimal, use a decimal !?!
Answer: This is just the way floats behave:

The correct solution is to use DECIMAL(M, D) datatype.
Answer: if you want to fix the decimal point value, need to change type of multiplier from float -> decimal

Then use this code
SELECT IF( brand_name =  "apple", multiplier, 1 ) AS multiplier
FROM stack
LIMIT 0 , 30


Error while hide-show functionality using javascript

Question: I am working on hide show functionality using JavaScript
but it occurring error on console for onclick function
I am not getting why this error occurring.
JAVASCRIPT CODE

<?php

echo $output;

?>

You are passing string inside your function but because of the missing quotes, It is reading those as HTML elements. Thats why, e is coming null.
Comment: if i adding line above it gives

Parse error: syntax error, unexpected T_STRING
Comment: See the whole code, which I am able to run successfully and it is working perfectly fine.
Comment: but i want to display HTML in php only like i have added code sample above
Comment: Got your point. See the updated code. If you have further issue, feel free to let me know.
Answer: Looks like the variable e is null. In other words there is no element in the dom with the id that you are passing to the function.
Answer: You forgot the quotes. Try this:
    onclick="showtabs('my_section','icon');"
Answer: I think you are not selecting id and id1 perfectly
var e = document.getElementById('id');   //check here
var flag = document.getElementById('id1');

Comment: because it takes parameter as string document.getElementById(elementID)  //elementID is string
Answer: just change the code of php of $output variable onclick=showtabs("my_section","icon") because you pass the id without double quats, So its react like object


Webrtc Remote video stream not working

Question: While setting the remoteDescription , I am getting below error in firefox  :
DOMException [InvalidStateError: "Cannot set remote offer in state have-local-offer"
code: 11
nsresult: 0x8053000b
location: http://localhost:8080/resources/assets/js/test-online.js:111]
Please find below my test-online.js code
var localVideo;
var remoteVideo;
var peerConnection;
var serverConnection;
var peerConnectionConfig = {'iceServers': [{'url': 'stun:stun.services.mozilla.com'}, {'url': 'stun:stun.l.google.com:19302'}]};
pageReady();
var offerOptions = {
          offerToReceiveAudio: 1,
          offerToReceiveVideo: 1
        };

var sdpConstraints = {'mandatory': {
      'OfferToReceiveAudio':true,
      'OfferToReceiveVideo':true }};

function pageReady() {
    localVideo = document.getElementById('localVideo');
    remoteVideo = document.getElementById('remoteVideo');

    localVideo.addEventListener('loadedmetadata', function() {
          trace('Local video videoWidth: ' + this.videoWidth +
            'px,  videoHeight: ' + this.videoHeight + 'px');
    });

    remoteVideo.addEventListener('loadedmetadata', function() {
          trace('Remote video videoWidth: ' + this.videoWidth +
            'px,  videoHeight: ' + this.videoHeight + 'px');
    });

    remoteVideo.onresize = function() {
          trace('Remote video size changed to ' +
            remoteVideo.videoWidth + 'x' + remoteVideo.videoHeight);
          // We'll use the first onsize callback as an indication that video has started
          // playing out.
          if (startTime) {
            var elapsedTime = window.performance.now() - startTime;
            trace('Setup time: ' + elapsedTime.toFixed(3) + 'ms');
            startTime = null;
          }
    };

    serverConnection = new SockJS("/onlineHandler");

    serverConnection.onopen = function() {
        console.log("Opening server connection");
     };
     serverConnection.onmessage = gotMessageFromServer;
     serverConnection.onclose = function() {
         console.log("Closing server connection");
     };
   //serverConnection.onmessage = gotMessageFromServer;

    var constraints = {
        video: true,
        audio: true,
    };

    navigator.mediaDevices.getUserMedia(constraints)
      .then(getUserMediaSuccess)
      .catch(function(e) {
        alert('getUserMedia() error: ' + e.name);
      });
}

function getUserMediaSuccess(stream) {
      trace('Received local stream');
      localVideo.srcObject = stream;
      localStream = stream;
}

function start(isCaller) {
    trace('Starting call');
      startTime = window.performance.now();
      var videoTracks = localStream.getVideoTracks();
      var audioTracks = localStream.getAudioTracks();
      if (videoTracks.length > 0) {
        trace('Using video device: ' + videoTracks[0].label);
      }
      if (audioTracks.length > 0) {
        trace('Using audio device: ' + audioTracks[0].label);
      }

    peerConnection = new RTCPeerConnection(peerConnectionConfig);
    peerConnection.onicecandidate = gotIceCandidate;
    peerConnection.oniceconnectionstatechange = onIceStateChange;
    peerConnection.onaddStream = gotRemoteStream;
    peerConnection.addStream(localStream);

    if(isCaller) {
        peerConnection.createOffer(gotDescription, errorHandler , offerOptions);
    }
}

function gotMessageFromServer(message) {
   /* if(!peerConnection) start(false);

    var signal = JSON.parse(message.data);
//    console.log("Got Message from server :" + message.data);
    if(signal.sdp) {;
        console.log("hi in sdp" + message.data);
        peerConnection.setRemoteDescription(new RTCSessionDescription(signal.sdp), function() {
            console.log("Creating answer :");
        if (peerConnection.remoteDescription.type == 'offer')
            peerConnection.createAnswer(gotDescription, errorHandler);
        }, errorHandler);
    } else if(signal.ice) {
        peerConnection.addIceCandidate(new RTCIceCandidate(signal.ice));
    }*/
    var signal = JSON.parse(message.data);
    if (signal.type === 'offer') {
        peerConnection.setRemoteDescription(new RTCSessionDescription(signal),doAnswer,errorHandler);
      } else if (signal.type === 'answer') {
          peerConnection.setRemoteDescription(new RTCSessionDescription(signal),doNothing, errorHandler);
      } else if (signal.type === 'candidate') {
        var candidate = new RTCIceCandidate({
          sdpMLineIndex:signal.label,
          candidate: signal.candidate
        });
        peerConnection.addIceCandidate(candidate);
      } else if (signal === 'bye' && isStarted) {
        handleRemoteHangup();
      }
}
function doNothing(){

}

function doAnswer() {
      console.log('Sending answer to peer.');
      peerConnection.createAnswer(gotDescription, errorHandler, sdpConstraints);
    }

function handleRemoteHangup() {
//  console.log('Session terminated.');
  // stop();
  // isInitiator = false;
}

function gotIceCandidate(event) {
    if(event.candidate != null) {

        var message ={
                  type: 'candidate',
                  label: event.candidate.sdpMLineIndex,
                  id: event.candidate.sdpMid,
                  candidate: event.candidate.candidate};

       // serverConnection.send(JSON.stringify({'ice': event.candidate}));
         serverConnection.send(JSON.stringify(message));
    }
}

function onIceStateChange(event) {
      if (peerConnection) {
        trace(' ICE state: ' + peerConnection.iceConnectionState);
        console.log('ICE state change event: ', event);
      }
    }

function gotDescription(description) {
   // trace('Offer from peerConnection\n' + description.sdp);
      description.sdp = preferOpus(description.sdp);
     // pc.setLocalDescription(description);
      console.log('setLocalAndSendMessage sending message' , description);
   // trace('peerConnection setLocalDescription start');
    peerConnection.setLocalDescription(
            description,
            function () {
                serverConnection.send(JSON.stringify(description));
            },
            onSetSessionDescriptionError
    );
}

function preferOpus(sdp) {
      var sdpLines = sdp.split('\r\n');
      var mLineIndex;
      // Search for m line.
      for (var i = 0; i < sdpLines.length; i++) {
          if (sdpLines[i].search('m=audio') !== -1) {
            mLineIndex = i;
            break;
          }
      }
      if (mLineIndex === null) {
        return sdp;
      }

      // If Opus is available, set it as the default in m line.
      for (i = 0; i < sdpLines.length; i++) {
        if (sdpLines[i].search('opus/48000') !== -1) {
          var opusPayload = extractSdp(sdpLines[i], /:(\d+) opus\/48000/i);
          if (opusPayload) {
            sdpLines[mLineIndex] = setDefaultCodec(sdpLines[mLineIndex], opusPayload);
          }
          break;
        }
      }

      // Remove CN in m line and sdp.
      sdpLines = removeCN(sdpLines, mLineIndex);

      sdp = sdpLines.join('\r\n');
      return sdp;
    }

    function extractSdp(sdpLine, pattern) {
      var result = sdpLine.match(pattern);
      return result && result.length === 2 ? result[1] : null;
    }

    // Set the selected codec to the first in m line.
    function setDefaultCodec(mLine, payload) {
      var elements = mLine.split(' ');
      var newLine = [];
      var index = 0;
      for (var i = 0; i < elements.length; i++) {
        if (index === 3) { // Format of media starts from the fourth.
          newLine[index++] = payload; // Put target payload to the first.
        }
        if (elements[i] !== payload) {
          newLine[index++] = elements[i];
        }
      }
      return newLine.join(' ');
    }

    // Strip CN from sdp before CN constraints is ready.
    function removeCN(sdpLines, mLineIndex) {
      var mLineElements = sdpLines[mLineIndex].split(' ');
      // Scan from end for the convenience of removing an item.
      for (var i = sdpLines.length-1; i >= 0; i--) {
        var payload = extractSdp(sdpLines[i], /a=rtpmap:(\d+) CN\/\d+/i);
        if (payload) {
          var cnPos = mLineElements.indexOf(payload);
          if (cnPos !== -1) {
            // Remove CN payload from m line.
            mLineElements.splice(cnPos, 1);
          }
          // Remove CN line in sdp
          sdpLines.splice(i, 1);
        }
      }

      sdpLines[mLineIndex] = mLineElements.join(' ');
      return sdpLines;
    }

function onSetSessionDescriptionError(error) {
  trace('Failed to set session description: ' + error.toString());
}

function gotRemoteStream(event) {
     remoteVideo.srcObject = event.stream;
     trace('Received remote stream');
}

function errorHandler(error) {
    console.log(error);
}

And my html code is below :
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<link
    href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css"
    rel="stylesheet">

    <meta name="robots" content="noindex,nofollow,nosnippet,noodp,noarchive">
    <meta name="keywords" content="JavaScript, WebRTC" />
    <meta name="description" content="WebRTC codelab" />
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1">

                <video id='localVideo' autoplay muted></video>
                <video id='remoteVideo' autoplay></video>

       <input type="button" id="start" onclick="start(true)" value="Start Video"></input>

I am not able to understand what I am doing wrong here.I am still a novice in webrtc field juts want to run this basic thing in my code.
Comment: Have you checked your browser version and type?
Comment: @NallaSrinivas My firefox version is 46.0a2 (2016-02-12)  and I am pretty sure that webrtc support starts way back in firefox  and  did you get chance to look into the above code and did you by change got something unusal with the code ?
Comment: You've commented out the call to `start(false)`, so I don't see how the receiver side creates a peer connection at all, so unless your signaling server is bouncing messages, I don't see how it gets far enough to produce that error. Also, which line is 111 exactly? The code sample seems a bit off when I count lines.
Comment: @jib Sorry for inconvenience, the line number 111 is  Inside gotMessageFromServer function  -> if (signal.type="offer") -> peerConnection.setRemoteDescription ......   line , where i try to set remoteDescription, then i got this error .
Comment: @jib And for making peerConnection ,I have a start button which calls start(isCaller) function in javascript and creates the connection and then offer is sent to server and then server sent offer back to all the clients and we got offer message in gotMessageFromServer and there i am facing the problem.
Comment: But does the recipient also have to press start before they can receive calls? That doesn't sound right. There needs to be a peer connection object on both ends (specifically, the code that's commented out seems important).
Comment: And since there's no sign of a peer connection on the receiving end here, I surmise that it's the sender-side peerConnection you're calling setRemoteDescription on with its own offer, which is consistent with the state error you're getting, since that peer connection already has an offer at that point (the same offer). This suggests that your signaling server may be bouncing messages back to the sender of the message, which is not what you want. Also, when you say "all the clients", note that WebRTC is not one-to-many, and there needs to be exactly one other peer in a connection.
Comment: Thanks @jib , Yes you are correct that I need to uncomment the peerConnection code and there seems to be a bug on my server side which i fixed and now its working . Although ,Now I have changed this code and started using sample code mentioned in here [link](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling).  And also the problem lies when i click twice the Send button which was not correct from my part . Now everything started working  :)
Answer: The offer-answer exchange is a state machine, and some methods are disallowed in certain states.
Calling setLocalDescription (or setRemoteDescription) changes the signaling state to "have-local-offer" (or "have-remote-offer").
At that point, it is the application's job to bring the state back to stable or closed, as described in the spec.
For instance, it is the application's responsibility to handle glare (which is where both sides send an offer at the same time).
There is also a bug in Firefox that it doesn't allow you to call createOffer or setLocalDescription again once in have-local-offer and vice versa for the answer (the little hoops in the state diagram in the spec linked above). But it doesn't sound from your error message like you're hitting that.
Comment: Thanks Jib for more insight, there was lot of confusion  while setting webrtc call as I was using different browsers , chrome ,firefox dev edition , firefox normal. It is quite a confusing stuff in webrtc regarding offers state.
Comment: I recommend using [adapter.js](https://github.com/webrtc/adapter) to smooth out differences from spec, though when it comes to offer/answer, things should work the same on the browsers you mention by now. If my answer was helpful, don't forget to vote up. :)
Comment: Thanks Jib ,yes it was helpful for realizing my mistakes :)

Webrtc Remote video stream not working


Give an example of function which is bounded on [a,b] but not Riemann integrable on [a.b].

Question: Unable to find the function which is bounded but not Riemann integrable.
Comment: Dirichlet's function is the classical example. Have you ever seen it?
Answer: You need a highly discontinuous function. The classical example is
$$
f(x)=\cases{0& if $x\in\Bbb Q$\\1& if $x\notin \Bbb Q$}
$$
Answer: Take any nice function, like $f(x) = 1$ or $f(x) = x$ and have it take different values on the irrationals. This almost always works for this type of thing. This is (AFAIK) what bothers people about the Riemann integral.
$$f(x) = 1$$ if $x$ is rational and $$f(x) = 0$$ otherwise.


Why effective number of parameters in K nearest neighbor is inversely proportional to K?

Question: ESLII states that
effective number of parameters in K nearest neighbor is inversely proportional to K. To get an idea why, note that if the neighborhood were not overlapping, there would be N/K neighborhoods and we would fit one parameter ( a mean) in each neighborhood.
My question :- what does it really mean when it states that we would fit one parameter in each neighborhood?
How does it( fitting one parameter per neighborhood) really work?
Any intuitive example will be appreciated, thank you!
Answer: At first glance, k-nearest neighbors has a single parameter, that is k, the number of neighbours to be included in deciding on the  majority-vote  predicted classification.
However, the effective number of parameters to be fit is not really k but  more like n/k. This  is  because  the  approach  effectively divides the  region spanned by the training set into approximately n/k parts and where each  part is governed by the majority vote classifier.
To form an analogy with a parameterised model (e.g. GLM) if you have a dataset of size n 50, a choice of k=25 for kNN results in an effective number of parameters of about 2 and is comparable in the extent of smoothing / degree of freedom to a linear regression fit with two coefficients.
P.S. For kNN, the effective number of parameters / the degree of complexity is known as Vapnik–Chervonenkis (VC) dimension.
Comment: This it not really an answer, you are basically repeating what is already said in ESLII a little bit more verbose.


How to create NSPopover programmatically

Question: i've didn't found some examples to create NSPopover dynamically instead using the Interface Builder.
Following code gives an exception, loaded nib, but no view is set:
NSViewController *controller = [[NSViewController alloc] initWithNibName:@"View"     bundle:nil];
NSPopover *popover = [[NSPopover alloc] init];
[popover setContentSize:NSMakeSize(100.0f, 100.0f)];
[popover setContentViewController:controller];
[popover setAnimates:YES];
[popover showRelativeToRect:[sender bounds] ofView:sender preferredEdge:NSMaxXEdge];
[popover release];
[controller release];

Here is the stack trace:
2011-10-22 12:00:16.804 Test[2020:707] -[NSViewController loadView] loaded the "View" nib    but no view was set.
2011-10-22 12:00:16.807 Test[2020:707] (
0   CoreFoundation                      0x00007fff87e10286 __exceptionPreprocess + 198
1   libobjc.A.dylib                     0x00007fff92f2cd5e objc_exception_throw + 43
2   CoreFoundation                      0x00007fff87e100ba +[NSException   raise:format:arguments:] + 106
3   CoreFoundation                      0x00007fff87e10044 +[NSException raise:format:] + 116
4   AppKit                              0x00007fff90951e21 -[NSViewController loadView] + 336
5   AppKit                              0x00007fff9094da8a -[NSViewController view] + 41
6   AppKit                              0x00007fff91065232 -[NSPopover showRelativeToRect:ofView:preferredEdge:] + 159
7   Test                                0x000000010000159a -[OITAppDelegate show:] + 570
8   CoreFoundation                      0x00007fff87dffa1d -[NSObject performSelector:withObject:] + 61
9   AppKit                              0x00007fff90924710 -[NSApplication sendAction:to:from:] + 139
10  AppKit                              0x00007fff90924642 -[NSControl sendAction:to:] + 88
11  AppKit                              0x00007fff9092456d -[NSCell _sendActionFrom:] + 137
12  AppKit                              0x00007fff90923a30 -[NSCell trackMouse:inRect:ofView:untilMouseUp:] + 2014
13  AppKit                              0x00007fff909a38e0 -[NSButtonCell trackMouse:inRect:ofView:untilMouseUp:] + 489
14  AppKit                              0x00007fff9092263a -[NSControl mouseDown:] + 786
15  AppKit                              0x00007fff908ed0e0 -[NSWindow sendEvent:] + 6306
16  AppKit                              0x00007fff9088568f -[NSApplication sendEvent:] + 5593
17  AppKit                              0x00007fff9081b682 -[NSApplication run] + 555
18  AppKit                              0x00007fff90a9a80c NSApplicationMain + 867
19  Test                                0x00000001000012f2 main + 34
20  Test                                0x00000001000012c4 start + 52
21  ???                                 0x0000000000000003 0x0 + 3

Answer: The problem is not in NSPopover; the exception is thrown by NSViewController, and it says that although nib load was successful, it's view property is still nil.
Open "View.nib" in Interface Builder and assign File Owner's view outlet to the view object that the controller is supposed to represent (NSViewContoller becomes the file owner when it loads a nib). This is done by Ctrl-dragging from File Owner icon to the view's icon, then choosing view from the list of outlets.
Comment: Thanks for the good answer to this old question.  A related question: how did you know that this exception related to failing to assign the *view* outlet, as opposed to something else -- say, failing to assign the popover's *contentViewController* outlet?
Comment: @MarkBernstein This exception with this message text is only raised when loading did not assign the `view` property.


If $f(x) = x^3 + 4x^2 + ax + 1$ is a monotonically decreasing function of $x$ in $(-2, -\frac{2}{3})$ then find $a$

Question: If  $f(x) =  x^3  + 4x^2  +  ax  + 1$ is a monotonically decreasing function of  $x$ in the largest possible interval$ (-2, -\frac{2}{3})$ then find $a$.
My work:
$$f'(x)=3x^2+8x+a$$
For it to be monotonically decreasing$$ f'(x)\lt 0$$
$$f'(x)=3x^2+8x+a \lt 0$$
$$D\lt0$$
$$64-12a\lt0$$
$$a\gt \frac{16}{3}$$
I am stuck here, what should I do next?
Comment: $f'(x)\leq 0$ in $(-2,-\frac{2}{3})$ and $f'(x)\geq 0$ in $(-\infty ,-2]\cup[-\frac{2}{3},+\infty )$.
Comment: It may be possible because question said largest possible interval of decreasing
Comment: Please tell me what information should I add to question
Comment: Try to find the largest possible interval within (-2, -2/3) ie find (d,e) and a where d > -2;e < -2/3;d <e; f'(d)=f'(e)=0.  Try to set up a function g (a) = e -d and find its maximum.
Comment: I am not able to understand what you are saying ?
Answer: We write that $f $ is decreasing on the interval $(d,e) \subset (-2,-2/3) $.
This means $f'(d) = 0$; $f'(e)=0$ and $f'(a)<0$ and $-2 \le d < e \le -2/3$
So $3d^2 + 8d + a = 0$.  Solve for $d $ in terms of $a$.  There will be 2 possible expressions but hopefully only one will satisfy $a > 16/3$ and $-2 \le d \le -2/3$.  Let's call this expression $d (a)$
Do the same thing for $e$ to get $e (a) $.
We want the maximum such interval.  I.e. $e (a)-d (a) $ is maximal.  So solve for $e'(a) - d'(a)=0$.  That will be the largest interval in which any such $f $ is decreasing.


What is standard .NET Core interface for deleting file?

Question: As far as I can see, there are three file providers in the .NET Core. now I want to delete a file, but there is no delete method in the IFileInfo interface.
What is the standard interface in the .NET Core to manipulate files? I want to delete or write a file etc.
Comment: Those providers are for ASP.Net to access file-system-like systems, not for general file IO.
Comment: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.delete?view=netframework-4.7.2  `File.Delete(path)` is available in .Net Core
Comment: You should explain what you really want. You mentioned in another comment that you want to access S3. Why not use the AWS SDK? Why do you want to create *another* abstration? What problem are you trying to solve?
Comment: @PanagiotisKanavos I should use IFileInfo because I can't directly inject AWS SDK in the ConfigureServices method of the ASP.NET Core
Comment: Cloud storage is *very* different from local file systems. There are no folders, the file prefix can affect performance (specifics varies by provider), paging can be unavoidable, versioning is provided out of the box.
Comment: @MRP add that to the question itself. Besides, why do you think you *can't* inject anything you want in ConfigureServices? It's just code. The AWS SDK already provided some mechanisms and a couple of days ago it released another version, with additional configuration providers
Answer: It's worth differentiating between ASP.NET Core and .NET Core. You linked to ASP.NET Core documentation for file providers, which are used to read files which might be virtual files within an assembly etc.
For plain file system access, use System.IO.File as you do in desktop .NET. That's been part of .NET Core since version 1. It allows files to be created, appended, read, deleted etc.
Comment: @MRP: At this point it's very unclear what you're trying to achieve. I'd suggest creating a new question with much more context. There simply isn't a general purpose file system interface in either .NET Core or ASP.NET Core as far as I'm aware. You could always create your own, potentially...
Comment: @MRP why do you need to add another abstraction? IFileInfo is only for reading. The AWS SDK for .NET Core provides its own abstractions and API. Cloud storage is *very* different from local file systems. There are no directories for example
Comment: yeah, you are right. I'm looking for ASP.NET Core. but I'm looking for an interface like IFileInfo. cos I'm going to write my own delete implementation.
Comment: The reason behind this is that I'm trying to implement Amazon S3 file provider. actually, I can't use System.IO.File
Comment: Thanks for your help, so I will deal with this issue with a custom extension method.


org.hibernate.exception.GenericJDBCException: could not execute statement in hibernate

Question: I am trying to use embeddable annotation to store different values in one object to be persisted in one table.
I have two classes:
userDetails:
package org.hibernet.src;
@Entity
@Table (name="UserDetails")
 public class userDetails {
 @Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int userId;
@Temporal(TemporalType.DATE)
private Date dob;
public Date getDob() {
    return dob;
}
public void setDob(Date dob) {
    this.dob = dob;
}
private String userName;
@Embedded
private Address address;

public Address getAddress() {
    return address;
}
public void setAddress(Address address) {
    this.address = address;
}
public int getUserId() {
    return userId;
}
public void setUserId(int userId) {
    this.userId = userId;
}
public String getUserName() {
    return userName;
}
public void setUserName(String userName) {
    this.userName = userName;
}

}

Address class which is embeddable class:
 @Embeddable

 public class Address {

@Column(nullable=true)
private String street;

@Column(nullable=true)
private String city;

 @Column(nullable=true)
 private String state;

public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
    return city;
}
 public void setCity(String city) {
    this.city = city;
 }
public String getState() {
return state;
}
public void setState(String state) {
    this.state = state;
}

}
this is my main class:
public static void main(String[] args) {

userDetails user = new userDetails();
Address add = new Address();

user.setUserName("Dipesh");
user.setDob(new Time(0));
add.setCity("vadodara");
add.setState("gujarat");
add.setStreet("raopura");

SessionFactory sessionfactory = new
 Configuration().configure().buildSessionFactory();
Session session = sessionfactory.openSession();
session.beginTransaction();
session.save(user);
session.save(add);
/*user = (userDetails)session.get(userDetails.class, 6);*/

session.getTransaction().commit();
session.close();

}

I was trying to store the data but it was showing:
   ERROR: Field 'pincode' doesn't have a default value
   Exception in thread "main" org.hibernate.exception.GenericJDBCException:
    could not execute statement

      at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at org.hibernate.test.userTest.main(userTest.java:36)
Caused by: java.sql.SQLException: Field 'pincode' doesn't have a default
value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1056)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3376)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3308)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1837)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1961)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2543)
at
    com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1737)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2022)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1940)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1925)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
... 22 more

I had pincode in my address but it was showing an error so i removed it but still it showing that error.
Please help me to solve it.
Answer: The table in your db has a field pincode for which you've not defined a default value and is not nullable. However, your entity has no mapping for that field and you are not sending a value  for this field. Thus, java.sql.SQLException: Field 'pincode' doesn't have a default
value
Comment: Using Embedded, you embed that Embeddable entity in your Entity class, which makes it add columns for the embedded entity in same table of your Entity class and there is no such persistable entity with a table mapped that corresponds to that Embeddable.
Comment: I dont have table named Address in my  database
Comment: I see that you're using  @Embeddable, missed that in the first reading. :P but your table does have a field pincode. Edited my answer.
Comment: I dont have anything in my userdetails table also
Comment: Please tell me where that pincode field is coming? The exception is propagated back from the DB.
Comment: I had that field in my address class but after showing an error on that field I had removed that field. now i dont have "pincode" word in my application. still it shows error on this
Comment: Check the definition of your table using MySQL CLI or WorkBench, you'll see a column 'pincode'. Either, make it nullable or provide a mapping for that column in your entity as suggested by @Rene Winkler in his anwer.
Comment: sorry!! I was cecking in different database. I have a column pincode in user_details. I have deleted it but now it is showing org.hibernate.MappingException: Unknown entity: org.hibernet.src.Address error
Comment: How is your hibernate configuration defined? Can you check it?
Comment: Look in your configuration -
1. if you are doing a scan by 'packagesToScan' then add the package of that Address enitty if not already there
2. If you are doing it by defining 'annotatedClasses' property then add a new value with the fully qualified name of that entity
Comment: I am using annotated classes and I have used fully qualified names of both of entities
Comment: Remove this line from your code

 session.save(add);
Comment: It is inside your main method
Comment: yess.... thanx a lot. I was stuck from last 2 hours. That was the error. I had `session.save(add)`  line in my main class. can you please explain what is the reason that we cant use that line?
Answer: 1) Adapt your entity that it includes the field "pincode"
@Entity
@Table (name="UserDetails")
public class userDetails {
...
@Column(name="pincode", columnDefinition="Number(10) default '34562'")
int pincode;
...

2) or alter the underlying table so that the pincode field has a default value:
 ALTER TABLE user_details MODIFY pincode NUMBER(10) NULL DEFAULT NULL;

Number(10) is just chosen as an example. Replace this by the variable type of pincode.
Comment: I do not have address table in my database because I want to embedd it with userdetails
Comment: my user_details table is empty
Comment: sorry!! I was cecking in different database. I have a column pincode in user_details. I have deleted it but now it is showing `org.hibernate.MappingException: Unknown entity: org.hibernet.src.Address` error
Comment: Have you configured the hibernate configuration fil? It must define the entity class:
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/72599/discussion-between-gotchha-and-rene-winkler).
Answer: I had same error as org.hibernate.exception.GenericJDBCException: could not execute statement where i forgot to initialize session factory.
Initializing(as follow) session factory resolved my issue.
@Autowired
private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}


How to change integral bounds from [a,b] to [c,d]?

Question: How can I change those bounds - using assigmnets of t=...:
$$\int_{0.5}^{1.5} e^{x^2} dx$$
To those bounds:
$$0.5\int_{-1}^{1} e^{-(1+0.5t)^2} dt$$
I've seen that if $x=1+0.5t$ it will work, but I don't know how to do it in general.
For example if next time my bounds were [a,b] and I needed the bounds to be [c,d] with some assignment
Comment: I've tried to clarify it now, edited
Answer: If your bounds are $[a,b]$ and you wish that your bounds were $[c,d]$, you can always make a linear change of variables as follows:

If your bounds of integration are $[a,b]$ and you  change variables $t(x) = \frac{x-a}{b-a}$, then the bounds of integration change to $[0,1]$. After all, you can confirm $t(a) = 0$ and $t(b)=1$.
If your bounds of integration are $[0,1]$ and you change variables $u(t) = (d-c)t + c$, then the bounds of integration change from $[0,1]$ to $[c,d]$. After all, $u(0) = c$ and $u(1)=d$.
Applying both of these changes, if your bounds of integration are $[a,b]$ and you wish they were $[c,d]$, you can change bounds using the formula:
$$y(x) = \frac{d-c}{b-a}(x-a) + c$$
This formula works in general, regardless of whether $a>b$ and so on.
In this specific case, your bounds are $[a,b] = [\frac{1}{2},\frac{3}{2}]$ and you wish they were $[c,d] = [-1, +1]$. According to this rule, the transformation you need is:

$$t(x) = \frac{d-c}{b-a}(x-a) + c = \frac{2}{1}(x-\frac{1}{2}) + (-1) = 2(x-1)$$
Comment: Great I liked the way to transform from [a,b] to [0,1] to [c,d]
Answer: let's say you want to compute $$\int_a^b f(x)dx$$
I understand that you want to transform the above integral into something of the form $$\int_c^d f(g(u))d(g(u))$$
using some change of variable $x = g(u)$
now how to choose $g$ ?
very simple
you just have to have $a = g(c)$ and $b = g(b)$
to simplify the computations choose $g$ to be a first order polynomial
$$g(x) = a_1x + a_0$$
so it only remains to determine $a_1$ and $a_2$
which is very simple because it only suffices to solve the following $2 \times 2$ system
$\begin{align}
a = a_1c + a_0 \\
b = a_1d + a_0 \\
\end{align}$
where $a_1$ and $a_0$ are the unknowns
Answer: You want to change $$\int_a^b e^{x^2}\,dx\mapsto\int_c^d e^{x^2}\,dx$$
We need $x\mapsto f(x)$ where $f(a)=c$, $f(b)=d$. Assuming $f$ is linear, $$f(x)=mx+k\\c=ma+k\\d=mb+k\\m=\frac{d-c}{b-a}\\k=d-\frac{d-c}{b-a}\cdot b=\frac{db-da-db+cb}{b-a}=\frac{bc-ad}{b-a}$$
So the change of variables you are after is $$t=f(x)=\frac{(d-c)x+bc-ad}{b-a}$$

In the example you gave, $f(x)$ simplifies to $t=2x-2$, or equivalently, $x=\frac{t+2}2=1+\frac t2$, as required.
Answer: Substitute $x=1+\frac t 2$....
Then $dx=\frac {dt} 2$
And  $-1 \le t \le 1$
$$\int_{\frac 1 2}^{ \frac 3 2}e^{x^2}dx=\frac 1 2 \int_{-1}^1 e^{(1+\frac t 2)^2}dt$$
Try to find the values of a,b in  $x=at+b$
Since you know that:
$$
\begin{cases}
\frac 1 2=a(-1)+b \\
 \frac 3 2=a(1)+b
\end{cases}
$$
Comment: I've seen this solution, but I don't know to to get to this solution myself. I would like to know how to do it in this case and in general case
Comment: I know how to change variables. But I didn't know how to reach $x=1+t/2$.
I still don't understand how to reach it.
And in other case, if I told you the bounds you need to achieve are [-1.93,92.3232], how would you do it?
I hope I clarified my question
Answer: In general, you have the range $x = a$ to $x = b$, and you want to find
$t = Px + Q$ so that $t$ will go from $c$ to $d$. In other words, you want
\begin{align}
Pa + Q &= c \\
Pb + Q &= d \\
\end{align}
and you need to find $P$ and $Q$. Then you'll do the substitution
$$
t  = Px + Q \\
dt = P ~ dx\\
\frac{1}{P} ~dt = dx
$$
So how do you find $P$ and $Q$? Remember that $a, b, c, d$ are known. So write
\begin{align}
Pa + Q &= c \\
Pb + Q &= d \\
\end{align}
Subtract to get:
\begin{align}
P(a-b) &= c-d \\
\end{align}
Solve for $P$:
\begin{align}
P &= \frac{c-d}{a-b}
\end{align}
And now take that (known) value of $P$ and use it in
$$
Q = c - Pa = c - \left( a \frac{c-d}{a-b} \right)
$$
to find $Q$.
And that's all you need to do!


Why are my prices showing up as unformatted (minor units) in a view on a search index?

Question: Bit of an odd one here, I am experimenting with the Search API, Search DB and Views. I have a view based on Commerce Products. The view works, along with most of it's facets (but that's another story).
I'm running into a strange issue. I have a view based on a search index using Search API and Search_DB. I have access to all the fields that I indexed, but price is presented as the unformatted price in minor units. It is pulled in as "Indexed Commerce Product Price>> Amount (Price >> Amount)"
The issue I'm having is that it's displaying price as 98,000 rather than $980
Why is the formatting changing? and what's the right way to pull that info into my search view? D-Commerce wants the prices in minor units for it's own internal formatting. I have a regular non-search view which has the correct price...
Answer: To start, if it's a Views view, check you field formatter within the view admin page.  You could also hook into it somehow (I'm not entirely sure how, possibly alter the query), to divide the price by 100, but only for formatting.
Comment: that's one answer, eventually resolved through UI change.


Spring Boot + CloudFoundry + Test Unit issue

Question: I want to make a Unit Test for my application. I am using Spring Boot and CloudFoundry.
When I start "Test File" without cloud connection then I get a mistake in my logs:
"Caused by: org.springframework.cloud.CloudException: No suitable cloud connector found"
I tried to use:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT, properties = {
        "spring.cloud.config.enabled:false" })

How I can exclude/off a cloud for an Unit test?
Thank you!
Comment: Did you find any solution?
Answer: I usually add @Profile("cloud") on CF-specific configurations. cloud profile will be automatically applied in CF env.
Comment: Thank you. But in my case I want to skip CF-specific configurations when Unit Test is started. Could you help me?
Answer: Is your app getting Spring Cloud Connectors via the Boot starter (e.g. org.springframework.boot:spring-boot-starter-cloud-connector), or do you have an explicit dependency on the Connectors libs (e.g. org.springframework.cloud:spring-cloud-spring-service-connector)?
If you are using the Boot starter, then the Cloud Connectors autoconfig should not be enabled unless the cloud Spring profile is active. Make sure that profile is not active when your tests are run.
If you want to explicitly disable Cloud Connectors autoconfig in your test, the proper syntax would be:
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT, properties = {
    "spring.cloud.enabled=false" })

Answer: This issue comes when running in a local environment
The problem in code
CloudConfig extends ApplicationCloudConfig {
        // local and cloud configuration code seperated with @Profile.
    }

Resolved Code
    class Config {
    //... some config code ...
        @Profile("cloud")
        static class CloudConfig extends  ApplicationCloudConfig {
        //cloud config related code
        }

        @Bean
        @Profile({"local"})
        public DataSource dataSource() {
          //data source config
        }
}