Primitive Roots mod a prime number

Question: I haven't fully wrapped my head around primitive roots yet and I have a question with them:
Let $p$ be an odd prime and $g$, $h$ be two primitive roots modulo $p$. Show that $gh$ is not a primitive root modulo $p$.
I think I'll need to use the fact that if $g$ is a primitive root modulo p then a reduced residue system modulo $p$ is $g$, $g^2$,..., $g^{p-1}$
Any help would be much appreciated!
Comment: Hint: since $h$ is non-zero mod $p$ it must be equal to $g^k$ for some positive integer $k$ (since $g$ is a primitive root).  Now try to deduce something about $k$ knowing that $h$ is a primitive root and $p$ is odd.  Can $g^{k+1}$ also be a primitive root?
Answer: Hint:
$$g^{(p-1)/2}\equiv h^{(p-1)/2}\equiv-1\pmod p$$
$$(gh)^{(p-1)/2}\equiv?$$
Comment: See https://math.stackexchange.com/questions/502089/prove-that-ap-1-2-equiv-1-mod-p-and-ap-1-2-equiv-1-mod-p
Comment: So (gh)$^{(p-1)/2}$ $\equiv$ 1 (mod p) , but how does that prove that gh is not a primitive root of mod p? I'm sorry, I've looked through the answers to the question you sent, which was very helpful, but I'm still having trouble connecting everything.
Comment: @vfantina, So, ord$_p(gh)\le\dfrac{p-1}2<p-1$
Answer: ANSWER AND COMMENT.-It is known that if $g$ is a primitive root modulo $p$ the other possible primitive roots are given by $g^n=h$ where $(n, \phi(p))=(n,p-1)=1$. Therefore if $$gh=g^{n+1}$$ is another primitive root, then $$(n+1,p-1)=1$$
It is not possible to have both
$$(n, p-1)=1\text{ and } (n+1,p-1)=1\space \space \text {(why?) }$$.
Example of searching another primitive root.
$3$ is a primitive root modulo $7$ and $\phi(7)=6$. Thus $3^5=5$ modulo $7$ is the only other p.r. because $2,3,4,6$ are not coprime with $6$ (exponent $1$ corresponds to the p. r. $3$ itself). There are just two primitive roots modulo $7$.

Primitive Roots mod a prime number


É possível converter um pseudocódigo para portugol?

Question: Estou com problemas pra decifrar as :← e as parte;
Para cont ← 0 Até 12 Faça
Leia Sexo
Leia Idade
    mGeral ← mGeral + Idade
     Se Sexo = "M" Então
      mHomem ← mHomem + Idade
       nHomem ← nHomem + 1
Senão
       mMulher ← mMulher + Idade
        nMulher ← nMulher + 1
Fim Se
          cont ← cont+1
Fim Para
           mGeral ← mGeral / 12
            mHomem ← mHomem / nHomem
             mMulher ← mMulher / nMulher

Programa IdadeSexo
Var mGeral, mHomem, nHomem, mMulher, nMulher, Idade, cont: Inteiro
Var Sexo: Texto
Início
mGeral ← 0
mHomem ← 0
mMulher ← 0
Para cont ← 0 Até 12 Faça
 Leia Sexo
 Leia Idade
 mGeral ← mGeral + Idade
 Se Sexo = "M" Então
 mHomem ← mHomem + Idade
nHomem ← nHomem + 1
 Senão
mMulher ← mMulher + Idade
nMulher ← nMulher + 1
Fim Se
 cont ← cont+1
Fim Para
mGeral ← mGeral / 12
mHomem ← mHomem / nHomem
mMulher ← mMulher / nMulher
Escreva "A média de idade geral do grupo é: " mGeral
Escreva "A média de idade das Mulheres do grupo é: " mMulher
Escreva "A média de idade dos Homens do grupo é: " mHomem
FIM.

Comment: Por favor, formate a pergunta de forma legível.
Comment: Seus títulos vem sendo bem ruins... Use-os para fazer uma descrição do ***exato problema*** que você tem.
Comment: Dica: reserve um tempinho pra ler a [help], acho que você está perigosamente próximo [disto](http://pt.stackoverflow.com/help/question-bans)...
Answer: ← Significa sinal de atribuição, ele precisa ser trocado por =
pseudo código:
mGeral ← mGeral + Idade

em portugol vira:
mGeral = mGeral + Idade

Comment: a parte de texto que uso como var posso usar oque? como pra número eu uso para inteiro ou real.
Comment: O `var` não precisa segundo o help do portugol studio, fica apenas, `tipo nome_da_variavel` ex: `inteiro idade`


Microsoft Universal Apps and Unit Testing, trouble with AppModel version

Question: I started a new Solution to try the Universal Apps.
To test my code I want to add a unit test project (windows phone 8.1), but if I do so I get this error message when I start a unit test:

Error : DEP0700 : Registration of the app failed. Windows cannot
  install package 808f4bed-6f93-48b9-9b63-071d68456607 because this
  package requires a higher Windows version. The package requested
  Windows version 6.3 with AppModel version 1, while the current Windows
  version is 6.3 with AppModel version 0. (0x80073cfd)

What does this AppModel version 1 and AppModel version 0 mean, and how can I fix this?
Or is there and another way to do unit tests in the context of Microsoft Universal Apps?
This is what my project structure looks like

Update
Windows Phone 8.1 Project + Windows Phone 8.1 Unit Test = don't work
Windows Phone 8 Project + Windows Phone 8 Unit Test = works
But I still don't have a clue how I can get the Windows Phone 8.1 to work.
btw my windows version (Windows 8.1 Update)
<code>PS C:\Windows\system32> [System.Environment]::OSVersion.Version

Major  Minor  Build  Revision
-----  -----  -----  --------
6      3      9600   0
</code>
Comment: I just tried the same and didn't have any issues.  Make sure you are using the 512MB emulator - the other's don't work for me because I don't have Hyper-V enabled properly or something.
Comment: Do you get this when trying to run via R#?
Comment: Judging by the number of upvotes, this is a common problem.  I'm experiencing exactly the same issue on a laptop, but another system runs just fine with a slightly earlier version of the codebase.  I've added a few files and a reference to MVVMLight PCL, but removing that reference didn't help.
Comment: Do you have resharper installed? if you do "normaly" it should allow be able to run your unite tests for you. Resharper-> Unite Tests -> Run Unite Tests (CRT+U,R)
Comment: FWIW I have unit tests running just fine in my universal app. I don't know the error message you're seeing though.
Answer: On
Universal Windows App msdn site
I see following note:

Note  These samples require Windows 8.1 and Microsoft Visual Studio
  2013 with Microsoft Visual Studio 2013 Update 2 or later. They don't
  compile in Microsoft Visual Studio 2012 for Windows 8

I checked my own current Visual Studio Installation 'About' page and see that I have VST 2013 Update 1.
Maybe you have to explicitly update your Visual Studio version, it doesn't seem to happen by default.
I also checked the Microsoft Visual Studio 2013 Update 2 download page and that explicitly states

It includes tools for Windows Phone 8.1 development.
Answer: It seems like this is not a problem of Visual Studio, but rather Resharper or some other tools, which want to make unit testing easier.
In my example, see this context menu screenshot. I always used the "run unit tests" command in the lower part, which resulted in the error message. Using the upper ones starts the emulator fine and runs the unit tests on the platform.


Installed Android Emulator (HAXM) on Azure VM

Question: We have one VM at Azure cloud. We want to run the android emulator in android studio and we are using Android Studio(3.5) for development purposes.
But while we try to install HAXM to run the android emulator on the android studio I'm facing the error:
Answer: VTx is the Intel Virtualization Extensions for running virtualized workloads.  Microsoft use Hyper-V as their hypervisor, on top of which you create virtual machines.  HAXM / Android Emulator is a hypervisor itself and so what your trying to achieve is known as nested virtualization.
In order to use nested virtualization you need to select a VM size which supports it, such as D3_v3.
Please refer to this article for detailed instructions and considerations:
https://learn.microsoft.com/en-gb/azure/virtual-machines/windows/nested-virtualization
NOTE: You don't need to install Hyper-V.  The article is written for using nested Hyper-V.
Comment: Thanks, please see that i am already using Standard D3 v2 (4 vcpus, 14 GiB memory) size on Azure, Further, i have removed the HYPER-v feature.Still facing error.
Comment: The v2 D-series doesn't support nesting.  `***Size:*** D1_v2 - D15_v2 ***ACU/vCPU:*** 210 - 250 ***Ratio:*** 1:1` It's missing the three asterisks.  Try the D4_v3 instead.  It should be cheaper too.


Como distribuir o espaçamento das colunas de uma table responsiva igualmente?

Question: Como posso distribuir o espaçamento das colunas igualmente de uma tabela usando CSS?
Ex:

    Nome
    Email
    Telefone

Answer: Você pode utilizar a propriedade table-layout: fixed

table {
  width: 100%;
  table-layout: fixed;
}

table td {
  border: 1px solid #000;
}

    Nome
    Email
    Telefone

Comment: Acho que você consegue elaborar bem mais essa resposta colocando exemplos dela funcionando.
Comment: Coloque um exemplo na sua pergunta assim como na resposta.
Comment: Código de exemplo adicionado conforme solicitado.


Express.js and connect-mongo session duration

Question: I use express.session with connect-mongo to store user sessions.
I set cookie maxAge to 2 weeks from now, but what I want is that if the user is active within those 2 weeks, the session extends to another 2 weeks, so that when he is inactive for 2 weeks his session gets deleted (both the cookie and the session in mongo).
But the problem is that the session gets updated in MongoDB when he visits a page, but the cookie will expire in 2 weeks and won't change it's 'expires'.
This is my code:
app.use(express.session({
  secret: 'superSecretKey',
  cookie: {maxAge: 3600000*24*14},
  store: new MongoStore({
    mongoose_connection: mongoose.connections[0],
    db: 'myDb'
  })
}));

How can I achieve what I want?
Thanks!
Comment: See [this answer](http://stackoverflow.com/a/14529888/893780) on how to achieve that. Apart from that, `maxAge` should be set to a number of milliseconds in the future at which the session will expire, and not a date (that's what `expires` is for). So use this: `maxAge : 3600000*24*14` to set the expiry to two weeks.
Comment: Thanks! I also found this on https://github.com/senchalabs/connect/issues/670. And yeah, I always mix up expires and maxAge, I edited the question and posted an answer
Answer: I finally solved it, you have to use a middleware to update any data in the session so that the cookie gets resend, just like this:
app.use(function(req, res, next) {
  req.session._garbage = Date();
  req.session.touch();
  next();
});

This way maxAge will update both on the cookie and on the session on every request to the app.
Comment: I want to do a similar thing, but for say 2 hours. Do I simply set the `maxAge` as in your original question and then put this `app.use` in the config ?
Comment: req.session.regenerate(callback) does not work for you ?


Dependency injection php website

Question: The more I read about dependency injection the more I get confused. I know what it is for, that is not the problem. Trying to do some design on paper this is what I came up with and somehow it seems to me I am overlooking something.
First I imagined building an actual server that would accept incoming requests and returns responses to the user.
<code>class Server {
  private $responseBuilder;

  public function __construct($responseBuilder) {
    $this->responseBuilder = $responseBuilder;
  }

  public function run() {
    // create socket, receive request
    $response = $this->responsebuilder->build($request);
    // send response
  }
}

class Response {
  private $method;
  private $message;
  private $url;

  // getters & setters
}

class ServerBuilder {
   public build() {
      // construction logic
      return new Server(new ResponseBuilder());
   }
}
</code>
Since Apache is used to handle server requests we could replace the server with something that just send the response.
<code>$bldr = new ResponseBuilder();
$response = $bldr->build();
// send response some way
</code>
Note that ResponseBuilder has direct access to the request ($_SERVER['..'])
and so it has everything it needs to choose the right response.
PHP however allows us to build and send responses inline. So we could have a Controller object for each page or something else that send the response and have a builder for that.
<code>$bldr = new ControllerBuilder();
$controller = $bldr->build();
$controller->run();

class ExampleController implements Controller {
    public function run() {
       header("HTTP/1.1 404 Not Found");
       echo 'sorry, page not found';
    }
}
</code>

This all makes sense to me. But let's look at the server example again.
It calls $responseBuilder->build() and gets a response back. But this would mean that the builder (or other builders if we split it) is also responsible for anything else that might occur like authenticating a user, writing to the database,... and I can't get my head around the fact that writing to a database would be part of the object graph construction.
It would be like: Send me your request. Oh you want the homepage? I will build you your response and while I'm at it I will also do some things that have nothing to do with building it like logging what I just did and saving some of your data in a cookie and sending a mail to the administrator that you are the first visitor on this page ever, ...
Comment: Let me get this right, you want to use this as a backend. Send requests to it with any data, find the page matching the data, and display it?
Comment: Isn't everything in php the backend? Anyway. This how I see it. Since it is the web there is in theory no use for setters since everything can be injected in the constructor. The main purpose of an incoming http request is to give back some html. Dependency injection is used to assemble the html by using Builders or Factories that inject everything in the constructors. But during the assembly some side effects must  be done like writing to a database and I don't believe that it is the task of a builder
Comment: Not really, You could use PHP to create the interface only( front end ), or you could use it to save things in a database or to handle model data (back end)
Comment: But isn't building an interface on the server still a backend job? Anyway yes, that is basically what I want. Getting an incoming http request, build the interface and send the http response.
My theoretical example would do this with buildResponse(). The question is where do the side effects belong. If not in the interface building process then where.
Answer: You should decouple them. You have a few assumptions that I think are a bit strange. Let's start with them.

The main purpose of an incoming http request is to give back some html

I have built PHP backends that only return JSON, instead of HTML. I had a really strong border between back and front end. I only used the backend to give me data from the database, or add/edit data in the databse. The front end was just a PHP script that would build the pages any way i wanted.

Since it is the web there is in theory no use for setters since
  everything can be injected in the constructor

You could use the constructor, but you don't have too. You can use setters. Dependency injection is actually just turning the flow around.
You are on the right track though. You want some class that is responsible for building your pages. So, make it only responsible for your building your pages, and take out the other responsibilities. Things like logging, authentication etc should be outside of that.
For instance if you want logging, you could have your builder create your page, and your logger could then listen to all the things your builder is doing (with the observer pattern for instance). So if your builder says: "i created the home page", you can log it with your logger, who is actually listening to your builder.
Authentication for instance should happen even before your builder starts. You don't want your builder to go to work if you can already figure out that a user is not supposed to be on a page. You could use a database for that, and whitelist any usertype/pagerequest combination.
Then for data handling, i would create a backend, that only handles requests that are supposed to give back data, or save it. The front end could then communicate to get it's content by pulling it.
I hope this clears up a few things, but I'll be happy to answer more indept questions.
Comment: In this case in would just return html but what I mean is that the main purpose is to return a response. Let it be html, a redirect, json, ... What this idea I've built my example.
Server gets request. Server builds response. Server returns response. And then I got confused because when it builds the response it could log.
But yes, I think I see the point of serverside backend and frontend seperation.
Comment: Well to really answer your question, obey the single responsibility principle as much as you can. This counts for classes, but also for functions. Once you find that a class is doing two things, create three classes out of it. Two for the two things it does, and the third to actually make sure both of them are given the data they need, and handle the data they're supposed too.
Comment: So what I could do is sort of like the input/output socket streams and inject them (tell don't ask principle) and let another class handle sending the response and not asking to build one and then return it (basically php echo).

This way I can have an object RequestHandler that can split its concerns. One path logs, another path sends the response.
Comment: Sounds like a decent solution.

Dependency injection php website


T-SQL multiple outer join with composite key

Question: I have two source views:
View1

-----------------------------------------------------
|  UserId  |  RoleId  |  Total1 (calculated value)  |
-----------------------------------------------------
|    1     |    21    |            9                |
-----------------------------------------------------
|    1     |    22    |            5                |
-----------------------------------------------------
|    2     |    21    |            7                |
-----------------------------------------------------
|    4     |    23    |            4                |
-----------------------------------------------------

View2

-----------------------------------------------------
|  UserId  |  RoleId  |  Total2 (calculated value)  |
-----------------------------------------------------
|    1     |    21    |            2                |
-----------------------------------------------------
|    1     |    24    |            1                |
-----------------------------------------------------
|    3     |    21    |            3                |
-----------------------------------------------------
|    4     |    21    |            4                |
-----------------------------------------------------

The preferred output is based on UserId AND RoleId equality:
---------------------------------------------
|  UserId  |  RoleId  |  Total1  |  Total2  |
---------------------------------------------
|    1     |    21    |     9    |    2     |
---------------------------------------------
|    1     |    22    |     5    |   NULL   |
---------------------------------------------
|    1     |    24    |    NULL  |    1     |
---------------------------------------------
|    2     |    21    |     7    |   NULL   |
---------------------------------------------
|    3     |    21    |    NULL  |    3     |
---------------------------------------------
|   ...    |    ...   |    ...   |   ...    |

As far I know I should use some type of OUTER JOINs - but how?
Answer: SELECT
  ISNULL(v1.UserID,v2.UserID) as UserID,
  ISNULL(v1.RoleID,v2.RoleID) as RoleID,
  v1.Total1 ,
  v2.Total2
FROM view1 v1
FULL OUTER JOIN view2 v2
 ON v1.UserID = v2.UserID
 AND v1.RoleID = v2.RoleID

Answer: Assuming there is only one matching row from each table, you would use a FULL OUTER JOIN:
SELECT COALESCE(v1.UserId, v2.UserId) AS UserId,
    COALESCE(v1.RoleId, v2.RoleId) AS RoleId,
    v1.Total1
    v2.Total2
FROM View1 v1
FULL OUTER JOIN View2 v2 ON v1.UserId = v2.UserId AND v1.RoleId = v2.RoleId

Alternatively, you can use a UNION and SUM the results, particularly useful if the rows are non-unique for each table and the join would produce duplication:
SELECT UserId, RoleId, SUM(Total1) AS Total1, SUM(Total2) AS Total2
FROM
(
    SELECT UserId, RoleId, Total1, NULL AS Total2
    FROM View1
    UNION ALL
    SELECT UserId, RoleId, NULL AS Total1, Total2
    FROM View2
) Combined
GROUP BY UserId, RoleId

Comment: +1 for the full outer join; most of the solutions I saw are union-based
Comment: I'm in a strange situation: both solution works perfectly. I tried EricZ's first so he'll get the point but thank you too, really. and of course +1.


Using old pc keyboard key-mapings on MAC oS

Question: All in all "I want my ubuntu shortcuts on MAC OS X"
I am on mac os for the first time and I really miss my old keyboard.
So I decided to get the old pc keyboard and use it instead of MAC OS keyboard.
The first step was to change the key mappings
https://i.stack.imgur.com/eqvE0.png
No problem here, but the problem arises when for example I want to override COMAND+TAB to use ALT + TAB instead.
Is there any good tutorial for this kind of things ?
Next thing I hate a lot is my page up , page down, home and end button does not work properly.
Next how do you do fast movement in text ?
For example in ubuntu you can press CTRL + LEFT/RIGHT and you can jump between words very fast...
Next when I press the end button I want to go to the end of line not to end of document, CTRL + END should go to end of document...
and so on and so on...
Does anybody else straggle with these things ?
Does anybody have an solution for this ?
Answer: I use Karabiner for keymapping on OSX, works like a charm:
https://pqrs.org/osx/karabiner/
Comment: Is it safe to use third party software ? I mean is it checked if it sends some key(typing) log to some server ?


Percorrer um vetor até determinado número de índices e formar uma lista com os valores

Question: Possuo o seguinte vetor:
a = [10, 10, 10, 10, 10, 20, 20, 20, 20, 20]

Preciso que a cada 5 índices ele forme uma lista com esses elementos.
Ficaria com a seguinte aparência:
b = [(10, 10, 10, 10, 10), (20, 20, 20, 20, 20)]

Acredito que seja algo simples, mas não estou conseguindo executar.
Alguém poderia me ajudar?
Comment: deixe o código para vermos
Comment: Não possuo código, apenas o vetor indicado a = [10, 10, 10, 10, 10, 20, 20, 20, 20, 20]
Answer: Uma alternativa, veja funcionando aqui.
a = [10, 10, 10, 10, 10, 20, 20, 20, 20, 20]
b = []
t =[] # Temporario

i = 1
for numero in a:
  t.append(numero)
  if i == 5:
    i = 0 # Volta a contagem do zero
    b.append(tuple(t))
    t = [] # Limpa
  i += 1 # Incrementa +1

print(b)

Comment: Muito Obrigado! É o que eu preciso.


Implement using only XOR gates F=A'B'C'D+A'B'CD'+A'BC'D'+A'BCD+AB'CD

Question: How can we implement the function:
F=A'B'C'D+A'B'CD'+A'BC'D'+A'BCD+AB'CD
without simplifying it and using ONLY XOR gates (not using AND/OR gates) ? NOT gates are usable too, since they can be implemented from an XOR and an entry with the value "1".
Answer: You can't.
Hint: XOR is associative and commutative, so every function you can implement using XOR (and the constant "1") only is equivalent to one in a particular canonical form.
This leaves very few functions that can be so expressed. Besides the special cases of the constant "0" and "1" functions, each of them is true for exactly half of the $2^4$ possible combinations of truth values for the four inputs. But the function you're trying to express here doesn't have that property.
Comment: I thought about it being impossible too, but since our teacher asked us to do it, I supposed she was right.


passing id of a nested resource for deleting a file in rails

Question: I have a listing with many photos. So I am using a nested resource. But the issue now am facing is that I am unable to delete a single photo. I can see that its because the photo id is nil.
Here is my photos_controller
class PhotosController < ApplicationController

  before_action :set_listing

  def index
    @photos = @listing.photos.all

  end

  def create
    @photo = @listing.photos.new(photo_params)
    if @photo.save
      respond_to do |format|
        format.js
      end
    end
  end

  def destroy
    @photo = @listing.photos.find(params[:id])
    @photo.destroy
    redirect_to photos_url, notice: 'Photo was successfully destroyed.'
  end

  private

  def set_listing
    @listing = Listing.find(params[:listing_id])
  end

  def photo_params
    params.require(:photo).permit(:image, :remove_image)
  end
end

routes.rb
 resources :listings do
    resources :photos, only: [:index, :create, :destroy]
   end

In my index page I have a div to display the images via partial
index.html.erb
create.html.erb
$("#photos div").append("<%= j render(@photo) %>")

Here is my photo partial
_photo.html.erb

                <%= image_tag photo.image_url(:thumb) %>

            <%= link_to "#", remote: true, method: :delete, data: {confirm: "Are you sure?"} do %>

                <% end %>

In the _photo.html.erb I also tried
<%= link_to listing_photo_path(photo.id), remote: true, method: :delete, data: {confirm: "Are you sure?"} do %>

But am getting this error while loading the index page

No route matches {:action=>"destroy", :controller=>"photos", :id=>nil,
  :listing_id=>1} missing required keys: [:id]

All photos do have id and can easily delete it if I hardcode the id for photos. Can someone tell me what am doing wrong here?
Answer: You should also provide your Listing id, as you have nested resources:
<%= link_to listing_photo_path(@listing, photo) # etc. %>

or simply:
<%= link_to [@listing, photo] # etc %>

Answer: When you have a nested resource in you route, like you have, there will be two levels of identifying ids as follow:
resources :listings do
  resources :photos, only: [:index, :create, :destroy]
end

a typical url for the nested photo (if you check rake routes) will be as follow:
/listings/:listing_id/photos/:id

Which means that you need to provide upto two identifiers(listing_id and id-which is the photo id)
so, in your link to the destroy method, all you need to do is include this as follow:
<%= link_to listing_photo_path(listing_id: @listing.id, id: photo.id), remote: true, method: :delete, data: {confirm: "Are you sure?"} do %>

Comment: worked...Thanks mate. I thought about it before but I saw that its already getting the listing_id correctly..so I didnt passed that..


MySQL 8 - Error log into Syslog

Question: i'am trying to switch /var/log/mysql/error.log into syslog in MySQL 8. Reason is compatibility with our monitoring for parse, maybe not that clean, but it does the job. I had no problem with this on mysql <=5.7
I followed man page https://dev.mysql.com/doc/refman/8.0/en/error-log-syslog.html and it start showing some start/stop messages, but still not quite I want to accomplished.
The log file /var/log/mysql/error.log is still the only log which show errors like these, which I would like to have in syslog:
2018-08-10T13:53:50.927165Z 1 [ERROR] [MY-012574] [InnoDB] InnoDB: Unable to lock ./ibdata1 error: 11
2018-08-10T13:54:06.285066Z 0 [Warning] [MY-011070] [Server] 'Disabling symbolic links using --skip-symbolic-links (or equivalent) is the default. Consider not using this option as it' is deprecated and will be removed in a future release.

I tried a lot of thing by now, even start mysqld_safe as root.
Please dont advise adding syslog under [mysqld], this setting is removed in 8.0.13 (next build)
In cnf I have only add /etc/mysql/mysql.conf.d/mysqld.cnf:
log_error_services  = 'log_sink_syseventlog'

Mysql version is mysql-community-server 8.0.12-1debian9
Any ideas?
Answer: If this is debian 9 its running systemd right? So the output would be going to the journal (The mysqld stderr will be going to the journal). Look at /proc/{mysqldpid}/fd and look where stdout/stderror go to. If so, journalctl should be able to access the mysql error log.
Comment: It is debian 9, but it does not run systemd.
Comment: `/proc/{mysqldpid}/fd` and looking at the 1 and 2 symlinks is where your error log is.

MySQL 8 - Error log into Syslog


What is the difference between inbound and out bound ip address

Question: I started learning azure one month back. We have created a app service on azure. for a app service there are two types of ip addresses generated one is Inbound and another one is outbound. Can someone please explain me why two ip address and where we can use those.
I know the same concept applies for almost every cloud based services like AWS .
Do  correct me if i am wrong.
Answer: The inbound IP address would be used as the target of anyone wishing to connect to your app.
Though in an App Service you cannot connect directly with just the IP address, a Host header is required to locate the app, since the address is shared.
So if you want to configure a hostname in DNS, like yourcompany.com, you could make an A record that points yourcompany.com to the inbound IP address.
That will then allow people to connect to yourcompany.com.
The outbound addresses are what other devices/services would see if your app makes an outbound network call (calls another API etc.).
There is a set of them and they are all shared by other apps, your app will use one of them on each connection.
As I understand the reason there is a set of outbound addresses is to allow more simultaneous connections as each connection takes a port where it receives the responses.
And there is a limited amount of ports per address.
Comment: In Azure there is also a way how to set one static outbound IP using load balancer. Here is some manual (not checked deeply but you can google far more materials about that) https://samcogan.com/obtaining-a-static-outbound-ip-from-an-azure-virtual-network/


How to solve $\ln x+x=1$

Question: How can I solve this equation:
$$\ln x+x=1$$
We had it on a local Olympiad math contest problem.
Comment: On a related note, see the [Lambert W function](https://en.wikipedia.org/wiki/Lambert_W_function).
Answer: $1$ is a solution, just substitute and check.
$x+\log(x)$ is strictly increasing, hence 1 to 1. Thus, $x=1$ is the only solution for the equation
Comment: @user144251 No, and I actually consider myself not good at all in hard math contests such as IMO
Comment: thanks, did you ever have math contest training?
Comment: @user144251 See the book " The Art and Craft of Problem solving"
Comment: Thanks, I will definitely check it!
Answer: Intuitively
\begin{align}
\ln x+x&=1\\
\ln x+x\ln e&=1\\
\ln x+\ln e^x&=1\\
\ln (xe^x)&=1\\
xe^x&=e^1\\
xe^x&=1\cdot e^1
\end{align}
By comparing LHS and RHS, we will obtain $x=1$.
Comment: @user144251 "That was so obvious!!". Is that a compliment or what?
Comment: That was so obvious!! DId you had a formal maths contest training?
Comment: @user144251 No! Why did you ask that?
Comment: Because I want to participate in an IMO and I want some advice!
Answer: $$\ln x+x=1\implies xe^x = e$$
In other words we need to find a root of $f(x)=xe^x - e$
This function is increasing for $x\gt-1$ thus will have at most one solution in $(-1,\infty)$.
Also since $e^x\gt0$ we must have $x\gt0$.
Now it is easy to see that the one root we need is $x=1$

How to solve $\ln x+x=1$


Will IIS always be installed as fully patched?

Question: When I install Internet Information Server on a Windows machine that is fully patched according to Windows Update, will it be installed as patched right from the start?
I have always wondered if any patching inconsistencies could arise from the fact that all available patches (some of which might affect IIS) are marked as installed, but at the point in time they were installed IIS was not on the system and the files they would have affected were not there.
Answer: No, IIS will be at the level of your installation source.  Your system does not download updates it does not think it needs.
Comment: @Tomalak: You will probably have already installed various .NET updates, but no IIS specific updates.
Comment: So you run Windows Update manually immediately after changing the selected active Windows components to pick up any (now) missing patches.
Comment: @Richard: Does that mean there are no patches that affect IIS and something else, and may be downloaded to patch that "other thing" even though there is no IIS installed?
Comment: @Tomalak IME where multiple things (version, system components) each need a patch for a vulnerability, you need to apply multiple patches. I cannot recall any exceptions (which doesn't mean it hasn't happened). E.g. consider recent ASP.NET security patch: some systems here needed three patches to cover all the installed bits.


Proving the existence of the limit of a multivariate function

Question: It is possible to show that the limit $$ \lim_{(x,y)\to (0,0)} \frac{\sqrt{x^2+y^2}}{|x|+|y|^{\frac{1}{3}}} $$ doesn't exist by approaching the origin in two different ways: along the $x$-axis the limit equals 1, but along the $y$-axis the limit equals 0.
However if I suppose that $\lim_{(x,y)\to (0,0)} \frac{\sqrt{x^2+y^2}}{|x|+|y|^{\frac{1}{3}}}=0$ and use the definition of the limit of a function:
$$ \forall \varepsilon>0 \; \exists \delta : \forall(x,y) \in \mathbb{R}^2\setminus {(0,0)} \; \; |(x,y)|<\delta \implies \left|\frac{\sqrt{x^2+y^2}}{|x|+|y|^{\frac{1}{3}}} \right|<\varepsilon $$ I can set $\delta = \varepsilon (|x|+|y|^{\frac{1}{3}})$ and then by definition the limit equals $0$.
Comment: Your $\delta$ depends on $x, y$; if that was allowed every function would be continuous
Comment: If you approach along the x-axis, the limit is not 1. It simply doesn't exist.
Comment: @WindSoul It should be $1$ for $y=0$. Am'I wrong?
Comment: $\frac{\sqrt{x^2}}{|x|}=\frac x{|x|}=\pm 1$.
Comment: @WindSoul Isn't it $\frac{\sqrt{x^2}}{|x|}=\frac {|x|}{|x|}= 1$?
Comment: You're right. Sorry.
Answer: Note that $\delta$ can depend from $\varepsilon$ but not from $x$ and $y$, the "game" with the definition of limit is that:

we fix $\varepsilon$
then we find $\delta$
such that $\forall(x,y) \in \mathbb{R}^2\setminus {(0,0)} \; \; |(x,y)|<\delta \implies\,\ldots$

and at the third step $\delta$ is a fixed value depending solely on $\varepsilon$.
Refer also to

How to understand the definition of limit?


DNS MX configuration

Question: Can anybody confirm this would work ?
I have two MX-configured DNS records to handle smtp and pop. I'd like to implement a 'mailing list' server in another machine so:
Would it do any harm the fact that this third mail server has no user inboxes ?
Would the mails that it sent be acknowledged as valid by the receiving servers given it's ip/name is present as a MX record ?
Answer: You need Sender Policy Framework. The purpose of Sender Policy Framework (SPF) Text is to allow a mail server to validate that the sending mail server is authorized to send mail on behalf of a domain. Having an SPF record can reduce email fraud and forged email. There used to be an SPF Setup Wizard to generate a string. But it seams to be off line right now.
It might work again by the time you get to it, so here it is.
http://openspf.org
Answer: take a look at domain keys for this: http://en.wikipedia.org/wiki/DomainKeys
Your idea has major issue if your main mail servers are down, then all incoming mail would flow to 'mailing-list' server. In sendmail, we generally do masquerading domain and it works just fine.
Comment: Thanks for your repy, in this case I only have full control over this new third server, the two others - with the accounts - are outsourced.

DNS MX configuration


Matrix with same image and kernel

Question: Does exists a matrix A for which kernel of A is the same as the image of A?
Answer is True. But I couldn't find the example. I think I saw it from somewhere but I can't find it.  It was 2 by 2 matrix.
Comment: Look for a nonzero matrix such that $A^2=0$.
Answer: $$\begin{bmatrix} 0 & 1 \\ 0 & 0 \end{bmatrix}$$
Answer: Let $A = e_1 e_2^T$. Then $\ker A = \operatorname{sp} \{ e_1 \}$, and ${\cal R }(A) = \operatorname{sp} \{ e_1 \}$.
Note that since since $\dim {\cal R }(A) + \dim \ker A = n$, the dimension of the domain must be even.

Matrix with same image and kernel


Finding the limit of $\sqrt{4x^2+x+7}+2x$

Question: I've been working on this problem for a while now, but I can't solve it
$$\lim\limits_{x\to-\infty}{\sqrt{4x^2+x+7}+2x}$$
I've tried multiplying by
$$\frac{\sqrt{4x^2+x+7}-2x}{\sqrt{4x^2+x+7}-2x}$$
but I didn't get it.  Am I missing something really obvious?  Can someone help me with this question?
Answer: $$
\begin{aligned}
\lim_{x\to-\infty}\left(\sqrt{4x^2+x+7}+2x\right) &= \lim_{x\to-\infty}\frac{4x^2+x+7-4x^2}{\sqrt{4x^2+x+7}-2x}\\
& =\lim_{x\to-\infty}\frac{x+7}{\sqrt{4x^2+x+7}-2x}\\
&=\lim_{x\to-\infty}\frac{-1-\frac{7}{x}}{\sqrt{4+\frac{1}{x}+\frac{7}{x^2}}+2}\\
&=-\frac{1}{4}
\end{aligned}
$$
Comment: @NoLand'sMan, what do you mean? The square root is always non-negative.
Comment: How do you know that $\sqrt{4}$ isn't $-2$?
Comment: $(-2)^2$ is also $4$
Comment: @NoLand'sMan, I think you confuse solving a equation of the form $x^2=4$ with the definition of the square root function. Notice that $f(x)=x^2$ and $f(x)=\sqrt{x}$ are not the inverse of each other since they have different **definition domains**.
Answer: To find $\lim_{x \to -\infty} \frac  {x+7} {\sqrt {4x^{2}+x+7} -2x}$ divide the numerator and the denominator by $-x$. The limit is $-1/4$.
Answer: Hint: Multiplying by $\ \frac{\sqrt{4x^2+x+7}-2x}{\sqrt{4x^2+x+7}-2x}\ \left(=1\right)\ $ shows that
\begin{align}
\sqrt{4x^2+x+7}+2x&=\frac{x+7}{\sqrt{4x^2+x+7}-2x}\\
&=\frac{-1+\frac{7}{|x|}}{\sqrt{4-\frac{1}{|x|}+ \frac{7}{x^2}}+2}\ \ \text{for }\ x<0\ .
\end{align}
Can you see what the limit of this last expression is?
Answer: \begin{gather*}
\lim _{x\rightarrow -\infty }\sqrt{4x^{2} +x+7} -2x\ =\ \lim _{x\rightarrow -\infty }\sqrt{4x^{2}( 1+\frac{x}{4x^{2}} +\frac{7}{4x^{2}}} -2x\ =\ \ \\
\lim _{x\rightarrow -\infty } 2x\sqrt{( 1+\frac{1}{4x} +\frac{7}{4x^{2}}} -2x\ \ Apply\ Binomial\ theorem\\
\lim _{x\rightarrow -\infty } 2x\left( 1+\frac{1}{8x} +\frac{7}{8x^{2}}\right) -2x\ =\ \frac{1}{4}\\
\end{gather*}
Comment: I think you mean $-\frac14$
Answer: Set $x=-\dfrac1h,\implies h\to0^+$
$$\sqrt{4x^2+x+7}=\sqrt{\dfrac{4-h+7h^2}{h^2}}=\dfrac{\sqrt{4-h+7h^2}}h$$
So, we need $$\lim_{h\to0^+}\dfrac{\sqrt{4-h+7h^2}-2}h=\lim_{h\to0^+}\dfrac{4-h+7h^2-2^2}{h(\sqrt{4-h+7h^2}+2)}=\dfrac{-1}{\sqrt4+2}$$
Answer: $$L=\lim_{x \rightarrow \infty} \sqrt{4x^2+x+7}+2x$$
$$\implies L= \lim_{x \rightarrow -\infty} |2x| \sqrt{1+\frac{1}{4x}+\frac{7}{4x^2}}+2x$$
$$\implies L=-2x\left(1+\frac{1}{8x}+\frac{7}{8x^2}+..+O(1/x^2)\right)+2x$$
$$L=-\frac{1}{4}.$$


Define a relation $\mathbb{R}^2$ by $(a,b) \sim (c,d)$ iff $b−a = d−c$. Show that $\sim$ is an equivalence relation.

Question: In order to be an equivalence relation, it has to be reflexive, symmetric, and transitive.
Comment: Please show us your working or let us know what is causing you a problem if you want help/explanations
Comment: Adapt https://math.stackexchange.com/a/4044792/589
Comment: So.... show it is reflexive, symmetric, and transitive.
Comment: So do you know what reflexive, symmetric and transitive mean.  Can you write the conditions in terms of the writing $b-a=d-c$?  That is Reflixive $\implies$ for any $(a,b)$ that $(a,b)\sim(a,b)\implies b-a = b-a$.  Can you always say that $b-a = b=a$.  If you can actually write out these sentences is it *literally* impossible not to prove it is an equivalence relationship.  Literally.
Comment: Welcome to MSE! In a sense, reflexivity, symmetry and transitivity are all "inherited" from the respective properties of equality (via which your relation is defined). In fact, it's not hard to prove the following generalization of your exercise: for any function $f$ the relation defined as $a\sim b$ if and only if $f(a) = f(b)$ is an equivalence relation.
Comment: Thank all so much! Was a bit confuse on the transitive point, I will be clearer next question. Took this from book word for word.
Answer: So do you know what reflexive, symmetric and transitive mean?
Can you write the conditions in terms of the writing $b-a=d-c$?
Example: Reflixive $\implies$ for any $(a,b)$ that $(a,b)\sim(a,b)\implies b-a = b-a$.
Can you always say that $b-a = b-a$?[1]
DO the same for the definitions of symmetric and transitive.
If you can actually write out these sentences is it literally impossible not to prove it is an equivalence relationship[2].  Literally.
.....
[1]  Hint: Yes you can.  Everything is equal to itself so $b-a = b-a$.
[2]  It is impossible not to prove it.  You'll end up having to make claims like:  "$K = K;$" and "if $K = J$ then $J=K; $" or "If $K = J$ and $J = L$ then $K = L$" and, literally, you can't not have those be true.
Answer: Reflexivity:
We need $\forall (a,b) \in \mathbb{R}^2, (a,b) \sim (a,b)$, and we have $(a,b) \sim (a,b) \Leftrightarrow b - a = b - a$, which is true.
Symmetry:
We need $\forall (a,b), (c,d) \in \mathbb{R}^2, (a,b) \sim (c,d) \Rightarrow (c,d) \sim (a,b)$, and we have $(a,b) \sim (c,d) \Leftrightarrow b - a = d - c \Leftrightarrow d - c = b - a \Leftrightarrow (c,d) \sim (a,b)$.
Transitivity: We need $\forall (a,b), (c,d), (e,f) \in \mathbb{R}^2, \Big(\big((a,b) \sim (c,d)\big) \; \cap \big((c,d) \sim (e,f)\big)\Big) \Rightarrow \big((a,b) \sim (e,f)\big)$, and we have $(b - a = d - c) \cap (d - c = f - e) \Rightarrow b - a = f - e \Rightarrow (a,b) \sim (e,f)$
Comment: Thank you!! very clear now
Comment: Glad I could help


Accessing synchronized method in java

Question: Simple question but I'm not experienced with multithreading.
If two threads use the same synchronized method (in Java) and the first thread cannot access the method at given time (because the second one is using it), does the first thread wait (freeze) for some time and then tries to access it again, or does it just give up and don't access it at all?
Answer: The first method blocks and waits until it can use the method, as per the doc

When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

I'm not 100% sure if I remember correctly, but if memory serves me right the JVM does not give any guarantees as to the order in which threads will be able to acquire the lock after it's been released.
Comment: A good answer links to the documentation and puts a short, relevant quote answering the question, +1.
Comment: ^ Agree. Thanks for the answer. I've been on that page like 4 times today and I haven't noticed that bit. I must do less skim reading and more proper reading.
Also, I only have 2 threads, so order is not a problem.
Answer: Please, read the Java documentation.
https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html
Answer: It waits.
The JVM will not allow two threads to synchronize on the same object at the same time.  If one thread is already synchronized when a second thread attempts it, then the second thread will be put to sleep and added to a queue.
Whenever a thread releases a lock (i.e., when it exits from a synchronized method or block), the thread at the head of that lock's queue will be waked up, and then it will be allowed to lock the lock.
Comment: are you sure about your last sentence?
Comment: @assylias.  I could only find this in the JLS: "While the executing thread owns the lock, no other thread may acquire the lock."  One efficient and fair implementation of that requirement would use a queue-based lock that would behave as I described.  Other implementations, that might behave differently are allowed, but their behavior might be harder to explain to a noob, and the difference probably is not all that important at this stage in his education.

Accessing synchronized method in java


Como setar hostname em publicação asp net core 3.1 selfHosted

Question: Tenho um projeto funcionando o qual a preferencia de publicação é no formato de publicar para pasta auto hospedado (selfhosted) (sem usar o IIS). Motivo de ser assim: o objetivo é diminuir o trabalho/conhecimento de quem vai implantar, não precisando configurar nada a não ser copiar, colar e executar o .exe. Nesse formato, a publicação gera numa pasta publish todos os arquivos necessários e um .exe, que ao executar levanta o serviço. conforme a imagem a seguir:

Obs.: No mesmo servidor tem o IIS hospedando outros dois sites feitos com asp .net framework, inclusive já utilizando a porta 80 em ambos, porém cada um com seu hostname diferente. exemplo: um é demo.nossosite.com.br on *:80 e o outro é dev.nossosite.com.br on *:80.
Importante ressaltar que para o funcionamento do novo site (feito em asp .net core selfhosted) conforme a imagem anterior, só foi possível após parar os dois sites que utilizavam a porta 80.
Com os dois sites funcionando na tentativa de levantar o novo, ocorre um erro conforme imagem:

"crit: Microsoft.AspNetCore.Server.Kestrel[0]
Unable to start Kestrel.
System.Net.Sockets.SocketException (10013): Foi feita uma tentativa de acesso a
um soquete de uma maneira que é proibida pelas permissões de acesso."
No IIS, na lista de Sites, botão direito sobre qualquer site, opção "Associações", é possível fazer a configuração de qual hostname juntamente com a porta apontara para aquele determinado site selecionado.
Creio que o problema que estou enfrentando esta relacionado a essa ausência de configuração de hostname.
Meios que já tentei:

Em launchSettings.json attributo applicationUrl onde tinham citações de localhost troquei por sitenovo.nossosite.com.br
Em appsettings.json attributo AllowedHosts onde tinha apenas um "*" troquei por "sitenovo.nossosite.com.br"
Em Program.cs no metodo CreateHostBuilder usando .UseUrls() informando as urls correspondentes.

Parece que nenhum surte o mesmo efeito como seria a configuração de Associações feita no IIS citada anteriormente.
Antes que me indiquem: é só alterar a porta para outra porta diferente, para nosso cenário fica inviável, precisamos que seja na porta 80.
Alguém sabe como resolver isso/já passou por esse problema de precisar manter sites hospedados em IIS e ao mesmo tempo auto hospedados?
Comment: Você tem certeza que as duas aplicações não estavam com rotas diferentes? Por exemplo, "http://dev.nossosite.com.br:80/app1/xxxx" e "http://dev.nossosite.com.br:80/app2/xxxx"?
Answer: Você pode até fazer o binding de um dns host name para a sua aplicação, assim por exemplo:
var host = new WebHostBuilder()
.UseKestrel()
.UseUrls("http://dev.nossosite.com.br:80", "http://localhost:80")

Porém, não vai conseguir por mais de uma aplicação na mesma porta, na mesma máquina.
Isso é possível no IIS porque ele gerencia as requisições e faz os redirecionamentos corretos, já uma aplicação self hosted não é capas de fazer isso, porque, se tem duas app querendo fazer bind da mesma porta, quem vai gerenciar isso?
Tem que ser "alguém" além das duas (ou mais) apps para fazer isso, ai que entra o IIS ou outro servidor Web.


Confusion in fixed point iteration method

Question: Find a real root of equation $x^3+x^2-1=0$ in the interval [0,1] with an accuracy of $10^{-4}$.
Above is a problem from my mathematics class on numerical analysis.
Following is what I have tried:
$x^3+x^2-1=0 \implies x=\frac{1}{x^2+x}$ and using iteration formula $x_{n+1}=\phi(x_n)$ where
$\phi(x)=\frac{1}{x^2+x}$
Root is given to belong to [0,1], so as initial approximation I took $x_0=0.5$ and proceeded. But it is do not approach to the any point, it is not hard to see that the iteration is oscillating around 1.
What was done in class:
$\phi(x)=\frac{1}{\sqrt{x+1}}$, this worked.
My confusion:
The problem is to find a real root of $f(x)=0$,in fixed point iteration method we change $f(x)=0$ to $x=\phi(x)$ and then use the iteration formula $x_{n+1}=\phi(x_n)$.
What I have done in the problem, why that approach failed and why? And is there any criteria for choosing $\phi(x)$?
Answer: Or even more simple than looking at the derivative like in the other answer, you want an iteration that maps the interval $[0,1]$ into itself. However, with your map $x\mapsto \frac1{x+x^2}$, points close to $0$ are mapped to very large points far away from the interval. The given map $x\mapsto \frac1{\sqrt{1+x}}$ does not have this problem, it maps the interval into itself.
The fastest (relatively) simple fixed-point iteration for this equation is the Newton method for the "degree-balanced" function $f(x)=x^2+x-x^{-1}$,
$$
x_{+1}=g(x)=x-\frac{f(x)}{f'(x)}
=x-\frac{x^2+x-x^{-1}}{2x+1+x^{-2}}
=x\frac{x^3+2}{2x^3+x^2+1}
$$
It give the iteration sequence starting in the middle of the interval
<code> 0:  0.50000000000000000
 1:  0.70833333333333337
 2:  0.75407185204559835
 3:  0.75487746388872945
 4:  0.75487766624668007
 5:  0.75487766624669272
 6:  0.75487766624669272
</code>
Answer: For the function you've selected $\color{blue}{\phi'(x)  = -\frac{2x+1}{(x^2+x)^2}}$
and at $x_0 = 0.5$$ \ \phi'(x) = -3.5555\cdots$
But for the application of fixed point iteration method, you need $\color{blue}{|\phi'(x)|<1}$
Clearly the selected function doesn't satisfy the condition.

So take, $x^3 +x^2-1=0 \implies \phi(x) =x = (1-x^2)^{1/3}$
$$\phi'(x)=-\frac{2x}{3(1-x^2)^{2/3}}$$
This has a magnitude less than $1$ at the points of consideration.
Answer: A nice trick is to exploit the fact that $T_3(x)=4x^3-3x=\cos(3\arccos x)$, hence in locating the roots of $f(x)=x^3+x^2-1$ it is possible to enforce the substitution $x=\frac{\sqrt{3}}{2\cosh\theta}$ in order to get
$$ \frac{3\sqrt{3}}{8\cosh^3\theta}+\frac{3}{4\cosh^2\theta} = 1, $$
$$ 4\cosh^3\theta - 3\cosh\theta = \cosh(3\theta)= \frac{3\sqrt{3}}{2} $$
then
$$ \theta = \frac{1}{3}\operatorname{arccosh}\left(\frac{3\sqrt{3}}{2}\right) =\frac{1}{3}\log\left(\frac{\sqrt{27}+\sqrt{23}}{2}\right)$$
and
$$ x = \frac{\sqrt{3}}{\sqrt[3]{\frac{\sqrt{27}+\sqrt{23}}{2}}+\sqrt[3]{\frac{2}{\sqrt{27}+\sqrt{23}}}}\approx 0.75487766624669276.$$
There is a single real root since the stationary points of $f(x)$ occur at $x=0$ and $x=-\frac{2}{3}$ and both $f(0)$ and $f\left(-\frac{2}{3}\right)$ are negative. Such root belongs to $(0,1)$ since $f(0)f(1)<0$. Newton's method with starting point $x_0=1$ produces the following sequence of approximations, decreasing towards the actual zero:
$$ \frac{4}{5},\frac{333}{440},\frac{103913617}{137655540},\frac{137803872517532490480941}{182551264498284560927730},\ldots$$
Better approximations are produced by starting at $x_0=\frac{3}{4}$:
$$ \frac{77}{102},\frac{1289516}{1708245},\frac{12113936460107727037}{16047549161626557960},\ldots$$


SQL (Hive): using window functions while aggregating with GROUP BY

Question: I have the following table in Athena (Hive/Presto):
CREATE EXTERNAL TABLE tmp (
    id STRING,
    updated_at TIMESTAMP,
    location STRING,
    direction STRING
)
LOCATION 's3://path';

I need to aggregate and count on the id field and at the same time select location and direction that are relative to the latest timestamp within the group (partition again is on id).
So far I came up with the following query leveraging window functions first and group by after:
SELECT
    b.id,
    MAX(b.latest_location) AS "latest_location",  -- It seems it is not possible to use first_value() on GROUP BY
    MAX(b.latest_direction) AS "latest_direction",
    COUNT(*) AS "total"
FROM (
    SELECT
        a.id,
        first_value(a.location) OVER (PARTITION BY a.id ORDER BY a.updated_at DESC) AS "latest_location",
        first_value(a.direction) OVER (PARTITION BY a.id ORDER BY a.updated_at DESC) AS "latest_direction"
    FROM tmp a
) b
GROUP BY b.id;

I have first tried to do the group by aggregation and the window aggregation at the same time, but it seems that this is not allowed by the engine. Is it possible to write a more efficient query (maybe without the subquery)?
Comment: You do `select distinct` on the inner query and add `count(*) over (partition by a.id)`. It'll be shorter though I'm not sure that's going to change much internally regarding execution efficiency.
Answer: SELECT DISTINCT
    id,
    first_value(a.location)  OVER (PARTITION BY id ORDER BY updated_at DESC) AS latest_location,
    first_value(a.direction) OVER (PARTITION BY id ORDER BY updated_at DESC) AS latest_direction,
    count(*) OVER (PARTITION BY id) as total
FROM tmp

In your original query, max was basically a dummy aggregate as all the rows have the same value. And group by was essentially doing what the distinct does here.
Answer: adding to preferred answer -- consider being more formal with your window definition supporting DRY (Don't Repeat Yourself) preference:
    SELECT DISTINCT
    id,
    first_value(a.location)  OVER w AS latest_location,
    first_value(a.direction) OVER w AS latest_direction,
    count(*) OVER (PARTITION BY id) as total
    FROM tmp
    WINDOW w AS (PARTITION BY id ORDER BY updated_at DESC)

This will allow more complicated window definitions to be maintained exactly one place and guarantee that the same window logic is used for both column calculations.
Answer: You can mix window functions and aggregation functions . . . but in the other direction:  aggregation first, then window functions.
That said, your query should be much faster if you eliminate aggregation.  Just use row_number() and filtering:
SELECT a.id, a.location, a.updated_at
FROM (SELECT a.*,
             ROW_NUMBER() OVER (PARTITION BY a.id ORDER BY a.updated_at DESC) AS seqnum
      FROM tmp a
     ) a
WHERE seqnum = 1;


Have you ever seen anyone mention probability density function as a framework for neural network?

Question: I am evaluating a proposal pitch from a vendor about their machine learning solution. I do not have access to the source code or any other technical details about the algorithm they are using as it is their IP. But in the only technical side of PPT slides, they mention that they are using self learning neural network (actual text is given below). Initially this sounded like reinforcement learning to me. But in the very next line they mention the framework behind the solution and the big surprise to me was that they have mentioned 1) Probability Density Function and 2) Clustering. In the machine learning world, these two are not frameworks and this immediatedly makes me suspicious about the caliber of the vendor. Honestly I was expecting a deep learning framework like Pytorch or Tensorflow but PDF as frameworks is a big redflag for me about the technical knowledge of the vendor.
However, I could be wrong. So my question is:
Question: What would be your perception or first impression of a vendor who puts probability density function as the core a framework for something they claim to be a self-learning neural network?
Text from PPT slide

We use self-learning, to provide employers with the best
matching candidates to their open jobs. The AI is built on smart
neural networks that learn from the behaviors and activities of users
as well as employers' activities. The below are some of the frameworks
used in the backend in providing informative hiring decisions for
recruiters:

Probability Density Functions – the use of normal probability distributions, such as Gaussian distribution, which will help better
analyze the users' data in the system which will eventually cater to
the needs of each employer based on their history, peer vector
analysis, scoring modules and other technical information to provide
the best matching talent. This would help employers in their pipeline
building as well as in hiring their needs efficiently and in a timely
manner.
Comment: Regarding the edit, it's impossible to know definitively what they mean without more information. However, the slides were likely written by non-experts like sales & marketing folks. In particular, the phrase "the use of normal probability distributions, such as Gaussian distribution," indicates to me that this was not written by someone with even a stats 101-level understanding because a Gaussian distribution and a normal distribution are the same thing.
Comment: I have no way of knowing if this is what the vendor is doing, but one place PDFs may appear in neural networks is in constructing loss functions. See: https://stats.stackexchange.com/q/378274/22311
Comment: The pitch is likely made by marketing people - not by statisticians or machine learning experts. However, if the latter are the target audience, it is a serious failure... if the audience are non-experts, than mentioning probabilities and clustering is merely intended to demonstrate that there is some serious theory behind what they do (at least a real statistician or a computer scientist, rather than simply using sklearn.) Welcome to the real world! ;)
Comment: @Sycorax-OnStrike May be, but even if it were the case, it would be way too cryptic; I mean why mention it at all as your key framework especially when PDF is basically entry level statistics 101 is somethign I fail to understand
Comment: Yeah, agree that although PDF is indeed related to neural network, it is just too elementary to mention.
Answer: This is buzzwordery at its worst. How is a Gaussian used? Why a Gaussian and not some other distribution?
Then again, their pitch deck almost certainly was created not by the people with the actual statistical knowledge*, but by marketing and/or product management, and while PM typically has a little more technical understanding than marketing, that is emphatically not the same as statistical understanding. Their statistics may be absolutely fine, but have been garbled in a game of telephone in the production of these pitch slides. For all we know, the original incarnation of the slides may have been completely correct statistically, but it may have been "improved" by various layers in the bureaucracy for better "understanding" in the target group - which usually does not include statisticians.
Solution: ask. Ask the vendor for a call specifically with the statistical expert, and have a technical discussion with them.

*Source: long and painful experience in a large company creating a product with core statistical functionality, which is then sold to customers with possibly less statistical understanding.
Answer: I would read the text provided on the slide as follows:

Either they use some kind of probabilistic model. Such models are commonly used, there is nothing strange about it.
Alternatively, they use fancy language to say that they are using squared error to fit the model. This would be equivalent to using maximum likelihood with a Gaussian distribution, so "you can think of" the results as of fitting Gaussians to the data.

The description is however too vague to tell what it is exactly and definitely is not written by an expert in this area. From the description you simply cannot tell what is the model and if it makes sense or not.
Answering the question from your title, yes, it is pretty common to interpret neural networks in probabilistic terms. For example, Goodfellow et al (2016) in the classic handbook on deep learning says

Given features $h$, a layer of linear output units produces a vector
$\hat y = W^\top h + b$.
Linear output layers are often used to produce the mean of a conditional Gaussian distribution:
$$ p(y | X) = \mathcal{N}(y; \hat y, I) \tag{6.17} $$
Maximizing the log-likelihood is then equivalent to minimizing the mean squared error. [...]
Answer: I believe their method is to have a seperate encoder for user and item information. Each encoder outputs the mean and variance of a gaussian in an embedding space ("probability density function framework"). Then, they use wasserstein distance between users and items as a measure of similarity. Finally, they use some sort of representation learning loss formulation such as InfoNCE to fit the model ("self-learning"?)
Sounds similar to Probabilistic Metric Learning with Adaptive Margin for Top-K Recommendation (manuscript).


Linux host to host migration

Question: I need to migrate my CentOS server onto another with an identical system distribution. I don't know yet how different is hardware the besides amount of memory and GHz (posted separate question about that)
I've been compiling lot's of libraries by hand on my original server, installing them to standard location and did not keep a record :). (there is no one to fire me for this - I only lose time and money here and hopefully - learn something)
Migration will also involve moving user stuff, setting permissions, file ACLs. (here is question on moving user accounts, but there's nothing about facl)
Is there anything in the world that can help me re-create the beast on the new host?
Are there any tools that allow such migrations in a more orderly fashion? (preventive or more active tools)
Obviosuly I'm no sysadmin - but I hope to learn more. Thanks.
There was a similar question about migrating windows server - in my case it's linux.
Answer: The SystemRescueCD (http://www.sysresccd.org) now includes both partimage and fsarchiver.  Either of these can do a disk-to-disk, partition-to-partition, or disk-to-image-to-disk duplication (like Symantec Ghost).  fsarchiver is a bit newer and has some nicer features, but is commandline only.  partimage has a curses-based gui, has a few warts, and doesn't seem to be currently maintained, but still works well.  This will basically allow you to transfer a full disk image from the old disk to the new one.
If you are wanting to move your configs and data from the old server to a new clean one, you'll probably want anything you've edited in /etc, get dumps from any databases, and any other app data.  /etc/passwd, /etc/shadow, and /etc/group should transfer without too much trouble.  User homedirs should also transfer with relative ease.  If your ACLs are in ldap, I imagine you should be able to sync from one server to the other.  I don't know about facl, I've never looked at it.
If you are just doing the disk imaging method, you'll need to make sure the kernel from the old machine will work on the new one.  You may need to boot to a livecd (like the sysresccd) to modify and build it before it will boot.
Comment: thx. fortunately I can just try and if it fails ask the provider to re-image the box. I don't have physical access to the machines.
Answer: If the target disk is at least as big as the origin disk, then you can hook them both up on the same system. then do dd /dev/sda /dev/sdb, assuming sda is the origin and sdb is the target.
If not, then pop a live CD into the destination system and set up filesystems to be identical to how they are on the origin host. If the systems are on the same network and you trust that noone's going to snoop, then use FTP to copy every file onto the new host, otherwise use SFTP or SCP. One thing you're going to want to check is /etc/fstab to make sure that any disk labels mentioned can be referenced by label.
Answer: Normally I look at using either DD over Netcat or Partimage to image systems, but you left a comment saying that you don't have physical access to the box. This complicates things as you can't image anything without risking data inconsistency (unless you have all the data in a separate partition that can be unmounted).
One possibility is to try turning it into a virtual machine. The VMWare Converter will create an image of a running Linux system without any trouble (from when I converted a bulletin board system to a virtual machine on an ESXi system). I just had to adjust the network system (Ubuntu) after converting.
As a virtual machine, though, you get more flexibility in copying and re-deploying your system later on if you wish to do more with it down the road.
Answer: There's always the tried and true method of tarballing partitions, making partitions on the new box, starting up from a live disk on the new server, mounting partitions, scp'ing the tarballs, and untarring them on their new respective partitions.  Or if you're really feeling lucky, tar directly into ssh and untar on the fly on the other side.
Answer: I've been imaging desktops with Clonezilla, but there's absolutely nothing that would prevent it from working on any machine.
The trick would be to get either attached or network storage with enough space to hold the system image. If it were me, I would use an NFS on the local subnet to store the image.
The way the process works is that you power down the machine, and insert the Clonezilla Live CD (this is assuming you don't have a clonezilla server, which seems likely given that you wouldn't have asked the question if you had). Clonezilla boots and then gives you the option of selecting whether you want to image a partition or entire disk. You'll probably want to do entire disk, since the source and destination are identical. It will ask where you want to store the image, so select NFS server, and then it should set up the networking and ask for the server and directory. Give it that, and it will copy the image across the network to the NFS server.
When the time comes to image the new server, just do the same thing as before, except tell Clonezilla that you want to restore an image, and follow the instructions as above.
Answer: reimaging the server to the new hardware is definitely the way to go here, but before you do that, I would also run sys-unconfig. In short - it's a sysprep for RHEL derivative Linux distros.

Linux host to host migration


Differential of traders wealth function equals $0$. Correct?

Question: Calculating the differential of the trader's wealth function I get $dV_t \equiv 0$, which not only surprises me but also stops me from going forward with the current financial model I am looking at (I modified Kyle's model with information asymmetries).
Because I am already stuck over this for a while, I wanted to ask if I maybe did any calculation mistake. Simplified (without the information asymmetries which would only make it longer but not change the content) my financial model is the following:
Market makers use the signalling process
$$dY_t = a(Y_t)dX_t + b(Y_t)dt,$$
where $X_t = W_t + \theta_t$ is the cumulative demand of the noise traders ($W_t$ is a standard Brownian motion) and the individual trader (see below), and $a$ and $b$ are weight and drift functions respectively, in combination with $h$, a twice differentiable, strictly increasing function, to price a risky asset via $h(Y_t)$. In equilibrium, the price process is supposed to be a martingale. The risk neutral trader has a cumulative demand of
$$\theta_t = \int_0^t \alpha_s ds$$
where $\alpha$ is adapted to the traders filtration. Based on that, the trader's wealth at time $t$ can be described via
$$V_t = \int_0^t \theta_s dh(Y_s),$$
given that $V_0=0$ holds. If I now look at the differential $dV_t$ via Itô's lemma and use the definition of $\theta$, I get the following:
\begin{align}
dV_t &= \theta_t dh(Y_t) \\
&=\theta_t (h^\prime dY_t + \frac{1}{2}h^{\prime\prime}d\langle Y \rangle_t ) \\
&= \theta_t(h^\prime(adW_t + ad\theta_t + bdt) + \frac{1}{2}h^{\prime \prime} a^2 dt) \\
&= \alpha_t dt (h^\prime(adW_t + a \alpha_t dt + bdt) + \frac{1}{2}h^{\prime \prime} a^2 dt) \\
&= \alpha_t(h^\prime(adtdW_t + a \alpha_t dtdt + bdtdt) + \frac{1}{2}h^{\prime \prime} a^2 dtdt) \\
&= 0
\end{align}
where the last step follows from $dtdt = dtdW_t = 0$. Did I miss anything in my calculation? Thinking about it from a financial point of view, I interpret this result as no growth in the traders wealth which seems odd to me.
Already big thanks for any help and let me know if you need more information!
Answer: The mistake you make is replacing $\theta_t$ by $\alpha_t dt$ on line four and then trying to treat resultant terms like $dt dW_t$ as being the same as $d \langle \operatorname{Id},W \rangle_t$. To see this clearly, note that the same reasoning, if correct, would say that for a Brownian motion $W$,
$$ \int_0^t W_s ds = 0$$ since $W_s ds = 1 dW_s ds$. This is obviously false.
To see what's happened, it will help to write things out in integral notation. A term like $\theta_t h^\prime(Y_t) a(Y_t) dW_t$ really means $$\int_0^t \theta_s h^\prime(Y_s) a(Y_s) dW_s = \int_0^t \int_0^s \alpha_u h'(Y_s) a(Y_s)du dW_s.$$
Unfortunately, this integral does not cleanly split in to the product of two integrals and so we can not just cleanly take the covariation and apply the fact that $\langle \operatorname{Id},W \rangle = 0$. To treat e.g. $dtdW_t$ like $d \langle \operatorname{Id}, W \rangle_t$ you need $dtdW_t$ to mean a product of the two integrals and not an iterated integral like it does here.


Como espaçar o "título fixo" de uma página e as postagens?

Question: Durante a criação da página, resolvi colocar um "título" qual terá o nome do site e algumas abas para o usuário ser encaminhado; porém, ela sempre sobrepõe a primeira postagem:
Sendo que cada postagem é assim:

Usando PHP, CSS ou HTML, como posso fazer com que somente a primeira página do site tenha um recuo para não ser sobreposta por padrão?
[EDIT]
O meu problema foi resolvido, mas queria deixá-lo responsivo. Quando acessei o IP (o site) pelo meu celular, conforme eu aumentava o zoom, a barra de navegação ocupava mais espaço (ou seja, não havia como ler nada). Como posso fazer para arrumar isso?
Código:
html {
  background: url(images/bg.png) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

.navigationbar
{
    width: 100%;
    height: 5em;
    margin: 0 auto;
    background-image: linear-gradient(to right, black, darkgrey);
    position: fixed;
    top: 0%;
}

.navigationbar img
{
    margin: 0 auto;
    max-height: 100%;
    max-width: 100%
}

.navigationbar_spacer
{
    opacity: 100%;
    width: 100%;
    height: 5em;
}

.postagem
{
    padding: 1%;
    border-radius: 12px;
    width: 33%;
    margin:  auto auto;
    background-color:#edebed;
    margin-top: 1%;
}

.postagem div
{
    border-radius: 12px;
    background-color: #95bcf0;
    width: 75%;
    margin: auto auto;
}

.postagem h1
{
    font-family: "arial";
    font-size: 150%;
    font-weight: lighter;
    text-align: center;
    background-color:
}

.postagem p
{
    font-family: "book antiqua";
    font-size: 100%;
    text-align: justify;
    text-indent: 2em;
}

Comment: Chuto que esse "png test" esteja com `position: absolute; top: 0`. Tente colocar no body um `margin-top: 75px` ou o tamanho do "png test".
Comment: @Patrick ele esta com `margin: 0 auto; max-width: 100%; max-height: 100%`
Answer: Tal como diz @Patrick, uma vez que a sua navigation bar ou header vais estar sempre presente ao longo das suas páginas a forma mais segura será adicionar ao CSS do seu contentor onde os seus posts estão alojados uma margin-top: 50px;.
.header{
    width: 100%;
    height: 50px;
    position: fixed;
    top: 0;
    background-color: #ccc;
}

.container{
    width: 100%;
    height: 100%;
    color: #fff;
    background-color: #111;
    margin-top: 50px;
}

.sub-container{
    width: 100%;
    float: left;
}

Pode ver o JSFIDDLE e faça scroll no display para ver o seu título fixo
Para vários containers no site eu usaria a seguinte estrutura:

PNG TEST

Uma vez que a técnica do layout fluído é o uso extenso de percentagens nos CSS, basta colocar a altura da sua barra igualmente com percentagem:
.header{
    height: 5%;
}

NOTA: No entanto é desaconcelhado colocar percentagens em alturas (height)
Comment: Circle, o problema é que eu terei VÁRIOS containers ao longo do site, mas eu achei uma solução e vou postar aqui.
Comment: @Lucas resposta actualizada
Comment: Circle, estou com mais um probleminha que eu coloquei na pergunta (em EDIT). Você sabe como solucionar?
Comment: @Lucas, resposta actualizada
Comment: Obrigado Circle; e olha que sacanagem: o único que eu não havia utilizado porcentagem era o height. Vou adicionar o código atual caso alguem queira utilizar futuramente.
Comment: Fazendo o que você disse em ambas as divs, a navigation bar fica minúscula e o método que eu fiz não funciona.
Comment: Consegue criar um fiddle para analisar melhor a sua questão?
Comment: http://jsfiddle.net/mbq6d/
Comment: Vamos [continuar esta discussão no bate-papo](http://chat.stackexchange.com/rooms/15780/discussion-between-lucas-henrique-and-circle).
Answer: Você pode criar uma class no body de cada página, é algo bem utilizado, geralmente essa class é o nome da página.
sendo assim você consegue ter controle de qualquer elemento por página.
Exemplo:
.class-body .titulo{margin-bottom:20px;}

Assim você consegue controlar apenas em tal página, que isso pode acontecer
Por php é possivel pegar o nome da página atual aberta, você pode fazer uma condição pegando nome da página == 'voc digita a p^´agina que terá a alteração' dentro da condição pode chamar um css ou dar echo de brs que não é aconselhavel
Answer: O que parece é que esse seu "header" está com position fixed ou absolute com top setado para 0
De qualquer forma, seria assim o que eu faria
CSS
.header {
    width:100%;
    height:80px;
    background:#e1e1e1;
    margin-bottom:20px;
}

.post {
    width:50%;
    padding:10px;
    background:#e1e1e1;
    border-radius:10px;
    margin:0 auto;
}

Pode acompanhar o resultado nesta DEMO.
OBS.: utilizei valores fictícios pois não tenho seu código como referência.
Answer: Como ideia adicional, eu fiz uma div com as propriedades de tamanho equivalentes às da barra de navegação e opacidade máxima; ou seja, ela ocupa o mesmo espaço que a barra de navegação, e como as postagens tem identação por padrão, a div não fica colada com o texto. O código foi:

Tendo navigationbar_spacer as mesmas propriedades de tamanho que navigationbar, ou seja, navigationbar sobrepõe exatamente o mesmo tamanho que navigationbar_spacer tem.
Comment: Tenta explicar melhor com algum exemplo, eu não percebi nada do que fizeste.
Comment: @JorgeB. resposta editada


Derivative of 'inside' matrix in the squared Frobenius norm of a product of three matrices

Question: How does one approach finding $\nabla_X\|AXB\|_F^2$?
Normally I would expand to $\|AXB\|_F^2=\text{Trace}(B^TX^TA^TAXB)$ and rearrange using the cyclic property of traces to make $X$ the first and/or last matrix in the product, but this isn't possible here.
$A$ is wide and $B$ is tall; both are full-rank. $X$ is square. All matrices are real-valued.
Answer: Look up formula (116) in the Matrix Cookbook:
$$\frac{\partial}{\partial X}
\operatorname{tr}(
B^T X^T C X B
)    =
C^T X B B^T + C X B B^T$$
So, the answer is:
$$2 A^T A X B B^T$$
Answer: Use a colon as a convenient product notation for the trace
$$\eqalign{
A:B &= {\rm Tr}(A^TB) \\
A:A &= \big\|A\big\|^2_F \\
}$$
and, for typing convenience, define the matrix
$\;Y = AXB$.
Write the cost function in terms of this new variable, then calculate its differential and gradient.
$$\eqalign{
\phi &= \big\|Y\big\|^2_F = Y:Y \\
d\phi &= 2Y:dY = 2Y:A\,dX\,B = 2A^TYB^T:dX \\
\frac{\partial \phi}{\partial X} &= 2A^TYB^T = 2A^TAXBB^T \\
}$$


Related nodes by taxonomy term in a view block of drupal7

Question: I want to show related nodes to the current node in a block using taxonomy terms.
In my site say x is my taxonomy vocabulary and x1,x2,x3,x4,x5,x6 and x7 are the taxonomy terms under it. A node could be tagged with any of these taxonomy terms.
Say node T is tagged with x2 and x3.
node W tagged with x3, x1 and x5.
node c tagged with x2 and x6.
node R tagged with x2 and x7.
F tagged with x4,x6.
H tagged with X2,x5.
Now when the node T is displayed I want items having any of the taxonomy terms similar to the current node i.e. X2 or x3 but the priority should be x2 i.e. list all the related nodes with x2 as tag first and then only with x3. so in the above case i need related nodes in the order C R H W? How is it possible by using views in drupal 7?
Comment: Not sure how to do it with Views, but you can write a custom module: http://drupal.stackexchange.com/questions/32682/a-nice-way-to-build-a-related-content-algorithm
Comment: Possible duplicate of: http://drupal.stackexchange.com/questions/27844/how-to-create-a-list-of-similar-nodes-in-drupal-7-views-3
Comment: There's also this module: https://drupal.org/project/similarterms
Comment: Thanks for the reply @Beebee. I had to write a custom module and it worked.
Answer: There will be a significant amount of customization (in the form of a module) to get this done through views. I've created a sandbox module that you can install to get things working and so you can play around with it (see views.api.php in the views module).
Once enabled you should find a new contextual filter value called "The node whose taxonomies you want to relate". This contextual filter default will take the current node ID and return nids of nodes that share the same terms in vocabularies that you select. Therefore, please set the view display as a block.
If you need to know how to group by term using views, please see this answer.


Connect to Intersystems Cache DB via ODBC

Question: I'm trying to connect to an external data source within out intranet site. The database is Intersystems Cache. Our web-servers are running Cent OS 6.4, so I have setup the necessary unixODBC drivers to connect to it and this is successfully working. What I'm struggling to work out is how I access this data from within Drupal.
I know I could just call odbc_connect within my code, but this isn't the Drupal way. I also loose the benefits of Memcached etc.
Would it be possible to use PDO's ODBC driver, which I think Drupal uses anyway?
Thank you.
Comment: check this http://drupal.stackexchange.com/questions/73914/msaccess-to-sqlite-install-of-drupal-and-setup-custom-content-types
Answer: As @Bala said you want to try to install the PHP ODBC driver. Drupal does not use this driver by default (a drupal install may use MySQL, Postgres, or I believe MsSQL on install if those drivers are found by PHP).
Once the ODBC driver is installed for PDO, you can inform Drupal of your 2nd database by following the Multiple Databases Documentation. Bala linked you to a previous example I gave using ODBC to an MsAccess database file -- you're request is simply a different DBMS vendor. The same approach should work InterSystems Cache DB by following the concepts in the documentation page linked about.
Note that ODBC is a slow interface as its essentially a wrapper to your client Database. Its not as fast as a full native DBMS driver. Keep that in mind when querying and using your data.
Comment: Thank you for the pointers. I now successfully have PDO working with ODBC using native PHP, but I'm struggling to find the correct way of adding it to settings.php.
I have a DSN setup in odbc.ini so I can simply go $dbh = new PDO("odbc:CCMACDF"); and I'm connected. If I do the same in settings.php, only adding the driver = 'odbc:CCMACDF' key/value, it doesn't work.
Comment: The code posted above is showing the code used to test in native PHP to make sure PDO iss working outside Drupal. I use this within drupal: `db_set_active('CCMACDF'); db_query("SELECT * FROM dbo.iActivityCodeStat"); db_set_active();`. settings.php is `$databases['CCMACDF']['default'] = array(
 'driver' => 'odbc',
 'hostname' => '####',
 'namespace' => 'CCMA_STAT',
 'uid' => '####',
 'password' => '####',
);` but the error is `Failed opening required '/includes/database/odbc/database.inc'`
Comment: What do you mean "it doesn't work" in drupal you would use `db_set_active('YourDatabaseKey for ODBC'); $result = db_query('select FOO;');` not `$dbh = new PDO(...);`. How to _select_ the database connection to use and issue a query is in the documentation link I provided.


Solve the trigonometric equation: $\sin {3x} = 4 \sin^2 x$

Question: Solve the equation $\sin{3x} = 4 \sin^2 x$.
I tried to change the $\sin{3x}$ to $3\sin x\cos x$ then solve it, but I could not find the correct answer.
Comment: sin(3*x) = 3*cos(x)^2*sin(x) - sin(x)^3, not 3*sin(x)*cos(x).
Answer: Hint: We have $$\sin 3x = 3\sin x - 4\sin^3 x\neq 3\sin x\cos x$$
So you get (let $\sin x = \alpha$) $$3\alpha - 4\alpha^3 = 4\alpha^2 \iff 4\alpha^3 + 4\alpha^2 - 3\alpha = 0$$
Which is a simple cubic in $\alpha$. Find the roots of the cubic, back-substitute and find the corresponding values of $x$.
Comment: a good solution, but please edit your first equation to achieve the perfect answer. Thanks!
Comment: @Hathanhminh. I corrected the typo, thank you! :-)
Comment: Do csc^2 x equal to 1/sin^2 x?
Comment: @user255652 yes.
Answer: $\sin(3x)=\sin(2x+x)$
 thus we have:
$$\sin(2x)\cos(x)+\cos(2x)\sin(x)=4\sin^{2}(x)$$
$$2\sin(x)\cos^{2}(x)+(\cos^{2}(x)-\sin^{2}(x))\sin(x)=4\sin^{2}(x)$$
$$\sin(x)(1-\sin^{2}(x))+(1-2\sin^{2}x)\sin(x)=4\sin^{2}(x)$$
$$3\sin(x)-4\sin^{3}(x)=\sin^{2}(x)$$
$$3\sin(x)-4\sin^{3}(x)=\sin^{2}(x)$$
$$3\sin(x)-4\sin^{3}(x)-\sin^{2}(x)=0$$
$$\sin(x)(3-4\sin^{2}(x)-\sin^{2}(x))=0$$
Simply assign $\sin x=a$ then you get $a=6/8$ and $-9/8$ and $a=0$
$x=\sin^{-1}(6/8)$ or $\sin^{-1}(-9/8)$ or $sin^{-}(0)$
Comment: Here is my answer and there are no explanations, if you don't understand or you like to be explained clearer I am here to help!
Comment: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference and +1
Comment: It's a cubic, not a quadratic.
Comment: @ZainPatel yes a third solution also appears a=0, I will insert in the solution. Thanks!
Answer: Notice, $$\sin 3x=4\sin^2 x$$ $$\implies 3\sin x-4\sin^3x=4\sin^2 x$$ $$\implies 4\sin^3x+4\sin^2 x-3\sin x=0$$$$\implies \sin x(4\sin^2x+4\sin x-3)=0$$
$$\implies \sin x(2\sin x-1)(2\sin x+3)=0$$ As you have not mentioned any condition of the unknown value $x$ hence writing the general solution for $x$ as follows $$\implies \color{blue}{\sin x=0}\iff \color{blue}{x=n\pi} $$  $$\implies \color{blue}{2\sin x-1=0\ \text{or}\ \sin x=\frac{1}{2}\ or \ \sin x=\sin\frac{\pi}{6}}\iff \color{blue}{x=2n\pi+\frac{\pi}{6}} $$
$$or\ \color{blue}{\sin x=\sin\frac{5\pi}{6}}\iff \color{blue}{x=2n\pi+\frac{5\pi}{6}} $$
$$\implies \color{blue}{2\sin x+3=0\ \text{or}\ \sin x=\frac{-3}{2}}\iff \color{blue}{\sin x\neq \frac{-3}{2}} $$  Now, the complete general solution can be written as $$\color{blue}{x=[n\pi]\cup\left[2n\pi+\frac{\pi}{6}\right]\cup\left[2n\pi+\frac{5\pi}{6}\right]}$$
Where $\color{blue}{\text{n is any integer}}$
Comment: How is sin(3x) equal to 4sin^{2}(x)?
Comment: Kindly, notice $\sin 3x=3\sin x-4\sin^3 x$ it is not equal to $4\sin^2 x$ as you asked
Comment: More over a you have not mentioned any condition of the unknown value $x$ therefore I gave general solution that's it. Kindly observe all the steps carefully then you may find the solution
Comment: Sorry, I asked you the question, what am I thinking, yes you gave the general solution.


What should I do when I created a bounty on my own question and answered it myself?

Question: Ok so I've added a bounty to my own question and after a while I managed to fix it by myself.
Here's the question: Magento 1: unable to sort grid by custom attribute
Problem is Stackexchange tells me to assign the bounty to someone but the only answer different than mine is totally not helpful, has got negative score and it looks like the poster didn't read my question in details.
So I'm not sure about the action I should take in that case.
Comment: There are pages and pages of this question across the SE network. Did you try Googling this first?
Comment: Tbh, no I trusted the similar question suggestions and thought it would also like other meta network that's why I asked.
Comment: Ok. The search would only cover this meta, but in general I see no benefit in asking the same question on multiple site metas...
Answer: If you didn't get an answer that at least pointed you in the right direction, you should not award the bounty.
In this case, and since you cannot award the bounty to yourself, the bounty points are lost forever.
Comment: I'm fine with bounty points being "lost", but I find it annoying that when I land on my profile, I see a little 1 next to bounty. No way I can get rid of it apart from deleting the question (which would be dumb as what I've found is kinda interesting) ?
Comment: That 1 will go away tomorrow.
Comment: Ok great thanks for enlighting me


Find the following indefinite integral

Question: Let $n$ be a positive integer. Find a general expression for $$\int x^n\cos(x)~dx$$ None of the standard integration techniques or the standard tricks I've seen for difficult integrals seem to apply to this one. I guess it is some type of reduction, but how to get a closed form?
Answer: Use repeated integration by parts. Take the antiderivate of the cos(x) or sin(x)-function and differentiate the polynomial term. The degree decreases in each step.
Comment: The recursion can be unfolded to give you a "closed form".
Comment: This does not give a closed form, just a recursion. I'm looking for a closed for in the case when $n$ is a natural number since I ultimately want to investigate this integral when $n$ is an integer.
Comment: It shoulb be no problem to find the sum using my idea. Perhaps you have to distinguish some cases.
Answer: This integral is explicitly explained here.
Answer: Probably as you did, integrating twice by parts, you arrived to a simple recurrence relation between I(n) and I(n-2). You can check your results at
http://en.wikipedia.org/wiki/Integration_by_reduction_formulae
as mentioned by Spock.
In practice, it is always a good idea for this kind of integrals, to use the form using cos(x) and the form using sin(x).
These recurrence relations are sufficient for almost any purpose I know, but I agree, they do not give you closed forms ... which exist; however, I am not sure you would enjoy them since, for your integral, the result is
-x^(1 + n) (ExpIntegralE[-n, -I x] + ExpIntegralE[-n, I x]) / 2
Answer: http://en.wikipedia.org/wiki/List_of_integrals_of_trigonometric_functions#Integrands_involving_only_cosine can find the reduction formula and also the final result.

Find the following indefinite integral


What's the difference between a Layer 2 & Layer 3 switch

Question: What's the difference between a Layer 2 & Layer 3 switch?
I've always wondered and never needed to know until now.
Comment: See the related question (http://serverfault.com/questions/2219/what-should-i-pay-attention-to-when-im-buying-a-network-switch)
Answer: I will complete Zoredache's answer.
A L2 switch does switching only. This means that it uses MAC addresses to switch the packets from a port to the destination port (and only the destination port). It therefore maintains a MAC address table so that it can remember which ports have which MAC address associated.
A L3 switch also does switching exactly like a L2 switch. The L3 means that it has an identity from the L3 layer. Practically this means that a L3 switch is capable of having IP addresses and doing routing. For intra-VLAN communication, it uses the MAC address table. For extra-VLAN communication, it uses the IP routing table.
This is simple but you could say "Hey but my Cisco 2960 is a L2 switch and it has a VLAN interface with an IP !". You are perfectly right but that VLAN interface cannot be used for IP routing since the switch does not maintain an IP routing table.
Comment: If you've got a lot of L2 vlans, which overlay L3 subnets, then you needed something called a one armed router aka router on a stick.

Thus, if you had a lot of intra vlan traffic then this would be come the bottle neck. L3 switches can fulfil this job.

http://www.cisco-tips.com/cisco-router-on-a-stick-with-switch/

now, you can think of the layer 3 engine being integrated into the switch itself.
Comment: So if a L3 switch had two hosts on separate VLANs it could route between them rather than going through a router?
Comment: Possibly. Most with routing can. heck, my extreme networks summit supports all major dynamic routing protocols AND can be "split" into multiple logical routers if needed. Routing between VLAN's is the smallest part - and works REALLY nice. The bad side is th ecost of such a beast ;)
Answer: The layer 3 vs 2 refers to the OSI model.  A layer 3 switch supports routing.  A layer 2 switch only knows ethernet, you may be able to setup VLANs.
Comment: Adding to that a layer 2 switch normally does hardware routing. It basically sets up a hardware switch module based on bytes in the ethernet packet for "switching the packets according to route". So it is / can be a LOT more efficient than a normal software based router implementation. Some of those get pretty powerfull (looking at the direction of Extreme Networks).
Answer: Simply put, a layer 3 switch can forward packets between different networks like a router while layer 2 switches forward packets to different segments/or within a given network.
Answer: A switch can be thought of as a more powerful bridge and a less powerful router.
If a switch is configured to work only as a bridge, it is called a layer 2 switch.
If a switch is configured to work only as a router, it is called a layer 3 switch.
More often, a switch is configured to perform both these functions(layer2 as well as layer3):

Either together on the same ports(using Integrated Routing and Bridging, ie, IRB): If the DMAC in the incoming IP data packet is of the IRB interface, routing or layer 3 behavior is done.
Otherwise, the packet is bridged(layer 2 behavior) on all the same vlan ports.
Or, on separate sets of ports of the switch(some ports as L2 ports while some ports as L3 ports): A set of "x" ports on a switch may be configured as a bridge(and will bridge packets). While, another set of "y" ports may have IP addresses assigned to them and will act as router ports(routing received IP packets).
Comment: A switch configured as a bridge would be working at layer 1, not 2. A switch working only as a router would be a router, not a switch... though the difference is getting pedantic. Most switches can't operate at L3, and the DMAC isn't part of the IP header, but part of the Ethernet header.
Comment: As per Wikipedia page on this topic, ["bridge"](http://en.wikipedia.org/wiki/Bridging_(networking)) operates at layer 2. So, a switch configured as a "bridge" will be a layer 2 switch.

If you go through the data sheets of the different switches manufactured by Juniper Networks(eg, [ex8200](http://www.juniper.net/techpubs/en_US/junos12.1/information-products/pathway-pages/ex-series/index.html), ex6200, ex4200, ex4500, etc) or Cisco, you will find all the layer 3 functionality available(including routing protocols like rip, ospf, isis, bgp). So, most switches, these days, do operate at layer 3.
Comment: All IP packets passed over the Ethernet(among the intermediate hops) are encapsulated in Ethernet header. DMAC is present in the Ethernet header.
Even a "router" examines the DMAC to decide on whether to process/route the received IP packet or to "discard" it(if the DMAC in the Ethernet header does not match the MAC address of the interface on which the IP packet is received). So, a layer 3 switch behaves in the same way.
Answer: Layer 2 is generally hardware i.e. mac address "routing" or mac tables. Layer 3 has to do with ip's. Layer 3 devices are usually managed and they can create and route between vlans.
Comment: This isn't all necessarily true and has already been covered by previous answers.


can not find symbol class Builder

Question: Criei um projeto no Android Studio 1.0, Login Activity.
Fiz as seguintes mundanças:
No Build.gradle
compileSdkVersion 21
buildToolsVersion "21.1.1"

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:21.0.2'
compile 'com.google.android.gms:play-services:6.5.87'
compile 'com.google.android.gms:play-services-plus:6.5.+'
compile 'com.google.android.gms:play-services-identity:6.5.+'
compile files('libs/google-play-services.jar')
compile files('libs/android-support-v4.jar')
}

Tenho uma classe chamado LoginActivity.java e outra PlusBaseActivity.java
O classe PlusBaseActivity.java, apresenta o seguinte erro:
can not find symbol class Builder

Parte do codigo que contém o erro:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Initialize the PlusClient connection.
    // Scopes indicate the information about the user your application will be able to access.
    mPlusClient =
            new PlusClient.Builder(this, this, this).
                    setVisibleActivities("http://schemas.google.com/AddActivity", "http://schemas.google.com/CheckInActivity")
                    .setScopes(Scopes.PLUS_LOGIN,
                    Scopes.PLUS_ME).build();
}

Já pesquisei pela internet e ainda não encontrei a solução, alguma dica como resolver esse problema?
Comment: Outra sugestão é usar as depêndencias do **Google Play Services** e o **Support Library** via Gradle, e não com o jar. Use `compile 'com.android.support:support-v4:21.0.0'`, e no caso do **play-services** não está duplicando?
Answer: Pesquisei sobre o assunto, encontrei que PlusClient não é mais aprovada (deprecated), se mesmo assim ainda quiser usá-la, utilize uma versão anterior da API, desse jeito:
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:21.0.2'
    compile 'com.google.android.gms:play-services:6.1.71'
    compile 'com.android.support:support-v4:21.0.0'
}

Recomendo que você procure mais informações sobre a GoogleApiClient, pois ela é uma API unificada que permite a integração com os serviços do Google Play.
Referências
can not find symbol class Builder
New Client API Model in Google Play Services
Setting Up Google Play Services
Accessing Google APIs
Comment: Quem deu o downvote poderia se manifestar para que eu possa melhorar a resposta? E corrigir caso exista alguma falha nela!
Comment: Ainda vou testar as sugestões. Obrigado pelas dicas a todos

can not find symbol class Builder


Can I set up materialised views on oracle for a SQL Server table over sqllink?

Question: I have a table in a SQL Server database that needs to be visible to an oracle database. We have tried using a normal view over sqllink, but we are not able to create an onUpdate triggers on that view.
I have read that we can create the trigger if it is a materialised view, but is unable to find any information on whether it can be done across different databases. (all the example are for oracle to oracle tables)
Can someone tell me if it is possible? and what issues I might need to look out for if I used materialised views?
Thanks
Comment: Can you explain a bit more. You can read a SQL Server table from Oracle using a Database link. You can create a view in Oracle that does that. SQL Server isn't aware of the Oracle link, so it shouldn't prevent any triggers on the SQL Server end.
Comment: The main problem I am encountering is that the connection between Oracle and SQL Server does not allow it to be shared between connections.

My application uses multiple connections to connect to Oracle to query from the view (hence multiple connection over the database link, hence FAIL!)

So now, we are investigating if we can set up an "on update" trigger on the view (that links to the SQL Server table) to copy the records to another Oracle table. That way, we can query it to our hearts content without hitting the shared connection problem.
Comment: Plan was dropped as my engineer discovered some problems with the approach.

We were unable to create the view using fast refresh, meaning that the view will need to copy all the records over when needed, and we could not get the view to refresh on update or select, so we need to manually issue a view refresh statement.
Answer: I do something similar and ended up using Oracle's HS gateway to handle it. Created an MV based of tables or queries to establish a staging area in Oracle. Followed up with logic to meet requests.
Comment: Just out of curiosity, how did you get the materialized view to work over the separate databases?


Fundamental group of a quotient of $S^2 \times I$.

Question: Let $X=S^2 \times [0,1]$ and let Y be the quotient space obtained from X identifying each point $x\in S^2 \times \{1\}$ with its antipodal in $S^2 \times \{0\}$. How can I calculate $\pi_1 (Y)$?
All I have been able to do so far is draw some loops in Y, based at the north pole of $S^2 \times \{1\}$ and passing through both poles of $S^2 \times \{1\}$. They do not seem to be homotopic, but I just don't know if there are relations between them, neither if there are more loops.
Comment: Do you know the Seifert-van Kampen Theorem?
Comment: Sure. Maybe I should have asked for suggestions of division spaces
Comment: It seems that you can write down the universal cover explicitly. It seems that there is a two to one cover from $S^2 \times S^1$ to $Y$.
Comment: Oh, I would be very thankful for hints towards a solution using the Seifert-van Kampen Theorem, since I'm still not familiar with covering spaces.
Answer: Note that if you can write down your complex in a cellular form, then the fundamental group will have generators given by the 1-cells and relations given by the 2-cells.
If you prefer using the van Kampen Theorem directly without a full cellular decomposition, I think there is at least one reasonable path forward.  If you break $S^2$ into its equatorial circle and its complement, there is a corresponding decomposition of $S^2 \times I$ given by one piece $A$ being an open neighborhood of $S^1 \times I$ and another being $B = (S^2\setminus S^1) \times I$.  The intersection $A \times B$ is then a deformation retract of $(S^1 \coprod S^1) \times I$.
This covering is not good for computing the fundamental group of $S^2 \times I$, since the intersection isn't connected, but upon taking the quotient relation the two components of the intersection get glued together.  I claim that the intersection now has the homotopy type of a torus.   I think that the image of $A$ under the gluing is a model for the Klein bottle and the image of $B$ deformation retracts to the circular path passing through the poles.  It remains to determine the corresponding maps on fundamental groups to compute the relevant amalgamated product.


Rigorous way of proving infimum of a sequence

Question: Would someone be able to provide me with a rigorous way of proving that inf(1/sqrt(n)) = 0. I have already proven that it exists by the completeness property.
Thank you!
Answer: Perhaps Archimedean principle helps. For every $\epsilon>0$, find some $N\in{\bf{N}}$ such that $\dfrac{1}{N}<\epsilon.$, then for all $n\geq N^{2}$, we have $\dfrac{1}{\sqrt{n}}\leq\dfrac{1}{N}<\epsilon$. Since any such $n$ satsifies $\dfrac{1}{\sqrt{n}}\in\left\{\dfrac{1}{\sqrt{n}}: n\in{\bf{N}}\right\}$, so $\inf\left\{\dfrac{1}{\sqrt{n}}: n\in{\bf{N}}\right\}<\epsilon$. This is true for all $\epsilon>0$ and the infimum is nonnegative, so it is zero.
Comment: thank you very much! In your opinion, should I always use the Archimedian property to prove that the infimum ( or supremum) of a sequence is "x"?
Comment: If it were some infimum of nonnegative numbers is zero, then it always helps.
Comment: okay thank you very much
Answer: $A:= ${$1/√n$ | $n\in \mathbb{Z+}$}.
$ \inf(A)$ exists and $\inf(A) \ge 0.$
(Since $0$ is a lower bound.)
Assume $\inf(A) =a >0.$
Choose  $n_0 > 1/a^2.$
(Archimedes)
Then
$0 < 1/√n_0 < a.$
$\rightarrow$
$a(>0)$ is not a lower  bound of $A.$
Hence
$ \inf(A)= 0.$