text:
Q: Find the degree $[E:\mathbb{Q}]$ Let $p$ a prime number. Find a splitting field $E$ of the polynomial $x^p-2 \in \mathbb{Q}[x]$.
I have done the following:
The solutions of $x^p-2=0$ are :
$$\sqrt[p]{2}, \sqrt[p]{2}\omega, \dots, \sqrt[p]{2}\omega^{p-1}, \text{ where } \omega=e^{\frac{2 \pi i}{p}}$$
Therefore, the splitting field is $E=\mathbb{Q(\sqrt[p]{2}, \omega)}$
Is this correct so far??
How can I find the degree $[E:\mathbb{Q}]$ ??
EDIT:
$[E:\mathbb{Q}]=[\mathbb{Q(\sqrt[p]{2}, \omega)} : \mathbb{Q}]=[\mathbb{Q(\sqrt[p]{2}, \omega)} : \mathbb{Q}(\sqrt[p]{2})][\mathbb{Q(\sqrt[p]{2})} : \mathbb{Q}]=[\mathbb{Q(\sqrt[p]{2}, \omega)} : \mathbb{Q}(\sqrt[p]{2})]p$
Since $Irr(\sqrt[p]{2}, \mathbb{Q})=x^p-2 \Rightarrow [\mathbb{Q(\sqrt[p]{2})} : \mathbb{Q}]=p$.
But how can we find $[\mathbb{Q(\sqrt[p]{2}, \omega)} : \mathbb{Q}(\sqrt[p]{2})]$ ??
EDIT: Proof that the degree is the product of p and p-1:
$$[\mathbb{Q}(\omega, \sqrt[p]{2}) :\mathbb{Q}]=[\mathbb{Q}(\omega, \sqrt[p]{2}):\mathbb{Q}(\sqrt[p]{2})][\mathbb{Q}(\sqrt[p]{2}):\mathbb{Q}]=a \cdot p$$
$$[\mathbb{Q}(\omega, \sqrt[p]{2}):\mathbb{Q}]=[\mathbb{Q}(\omega, \sqrt[p]{2}):\mathbb{Q}(\omega)][\mathbb{Q}(\omega):\mathbb{Q}]=b \cdot (p-1)$$
$$a \cdot p = b \cdot (p-1) \Rightarrow p \mid a \cdot p \overset{(p, p-1)=1}{ \Longrightarrow } p \mid b \Rightarrow p \leq b \tag 1 $$ $$\Rightarrow a \cdot p \leq a \cdot b \Rightarrow b \cdot (p-1) \leq a \cdot b \Rightarrow p-1 \leq a \tag 2 $$
$$\mathbb{Q} \leq \mathbb{Q}(\omega) \leq \mathbb{Q}(\omega, \sqrt[p]{2}) \Rightarrow Irr(\sqrt[p]{2}, \mathbb{Q}(\omega)) \mid Irr(\sqrt[p]{2}, \mathbb{Q}) $$ $$\Rightarrow \deg Irr(\sqrt[p]{2}, \mathbb{Q}(\omega)) \leq \deg Irr(\sqrt[p]{2}, \mathbb{Q}) \Rightarrow b \leq p \tag 3$$
$$\mathbb{Q} \leq \mathbb{Q}(\sqrt[p]{2}) \leq \mathbb{Q}(\omega, \sqrt[p]{2}) \Rightarrow Irr(\omega, \mathbb{Q}(\sqrt[p]{2})) \mid Irr(\omega, \mathbb{Q}) $$ $$ \Rightarrow \deg Irr(\omega, \mathbb{Q}(\sqrt[p]{2})) \leq \deg Irr(\omega, \mathbb{Q}) \Rightarrow a \leq p-1 \tag 4$$
From $(1)$ and $(3)$ we have that $b=p$ and from $(2)$ and $(4)$ we have that $a=p-1$
Therefore, $[\mathbb{Q}(\omega, \sqrt[p]{2}) :\mathbb{Q}]=p(p-1)$.

A: You've done most of the work for yourself, and your proposed splitting field is correct.
We can consider two towers of fields:
$$\mathbb{Q} \subset \mathbb{Q}[\sqrt[p]{2}] \subset \mathbb{Q}[\sqrt[p]{2}, \omega]$$
$$\mathbb{Q} \subset \mathbb{Q}[\omega] \subset \mathbb{Q}[\sqrt[p]{2}, \omega]$$
 where $\omega$ is a $p^{\text{th}}$ root of unity.
In the first tower, the intermediate field is of degree $p$ over $\mathbb{Q}$ (Why?).  In the second tower, the intermediate field is of degree $p-1$ over $\mathbb{Q}$. (again, why?)
Now apply the fact that $[K:F] = [K:E] \cdot [E:F]$ for a tower of fields $F \subset E \subset K$.  Given this, both $p$ and $p-1$ divide the degree of the splitting field.  Further, the degree of the splitting field is at most $p(p-1)$ since, worst case scenario, the minimal polynomial for $\sqrt[p]{2}$ is irreducible over $\mathbb{Q}[\omega]$.
Therefore...


text:
Q: imagepng shows "cannot be displayed" error I dunno why, but there's something weird about imagepng. Whenever i use imagepng($image_p,NULL,9); it uploads the file and displays it on the page but when i use imagepng($image_p,'upload/test.png',9); it does upload the image, but the page returns the message "The image _ cannot be displayed, because it contains errors." and the succeeding codes will not work.
Can you guys please tell me what I'm doing wrong here?
here's the more detailed code:
$im = imagecreatefrompng($filename2);
$size = getimagesize($filename2);
$w = $size[0];
$h = $size[1];
$nw = 200;
$nh = 200;
$image_p = imagecreatetruecolor($nw,$nh);
imagecopyresampled($image_p,$im,0,0,$_GET['left']*1,$_GET['top']*1,$nw,$nh,$_GET['width']*1,$_GET['height']*1);
header('Content-Type: image/png');
$fn1 = "fin_".substr(uniqid(md5(rand()), true),0,10).".".$extension;
imagepng($image_p,'upload/'.$fn1,9);

A: I removed header('Content-Type: image/png'); and it worked. Unbelievable.
Thank you very much Fred ii for trying to help me out. I really appreciate your time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Incompatible Target Framework on Visual Studio Community I`ve been trying to make a unit test in my project following this tutorial: https://learn.microsoft.com/en-us/visualstudio/test/walkthrough-creating-and-running-unit-tests-for-managed-code?view=vs-2019
But when I try to reference my project on step 5 shows this:
"Project(Incompatible target framework: .NETFramework, version=v4.7)"
Anyone has found a solution?
First of all, Thanks.

A: I just faced a similar issue. I was developing from a macbook and I notice when you start a new project, somehow by default it starts with .Net Framework and when you add a unit test (MSTest in my case) it sets it from .Net Core and the two are just not compatible targets as it says.
How I solved this is, at the start of the new project, I select under Web and Console -> App ->Console Application (since you are doing a console app from the shared link). Then when I hit next, I am given the option to select a target framework. There I select .Net Core and go on with other processes. Then when I added my unit test from there it worked with no issues.
Try that lets see if it works for you as well.


text:
Q: Как из некоторых снимков сделать отдельную ветку?
Есть существующая старая ветка old в которой вся история из результирующих и промежуточных снимков. Необходимо выбрать из неё только результирующие снимки и создать на их основе отдельную «чистую» ветку, например, master.
Решение не обязательно должно соответствовать рисункам, возможно, есть более грамотный вариант, не знаю.
Рис. 1 — старая ветка.
Рис. 2 — вариант со слиянием.
Рис. 3 — вариант с копированием.
Чёрные — результирующие снимки.
Белые — промежуточные снимки.

A: Как работать, чтобы такая проблема не возникала?
«Промежуточные» коммиты нужны и полезны. Очень удобно бывает сохраниться где-то посреди разработки: чтобы попробовать другое решение, чтобы перенести работу на другую машину, просто для спокойствия.
Но в итоговой истории они не очень-то интересны. Более того, я лично не хотел бы, чтобы кто-то через месяцы и годы смотрел, как я изобретал велосипеды, писал по строчке в час и делал дурацкие ошибки. Нет, я хочу один финальный коммит, как будто я сел, возложил руки на клавиатуру и создал шедевр. Возможно, вам тоже так будет удобнее.
Что делать-то?
1. Используйте фичеветки (feature branches)
Для работы над каждой задачей делайте отдельную ветку от master. Делайте в ней сколько душе угодно коммитов. Когда результат будет готов — вы сможете собрать все эти коммиты в один или несколько осмысленных (инструкция ниже) и замержить в master.
Мержить рекомендую с --no-ff. Так получается более информативная история: видно, где закончились коммиты одной фичи и начались коммиты другой.

*

*Подробнее о фичеветках.

*Про разные модели работы, в том числе с фичеветками.

2. Пользуйтесь commit --amend для промежуточных коммитов
Исправили одну строчку в фичеветке и снова нужно сделать коммит? Проще переписать старый.
git add path/filename
git commit --amend --no-edit

Здесь --no-edit означает, что мы не хотим менять сообщение коммита — оставим старое.

Важно: Нужен хотя бы один новый коммит в ветке, который вы будете переписывать. Если вы только что сделали новую ветку от master, пока что нельзя делать --amend.  Иначе вы перепишете коммит из master.
Важно: commit --amend, rebase -i и другие операции по переписыванию истории нельзя выполнять в общих (стабильных) ветках вроде master.

Как объединить коммиты по группам в новой ветке?
Предположим, у нас есть такая история коммитов. «Промежуточные» коммиты обозначены как bullshit, а «результативные» — result x. Самый новый коммит — сверху.
git log --oneline --graph --decorate

* 71e8ed5 (HEAD -> oldbranch) result 2
* 0955502 bullshit
* cf30c6f bullshit
* d590b3d result 1
* 8266a62 bullshit
* ce5b35c bullshit

Пересобрать их в более красивую (что очень субъективно) историю нам поможет команда rebase -i.
Сначала сделаем новую ветку, в которой будет результат операции.
git checkout -b newbranch

Поскольку здесь мы хотим заребейзить всю ветку целиком, добавляем --root.
git rebase -i --root

Если нужно переписать историю только до какого-то коммита (не включая его), указываем хеш этого коммита.
git rebase -i ce5b35c

Открывается редактор с вот таким содержимым. Здесь порядок коммитов обратный: самый новый коммит — снизу.
pick ce5b35c bullshit
pick 8266a62 bullshit
pick d590b3d result 1
pick cf30c6f bullshit
pick 0955502 bullshit
pick 71e8ed5 result 2

# Rebase 71e8ed5 onto f7569aa (6 commands)
...

Что в этой ситуации можно сделать с коммитами? Нам интересны две команды:
# p, pick = use commit
# оставить коммит как есть

# s, squash = use commit, but meld into previous commit
# слить содержимое коммита с ПРЕДЫДУЩИМ коммитом

Объединяем (squash) коммиты группами: первый «промежуточный» после каждого результата станет основой нового результата.
pick ce5b35c bullshit
s 8266a62 bullshit
s d590b3d result 1
pick cf30c6f bullshit
s 0955502 bullshit
s 71e8ed5 result 2

Когда вы сохраните этот текст и выйдете из редактора, откроется новый, с текстом сообщения для нового коммита result 1, потом для result 2 и так далее — столько раз, сколько коммитов вы хотите в итоге оставить. Первым будет самый старый, последним — самый новый. По умолчанию вам предлагается вот такой шаблон:
# This is a combination of 3 commits.
# This is the 1st commit message:
bullshit

# This is the commit message #2:

bullshit

# This is the commit message #3:

result 1

# Please enter the commit message for your changes. Lines starting

Когда вы отредактируете и сохраните все новые сообщения, rebase -i завершится. Получится примерно такая история:
* 588a7ac (HEAD -> newbranch) result 2
* 2713fda result 1


text:
Q: How to block outgoing traffic (HTTP) from VMs? I am playing with vmware ESXi v5 and installed a Win XP 32bit as one of the VMs inside.
I wish to block outgoing access (especially http) from the VM (maybe some form of firewall?), yet still allow:

*

*Entry to the VM via RDC

*Sharing of files or other features with other VMs (perhaps meaning within LAN) in the host kind of like via Workgroup. (this might need a seperate question)

Any ideas on how can I do the above? Still very new in VM-ing! But willing to learn! :)

A: Assuming that your Windows XP VM is bridging to a physical interface on your ESXi box or part of a virtual switch connected to a physical interface on your ESXi box you have a few choices.

*

*You could use the Windows XP firewall to control inbound and outbound network connections. This would be the quickest way to do this without changing any ESXi settings. You can read more here

*You could build another VM or use a Virtual Applicance that would operate as a network firewall. You would then need to create two virtual switches. One that would be connected to your physical server interface and one of the interfaces on the firewall VM. You could note this as your "Outside Interface". Then one virtual switch that connects to the second interface on your virtual firewall VM and the interface of your Windows XP VM. You could note this as your "Inside Interface". The tricky part here is if you choose to NAT or route the traffic between your inside and outside. It may be easier to NAT the traffic and port forward the remote desktop connections, or you may feel comfortable advertising a new route to the subnet on the Inside interface. Some virtual firewall appliances may allow operation as a bridged firewall if so you could run the same subnet for the inside and outside interfaces, this may require extra work on the virtual switch to allow proxy ARP or permiscious traffic.

*You could place a firewall device between the ESXi physical connection and what ever network you are attached to.

A: I'd suggest one of the VMWare vShield products, perhaps 'App' or 'Edge' - take a look, there's lots of options.

A: Where do you want to block it from? If the machines (VMs) are configured with bridging, you can block access at the firewall, or set up a firewall on your network to filter traffic.
Another option is to create a VM with Linux, install firewall software on it, then set your other VM's to use it as the gateway to the Internet (use proxying and forwarding on the Linux VM to send traffic to your "actual" gateway.)


text:
Q: Get records for last month I need to get the customer id, number and amount of orders for the last month.
Paper::select('customer_id', DB::raw('SUM(price) as `sum`')
    ,DB::raw('COUNT(*) as `orders_per_month`'))
    ->where('created_at', '>=', Carbon::now()->startOfMonth())
    ->groupBy('customer_id')->get()

I tried so, but if the last month the client has no orders, it will not be selected

A: Try COALESCE:
DB::raw('COALESCE(COUNT(*), 0) as `orders_per_month`')

This function allows you define a default value when otherwise it is NULL.
http://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#function_coalesce
UPDATE:
I think if you are selecting only customer which has orders the last month, then definitely you will not get those customers without orders.
You can achieve what you need with something like:
mysql> select * from cu;
+----+----------+
| id | name     |
+----+----------+
|  1 | Google   |
|  2 | Yahoo    |
|  3 | Mirosoft |
+----+----------+
3 rows in set (0.00 sec)

mysql> select * from so;
+----+-------------+---------------------+-------+
| id | customer_id | created_at          | price |
+----+-------------+---------------------+-------+
|  1 |           1 | 2016-08-23 12:12:12 |     2 |
|  2 |           1 | 2016-09-24 12:14:13 |     3 |
|  3 |           2 | 2016-09-25 00:00:00 |     5 |
|  4 |           2 | 2016-09-12 09:00:00 |     3 |
+----+-------------+---------------------+-------+
4 rows in set (0.00 sec)

mysql> select cu.id as customer_id, coalesce(sum(so.price),0) as total, coalesce(count(so.customer_id),0) as orders_per_month from cu left join so on (cu.id = so.customer_id) where so.created_at >= '2016-09-01 00:00:00' or so.created_at is null group by cu.id;
+-------------+-------+------------------+
| customer_id | total | orders_per_month |
+-------------+-------+------------------+
|           1 |     3 |                1 |
|           2 |     8 |                2 |
|           3 |     0 |                0 |
+-------------+-------+------------------+
3 rows in set (0.00 sec)

However, the resulting query would not be very efficient as one way or another, you will have to scan all your customers and JOIN to get those without orders. It might be faster to get a list of customers with orders and without order separately and merge them with UNION or via your application code.
mysql> select customer_id, sum(total) as total, sum(orders_per_month) as orders_per_month from (select id as customer_id, 0 as total, 0 as orders_per_month from cu union all select customer_id, sum(so.price) as total, count(so.customer_id) as orders_per_month from so where created_at >= '2016-09-01 00:00:00'group by customer_id) agg group by customer_id;
+-------------+-------+------------------+
| customer_id | total | orders_per_month |
+-------------+-------+------------------+
|           1 |     3 |                1 |
|           2 |     8 |                2 |
|           3 |     0 |                0 |
+-------------+-------+------------------+
3 rows in set (0.00 sec)

A: Try this
Paper::select('customer_id', DB::raw('SUM(price) as `sum`'),
             DB::raw('COUNT(*) as `orders_per_month`')
       )
     ->whereMonth('created_at', Carbon::now()->month)
     ->whereYear('created_at', Carbon::now()->year)
     ->groupBy('customer_id')->get()


text:
Q: How to add a symbol next to an enumerated item? How could I add a symbol from bclogo next to an enumerated item like in the picture?

A: The assumption is that you only want some items to have a bomb next to them. So, create a \bombitem that adapts to the enumerate level:

\documentclass{article}

\usepackage{bclogo,graphicx}

\makeatletter
\newcommand{\bombitem}{%
  \refstepcounter{\@enumctr}% step the level-specific counter
  \item[% Insert item/enumeration
    {\raisebox{-.7ex}[0pt][0pt]{\scalebox{.5}{\bcbombe}}}% Place bomb
    \,% Space
    \@nameuse{label\@enumctr}]% Place level-formatted counter
}
\makeatother

\begin{document}

\begin{enumerate}
  \item First item
  \item Second item
  \bombitem Third item
  \begin{enumerate}
    \item First item
    \item Second item
    \bombitem Third item
    \item Last item
  \end{enumerate}
  \item Last item
\end{enumerate}

\end{document}

The above assumes you'll use \bombitem inside an enumerate.

A: Here is a solution
\documentclass{article}
\usepackage{bclogo}
\renewcommand\labelenumi{\raisebox{-1em}[0em][0em]{\bcbombe}\ \theenumi.}
\begin{document}
\begin{enumerate}
\item bla bla bla bla bla bla bla bla
bla bla bla bla bla bla bla bla
bla bla bla bla bla bla bla bla
bla bla bla bla bla bla bla bla
\item bla bla
\end{enumerate}
\end{document}

One can do the same with \labelenumii for second level.
Update to do this localy, Two methodes
\documentclass{article}
\usepackage{bclogo}
\begin{document}
\begin{enumerate}
\item bla bla bla bla bla bla bla bla
bla bla bla bla bla bla bla bla
bla bla bla bla bla bla bla bla
bla bla bla bla bla bla bla bla
{\renewcommand\labelenumi{\raisebox{-1em}[0em][0em]{\bcbombe}\ \theenumi.}
\item bla bla}
\item bla
\item[\mbox{\refstepcounter{enumi}\raisebox{-1em}[0em][0em]{\bcbombe}\ \theenumi.}]
bla bla
\item bla bla
\end{enumerate}
\end{document}


text:
Q: How to find the Hilbert Adjoint operator of $T(f)(t)=\int_{0}^tf(s)\ ds$?
Possible Duplicate:
Finding the adjoint of an operator

Consider the vector space $C[0, 1]$ with inner product,
\begin{align*}
\langle f, g\rangle=\int_{0}^1f(t)g(t)\ dt.
\end{align*}
Let $T:C[0, 1]\rightarrow C[0, 1]$ the bounded linear operador given by,
\begin{align*}
T(f)(t)=\int_{0}^tf(s)\ ds.
\end{align*}
How can I find the Hilbert adjoint operator $T^*$ of $T$?

A: $\def\sp#1{\left\langle#1\right\rangle}$For $f,g \in C[0,1]$ we have
\begin{align*}
  \sp{Tf, g} &= \int_0^1 Tf(t)g(t)\,dt\\
             &= \int_0^1 \int_0^t f(s)\,ds \cdot g(t)\,dt\\
             &= \int_0^1 \int_s^1 f(s)g(t)\,dt\,ds\\
             &= \int_0^1 f(s)\int_s^1 g(t)\,dt\,ds\\
             &=: \sp{f, T^*g}
\end{align*}
with
$$ (T^*g)(s) = \int_s^1 g(t)\, dt, \qquad s \in [0,1] $$

A: We have
$$
(Tf)'=f \quad \forall\ f \in X:=C([0,1]).
$$
Using integration by parts we have, for every $f, g \in X$:
\begin{eqnarray}
\langle Tf,g\rangle &=&\int_0^1(Tf)(t)g(t)\,dt=\int_0^1(Tf)(t)(Tg)'(t)\,dt\\
&=&\left[(Tf)(t)(Tg)(t)\right]_0^1-\int_0^1(Tf)'(t)(Tg)(t)\,dt\\
&=&(Tf)(1)(Tg)(1)-\int_0^1(Tf)'(t)(Tg)(t)\,dt\\
&=&\int_0^1f(t)(Tg)(1)dt-\int_0^1f(t)(Tg)(t)\,dt\\
&=&\int_0^1f(t)[(Tg)(1)-(Tg)(t)]\,dt\\
&=&\langle f,T^*g\rangle,
\end{eqnarray}
where
$$
(T^*g)(t)=(Tg)(1)-(Tg)(t)=\int_0^1g(s)\,ds-\int_0^tg(s)\,ds=\int_t^1g(s)\,ds.
$$
Hence
$$
(T^*f)(t)=\int_t^1f(s)\, ds \quad \forall\ f \in X.
$$


text:
Q: SharePoint Online, get list of checked out files from lib using PnP I have a document lib that has been stale for a few years. I am trying to clean it up, but there are 1000+ document that are Checked Out to another user. I am a super admin, so I can go in and get take ownership / check these documents in individually. But that would take HOURS and there may be many more libraries that I need to sort through.
I see there is the Set-PnPFileCheckedIn command for PowerShell, which is good, but what I don't see is a command to take ownership of checked out files. Or a settings on the following commands that would allow me to loop through checked out items:

Find-PnPFile
Get-PnPListItem
Get-PnPFolerItem
Get-PnPFiel -asListItem

As of now the commands I listed above only return checkedin items, or items that are checked out under your user sessioned account.
Is it that I need to run a command as the user that has the documents checked out?
I know the ListItem fields have a field like CheckedOutTo but that does not help when you cannot get a list of said checkedout items to update who the document is currently checked out too.
Looking for a PnP command solution to this. If at all possible. I see some solutions using the older SPO commands, and if that is the only way than so be it, but I am tring to stick within the realm of PnP commands.
Thanks all in advance!

A: I was able to figure this out by using the $context.Load($thing); $context.ExecuteQuery()
# Setup the site context
[Microsoft.SharePoint.Client.Web] $Connection = Get-PnPWeb
$context = $Connection.Context
[Microsoft.SharePoint.Client.List] $list = Get-PnPList $listName

# Load the list
$context.Load($list)
$context.ExecuteQuery()

# Load the checked out files
$chkdOutFiles = $list.GetCheckedOutFiles()
$context.Load($chkdOutFiles)
$context.ExecuteQuery()

foreach ($file in $chkdOutFiles) {
    # Do Actions...
}

Some thing I was noticing is that the Get-PnPxxx functions don't return all data and that in some instances you need to load the object like above. I thought this processes was more required by the older Get-SPOxxx functions, but I guess is also needed for PnP.
@Martin Muldoon got me on the right track to figuring this out. So thank you sir!

A: To loop through the check out items, couldn't you simply:
$lists = Get-PnPList -Web $web
foreach($list in $lists)
{
     $checkedOutItems = $list.GetCheckedOutFiles()
     foreach($file in $checkedOutItems)
     {
           #take action
     }
}

UPDATE ------------------------
I was not iterating through the collection correctly.  Try this:
 foreach($file in $list.checkedOutItems)
     {
           #take action
     }


text:
Q: Can I use a progress indicator without using threads and asynchronous tasks? If yes, how we can achieve this?

A: Theoretically speaking, yes, you can, but you should not. Because progress indicator is meant for a relatively long-running task, and if you try to do this on your UI thread, your application will get force closed as non-responsive.


text:
Q: HAVING skipping certain numbers from an alias I have this query that takes a table that contains a votes column and ranks them 1st, 2nd, 3rd, and so on. I want to limit the ranks to the top 3 items, however when I use HAVING, it appears to skip over even numbers or even bump up to the next number if I were to use HAVING rank <= 6.
SELECT `category`,
       `year`,
       `month`, `votes`,
       @prev := @curr,
       @curr := `votes`,
       @rank := IF(@prev = @curr, @rank, @rank + @i) AS `rank`,
       IF(@prev <> `votes`, @i:=1, @i:= @i+1) AS `counter`
FROM `photo_contest`
CROSS JOIN (SELECT @curr := null, @prev := null, @rank := 1, @i := 0) `tmp_tbl`
WHERE `category` = 'World Up Close'
  AND `year` = '2017'
  AND `month` = 'April'
  AND `votes` > 0
HAVING `rank` <= 3
ORDER BY `votes` DESC

It may be an issue with our server's PHP installation as it uses a much older MySQL library (5.1.73) than the server that is currently running (5.6.35), but I am not sure. I've had issues with a previous question using similar queries.

A: You use the HAVING together with GROUP BY. In this case you need to use a subquery without  HAVING.
SELECT *
FROM ( SELECT <your query> ORDER BY `votes` DESC) as T
WHERE rank <= 3


text:
Q: Android camera photo comes back null In my android app I employ a camera activity which sometimes works and sometimes doesn't.  About 30% of the time the uri set up to store the photo comes back with a null value even though the camera picture is stored in the picture directory on the phone.  Below is my start activity.
  Uri imageUri;       // These are defined at the global level
  Uri selectedImage;
     ...............
  String fileName = name.replace(" ", "");
            fileName = fileName + suffix + ".jpg";
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.TITLE, fileName);
            values.put(MediaStore.Images.Media.DESCRIPTION, "Image capture by camera");
                 imageUri = getContentResolver().insert(
                 MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
             Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                 intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

            if (intent.resolveActivity(getPackageManager()) != null) {
                 startActivityForResult(intent, RESULT_LOAD_IMAGE);
            }
            else
                Toast.makeText(getApplicationContext(), "Photo was not taken", Toast.LENGTH_SHORT).show();

Below is my result activity.
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        Bitmap image1;
        if(requestCode == RESULT_CROP_IMAGE)
        {
            Bundle extras = data.getExtras();
             image1 = extras.getParcelable("data");
        }
        else {
            if (requestCode == RESULT_LOAD_IMAGE) {
               selectedImage = imageUri;   // returns null occassionally
          } else
                  selectedImage = data.getData();
        if(selectedImage == null)
            {
                Toast.makeText(getApplicationContext(), "Photo not captured correctly", Toast.LENGTH_LONG).show();
                return;
            }

The problem is that the variable imageUri returns as null everyone once in awhile even though the picture was taken and resides on the Samsung S4 phone picture directory.  Can anyone explain why this could happen and how to resolve it?  Is there another way to capture the photo if nulls are returned?  I should add that I am on Android SDK version 23.  I didn't use to have this problem.
I have more information on the problem.  I set my imagepath in the startactivity as follows:
           String mCurrentPhotoPath;  // is stored at the global level
           .....
           String fileName = name.replace(" ", "");
            fileName = fileName + suffix + ".jpg";
            mCurrentPhotoPath = fileName;
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.TITLE, mCurrentPhotoPath);
            values.put(MediaStore.Images.Media.DESCRIPTION, "Image capture by camera");
                 imageUri = getContentResolver().insert(
                 MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

And in my result activity I get null for mCurrentPhotoPath.  What caused this to get wiped out?  I did not reference mCurrentPhotoPath in any other place that would cause it to become null.
     if (requestCode == RESULT_LOAD_IMAGE) {
         if(imageUri != null)
             selectedImage = imageUri;
          else
          {
           if(mCurrentPhotoPath != null) {   // mCurrentPhotoPath returns null;
               File file = new File(Environment.getExternalStorageDirectory().getPath(), mCurrentPhotoPath);
                        selectedImage = Uri.fromFile(file);
                    }
                    else {
                        Toast.makeText(getApplicationContext(), "Photo not captured", Toast.LENGTH_LONG).show();
                        return;
                    }
                }

Can anyone explain why mCurrentPath returns a null value when I didn't reference it in any other place other than the start activity and the result activity?

A:
Can anyone explain why this could happen

ACTION_IMAGE_CAPTURE does not return a Uri, according to the documentation. data.getData(), in your code, should always be null. If it is not null, what that Uri means is undocumented.

how to resolve it?

You already know what the Uri is. You put it in EXTRA_OUTPUT. Use that.

I didn't use to have this problem.

Yes, you did. There are thousands of Android device models. These ship with dozens, if not hundreds, of camera applications built in. There are dozens, if not hundreds, of additional ACTION_IMAGE_CAPTURE-supporting apps available for download, from places like the Play Store. None of them have to return a Uri, since the documentation does not say that they have to return a Uri (and, even then, there are bugs in camera apps).

A: Thanks to CommonsWare I resolved the issue by implementing a onSaveInstance State.  This should be required information on any android camera documentation as you lose the global variables whenever you change the camera's orientation.
       @Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putParcelable("myURI", imageUri);
    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

public void onRestoreInstanceState(Bundle savedInstanceState) {
    // Always call the superclass so it can restore the view hierarchy
    super.onRestoreInstanceState(savedInstanceState);
    // Restore state members from saved instance
   imageUri = savedInstanceState.getParcelable("myURI");

}


text:
Q: pgAdmin's "Servers" tab is empty (Docker Compose) I am new to postgresql and unable to create a database,  please see my file below
My Docker compose file is :
version: '3.5'

services:
  postgres:
    container_name: postgres_container
    image: postgres
    environment:
      POSTGRES_USER: ${POSTGRES_USER:-postgres}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-changeme}
      PGDATA: /data/postgres
    volumes:
       - postgres:/data/postgres
    ports:
      - "5432:5432"
    networks:
      - postgres
    restart: unless-stopped

  pgadmin:
    container_name: pgadmin_container
    image: dpage/pgadmin4
    environment:
      PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL:-pgadmin4@pgadmin.org}
      PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD:-admin}
      PGADMIN_CONFIG_SERVER_MODE: 'False'
    volumes:
       - pgadmin:/root/.pgadmin

    ports:
      - "${PGADMIN_PORT:-5050}:80"
    networks:
      - postgres
    restart: unless-stopped

networks:
  postgres:
    driver: bridge

volumes:
    postgres:
    pgadmin:

The servers tab is empty,how to create a database,Do I need to enter something?

A: The pgAdmin needs a Server-config called servers.json.
More info on the servers.json can be found on their website
The config below worked for me:
docker-compose.yml
version: '3.9'

services:

  db:
    image: postgres:latest
    restart: "no"
    container_name: postgres
    volumes:
      - ./database:/var/lib/postgresql/data
    ports:
      - "9002:5432"
    environment:
      POSTGRES_PASSWORD: root
      POSTGRES_USER: root
      POSTGRES_DB: myDatabase

  pgadmin:
    image: dpage/pgadmin4
    container_name: pgadmin
    restart: "no"
    ports:
      - "9003:80"
    volumes:
      - ./servers.json:/pgadmin4/servers.json
    environment:
      PGADMIN_DEFAULT_EMAIL: you@email.com
      PGADMIN_DEFAULT_PASSWORD: admin123
      PGADMIN_LISTEN_PORT: 80
      POSTGRES_PASSWORD: root
      POSTGRES_USER: root
      POSTGRES_DB: myDatabase

networks:
  default:
    external:
      name: database_network

Database folder
Create a 'database' folder next to the above files because this is where the docker-compose wants to put the database.
servers.json
In the same folder as the docker-compose.yml
{
    "Servers": {
        "1": {
            "Name": "Local",
            "Group": "Servers",
            "Host": "db",
            "Port": 5432,
            "MaintenanceDB": "postgres",
            "Username": "root",
            "SSLMode": "prefer",
            "SSLCert": "<STORAGE_DIR>/.postgresql/postgresql.crt",
            "SSLKey": "<STORAGE_DIR>/.postgresql/postgresql.key",
            "SSLCompression": 0,
            "Timeout": 10,
            "UseSSHTunnel": 0,
            "TunnelPort": "22",
            "TunnelAuthentication": 0
        }
    }
}


text:
Q: Application managed JPA, when is Transaction needed We are working on a little web (will run on Tomcat) with the data layer done with JPA (Eclipselink).
I did similar thing some time ago. But i were always unsure when i need to begin and end transactions or do a flush.
At the moment i use transaction if i add (persist) and remove objects. If i call setters on an already persisted object i do not use transactions.
Is there a guide/ tutorial or a short answer when to use transactions or how to implement application managed JPA correctly.

A: I think one can summarize an answer to your question.
almost any JPA operation needs a transaction, except find/selects that do not lock entities (i.e any JPA operation that does not change the data).
(JTA transaction-scoped entity manager)
In the case of an JTA transaction-scoped entity manager it is better to quote from the spec (Chapter 3 Entity Operations):

The persist, merge, remove, and refresh methods must be invoked within
a transaction context when an entity manager with a
transaction-scoped persistence context is used.
If there is no transaction context, the javax.persistence.TransactionRequiredException is thrown.
Methods that specify a lock mode other than LockModeType.NONE must be invoked
within a transaction context.
If there is no transaction context, the javax.persistence.TransactionRequiredException is thrown.
The find method (provided it is invoked without a lock or invoked with
LockModeType.NONE) and the getReference method are not required to be
invoked within a transaction context. If an entity manager with
transaction-scoped persistence context is in use, the resulting
entities will be detached; if an entity manager with an extended
persistence context is used, they will be managed. See section 3.3 for
entity manager use outside a transaction.

(Application-managed/resource-local entity manager)
In the case of an Application-managed entity manager, the JPA spec is not clear about the behavior. In the case of Hibernate, it is pretty complicated what happens, when not inside a transaction (it could depend also on the JDBC driver and the autocommit mode of the DB connection). Check Hibernate's article on this theme. Basically you are strongly encouraged to always use transactions for the above mentioned operations.
To the second part of your question: if you called a setter of a managed entity, and without flushing you detached it (i.e before transaction commit), the behavior is unclear/undefined, i.e you should better correct the code.
Example of buggy code:
//begin Transaction
MyEntity entity = em.find(MyEntity.class, 1L);
entity.setField("New value");
em.detach();//it is not sure whether the "New value" will be persisted. To make sure it is persisted, ypu need to call em.flush() before detaching
//commit Transaction

Usually if the order of DB operations (not the same as the order of enity manager operations) is not important, you can leave the JPA implementation to decide when to flush (e.g on transaction commit).


text:
Q: With unit testing how to test a switchMap in viewModel calls the proper method from repository class In my ViewModel i have used swithcMap with a liveData varaible  as parameter. When the liveData variable gets set/changed then the switchMap calls a method from my Repository. My viewModel code:
class MainViewModel @Inject constructor(val mainRepository: MainRepository) : ViewModel() {

    var searchQuery:MutableLiveData<SearchQuery> = MutableLiveData()
    var liveResult:MediatorLiveData<My_Result> = MediatorLiveData()

    var apiData:LiveData<My_Result> = Transformations
    .switchMap(searchQuery){query ->
        query?.let {
        val source: LiveData<My_Result> = mainRepository.fetchApiresultFromClient(it.filter_search , it.filter_topics, it.filter_language , it.page_number)

        liveResult.addSource(source){ item->
            liveResult.value = item
            liveResult.removeSource(source)
        }

        source

        }
    }

}

Now I want to test that if searchQuery is set then:

*

*switchMap is triggered

*and when switchMap is triggered then mainRepository.fetchApiresultFromClient(..) is called

*also if mainRepository.fetchApiresultFromClient(..) is called then the returned type is of LiveData

How do I do this? All I have managed to do is :
@ExtendWith(InstantExecutorExtension::class)
class MainViewModelTest {

    lateinit var  mainViewModel: MainViewModel

    @Mock
     lateinit var  mainRepository: MainRepository

    @BeforeEach
    fun init()  {
    MockitoAnnotations.initMocks(this)
    mainViewModel = MainViewModel(mainRepository)
    }

    @Test
    @Throws(Exception::class)
    fun setSearchQuery_callsRepositoryMethod() {
    var filter_search: SearchQuery = SearchQuery("java", "","",1)

    }

}

A: To make your code easier to test you could replace it by:
class MainViewModel @Inject constructor(val mainRepository: MainRepository) : ViewModel() {

    val searchQuery:MutableLiveData<SearchQuery> = MutableLiveData()

    var apiData:LiveData<My_Result> = Transformations.switchMap(searchQuery) { query ->
        query?.let {
            mainRepository.fetchApiresultFromClient(it.filter_search , it.filter_topics, it.filter_language , it.page_number)
        }
    }
}

Then you should

*

*mock mainRepository.fetchApiresultFromClient to return a MutableLiveData

*call mainViewModel.searchQuery.value = Query(...)

*and assert that when mainRepository emits a new value apiData also emits the same value.

If you have some test code to share I can help you to complete it


text:
Q: classes and strings in definitions in python class someDistance(Distance):
 def __init__(self, dist_funct_name_str = 'Something Distance', p=2):
  self.p = p

Just wanted to ask what the
dist_funct_name_str = 'Something Distance'

does in the definition?
Any help would be greatly appreciated!

A: It is used to define the default value of the variable dist_funct_name_strin case when no value is passed for it when the object someDistance was invoked.
example:
In [69]: def func(a,b=2): # b has default value of 2
   ....:     print a,b
   ....:
   ....:

In [70]: func(1)   # no value passed for b ,so it is equal to 2
1 2

In [71]: func(1,5) # 5 is passed for b, so b=2 is neglected
1 5

A: Both dist_funct_name_str and p are called default values.  If these values aren't set when __init__ is called, then these default values are used instead.
They also occur on other functions as well - not just __init__.

A: dist_funct_name_str = 'Something Distance'

Is a "default parameter" passed to the init function. It's basically the parameter used by default of a user or coder has not passed any arguments to a function.
You can read up a bit more on this here: http://effbot.org/zone/default-values.htm and I also recommend this: http://www.deadlybloodyserious.com/2008/05/default-argument-blunders/ .
I've run into the same thing not long ago.


text:
Q: how to create a checkbox with the same value on vue .js how do I make one of the check boxes true does not all go true, this is how the checkbox has the same value, if I am true all of them do not follow true
its myCode

     <input type="checkbox" true-value="1" false-value="0" v-model="ai">
     <input type="checkbox" true-value="1" false-value="0" v-model="ai">
     <input type="checkbox" true-value="1" false-value="0" v-model="ai">
     <input type="checkbox" true-value="1" false-value="0" v-model="ai">
     <input type="checkbox" true-value="1" false-value="0" v-model="ai">
    {{ai}}

A: You need to change ai: '' to ai: []
From
data: {
  ai: ''
}

to
data: {
  ai: []
}

You can see the example in the documentation,


text:
Q: How to evaluate $\lim_{n\to\infty}\frac{2^{n}n!}{n^n}$ I managed to prove the sequence is monotonic and bounded which means it is convergent. Though, I couldn't evaluate the limit itself. I tried to use a comparation test with no results. Anyway, the result is 0. Any help will bi appreciated.

A: HINT
By ratio test
$$\frac{\frac{2^{n+1}(n+1)!}{(n+1)^{n+1}}}{\frac{2^{n}(n)!}{n^{n}}}=2\left(\frac n {n+1}\right)^n=\frac2{\left(1+\frac 1 {n}\right)^n}$$

A: Hint: use equivalence and Stirling's formula:
$$n!\sim_{\infty}\sqrt{2\pi n}\Bigl(\frac n{\mathrm e}\Bigr)^n,$$so
$$\frac{2^{n}n!}{n^n}\sim_{\infty}\sqrt{2\pi n}\Bigl(\frac 2{\mathrm e}\Bigr)^n$$
Can you proceed from here?


text:
Q: Matplotlib: How to copy a contour plot to another figure? I have a figure with many different plots (contour plots and lots of other stuff). I want to extract the contour plot to another single figure to see more details. But I fail how to do so.
Have a look on this code:
import numpy as np
from matplotlib import gridspec as gs, pyplot as plt

# Figure 1 with many different plots.
fig1 = plt.figure()
gridSpec = gs.GridSpec(2, 3)
for i in range(6):
    fig1.add_subplot(gridSpec[i])

# Create contour plot
x = np.arange(-3.0, 3.0, 0.02)
y = np.arange(-2.0, 2.0, 0.01)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) ** 4

# Plot it to a particular axes.
ax1 = fig1.axes[2]
contour = ax1.contour(X, Y, Z)

# Try to copy the contour plot to another figure (with only 1 subplot).
fig2, ax2 = plt.subplots()
# How to copy the content of ax1 to ax2?

plt.show()

This will give me the following:

I want to create a second figure with only 1 subplot and its content should be the same as you can see in top right corner of the first figure with 6 subplots.
First thing I tried was
ax2.add_collection(contour.collections[1])

but I got the error message
RuntimeError: Can not put single artist in more than one figure

This is because the content is already plottet to figure 1, so it is not possible to plot it to figure 2 as well. So I tried to make a copy of the contour plot:
from copy import deepcopy
ax2.add_collection(deepcopy(contour.collections[1]))

But this will get me a new error that copiing is not possible ...
NotImplementedError: TransformNode instances can not be copied. Consider using frozen() instead.

So .. what can I do? Any ideas for that problem? :)
Thanks a lot!
(Python 3.7.4, Matplotlib 3.1.1)


text:
Q: Empirical Analysis of Merge and Insertion Sort - Difficulties I'm trying to analyse the run time of my implementation of merge and insertion sort. I'm noticing a weird trend and I wasn't able to find anyone with the same problem through googling, but I'm probably using the wrong terms.
The number of times the sorting algorithms run, seem inversely related to the amount of time taken for the algorithm to complete. Sample shown below for insertion sort.
4213,2104,8195,9441,4823,925,980,964,911,491,470,482,481... (it settles on ~490ms)
And similar behaviour with merge sort, but merge settles on ~95ms.
I have no idea why this is happening, I'm generating a random array every time... even if it wasn't random shouldn't it just take exactly the same time every time (or close)? why does it converge on a smaller value?
Just looking for anyone who might know why this is happening because it seems really strange to me... I'm assuming it's something Java is doing behind the scenes maybe? Any suggestions/tips appreciated!
All the code I am running is posted below. With the test code shown first.
public static void tests(int noTests, int arraySize){
    //set up the running totals of the time taken by insertion and merge
    double insertSum = 0;
    double mergeSum = 0;

    for(int i = 0; i < noTests; i++){
        //generate an array of random integers
        Integer[] randInput = generateRandomArray(arraySize);
        Integer[] insertInput = Arrays.copyOf(randInput, randInput.length);
        Integer[] mergeInput = Arrays.copyOf(randInput, randInput.length);
        //start the clock for insertion
        final long insertionStart = System.nanoTime();
        //sort it
        insertionSort(insertInput);
        //stop the clock for insertion
        final long insertionFinish = System.nanoTime();
        System.out.println("Time taken for insertion: " + (insertionFinish - insertionStart)/1000 + " ms");
        //add it to the running total
        insertSum += (insertionFinish - insertionStart)/1000;

        //likewise for merge
        final long mergeStart = System.nanoTime();
        mergeSort(mergeInput);
        final long mergeFinish = System.nanoTime();
        System.out.println("Time taken for merge: " + (mergeFinish - mergeStart)/1000 + " ms");
        mergeSum += (mergeFinish - mergeStart)/1000;
    }
    //Get the average by diving by the number of times it ran
    System.out.println("-------------------------------------------------------");
    System.out.println("Insert average: " + insertSum/noTests);
    System.out.println("Merge average: " + mergeSum/noTests);
}

//Generate an array of random Integers
public static Integer[] generateRandomArray(int n){
    Integer[] arr = new Integer[n];
    for(int i = 0; i < n; i++){
        arr[i] = (int) Math.floor(Math.random()*100);
    }
    return arr;
}

public static <T extends Comparable<T>> T[] insertionSort(T[] a){
    for(int i = 1; i < a.length; i++){
        int j = i-1;
        T key = a[i];

        while(j >= 0 && a[j].compareTo(key) > 0){
            a[j+1] = a[j];
            j = j-1;
        }
        a[j+1] = key;
    }
    return a;
}

@SuppressWarnings("rawtypes")
public static Comparable[] mergeSort(Comparable[] input){

    if(input.length<=1){
        return input;
    }

    int middle = Math.floorDiv(input.length, 2);

    Comparable a[] = new Comparable[middle];
    for(int i = 0; i < middle; i++){
        a[i] = input[i];
    }

    Comparable b[] = new Comparable[input.length - middle];
    for(int i = middle; i < input.length; i++){
        b[i-middle] = input[i];
    }

    mergeSort(a);
    mergeSort(b);
    merge(input, a, b);

    return input;
}

@SuppressWarnings({ "rawtypes", "unchecked" })
public static void merge(Comparable[] input, Comparable[] a, Comparable[] b){

    int inputIndex = 0;
    int aIndex = 0;
    int bIndex = 0;

    while(aIndex < a.length && bIndex < b.length){

            if(aIndex < a.length & a[aIndex].compareTo(b[bIndex]) < 0){
                input[inputIndex] = a[aIndex];
                aIndex++;
            } else{
                input[inputIndex] = b[bIndex];
                bIndex++;
            }
            inputIndex++;
    }
}

Example output:
Time taken for insertion: 8060 ms
Time taken for merge: 1714 ms
Time taken for insertion: 11533 ms
Time taken for merge: 23418 ms
Time taken for insertion: 5674 ms
Time taken for merge: 326 ms
Time taken for insertion: 8235 ms
Time taken for merge: 459 ms
Time taken for insertion: 9737 ms
Time taken for merge: 333 ms
Time taken for insertion: 4756 ms
Time taken for merge: 374 ms
Time taken for insertion: 1088 ms
Time taken for merge: 493 ms
Time taken for insertion: 899 ms
Time taken for merge: 1147 ms
Time taken for insertion: 783 ms
Time taken for merge: 474 ms
Time taken for insertion: 653 ms
Time taken for merge: 252 ms
-------------------------------------------------------
Insert average: 5141.8
Merge average: 2899.0

Thanks!
Edit: Updated pass by reference error, insert and merge are now both sorting their own arrays. Problem persists. Updated example output, if given more terms insert eventually still converges on a much lower value than when it starts

A: You pass randInput to insertion sort then pass this to merge sort.
In Java, Arrays are passed by reference. In call by reference if you change its array in a method, the changed array will be available to the calling array.
So randInput is sorted when pass to mergesotmethod.
See this:
//generate an array of random integers
Integer[] randInput = generateRandomArray(arraySize);
// randInput is random
insertionSort(randInput);

// randInput is sorted
mergeSort(randInput);


text:
Q: RDP add domain users broken I have 3 Windows Server 2008 R2 instances, all of which are virtual machines hosted on a single VMware ESX server:

*

*Domain controller with DNS services

*DHCP/RRAS

*File server

All three servers are configured with static IPv4 addresses. All servers are in the same domain, SOFTWARE. RDP is enabled on all 3 servers.
I can connect to the DHCP/RRAS server via RDP, but I cannot connect to the domain controller or the file server.
When I add RDP users to the File server (both are domain admins for testing), they show up like this:

What is happening? Why don't I even get a login screen for RDP on the domain controller?

A: Update
In this case the answer was point 5. But the other points are here for others who might have similar questions.
Account Resolution
From your screen shot the user icons with the question mark indicate that the SIDs for the user accounts can not be resolved, which is fundamental. This could either be that the user accounts have been deleted from your Active Directory or there is a connectivity problem between the file server and your domain controller. Based on that you are having other issues I will assume the account do still existing in Active Directory.
To resolve this I would go back to the basics. Check the following:
1. DNS Resolution
Can you resolve you domain controller (DC) by DNS name.
i.e. Run > Cmd.exe and use nslookup .
e.g. nslookup server1.consoto.com
If you can't resolve check that local network settings are point to the DC as the DNS server and that there is nothing between the two servers like Windows firewalls or devices that would prevent this type of connectivity. Also check that you can resolve DNS on the DC itself.
2. Time in Sync
Is the local time and time zones on both the DC and file server synchronised. They should be ideally exactly the same, and the file server should be getting it's time off the DC. The following can help resolve this:
   w32tm /config /syncfromflags:domhier
   w32tm /resync /rediscover
   net stop w32time
   net start w32time

When running Windows domain connected servers as VMs on ESX, disable host time sync for all VMs. This is done ether by:

*

*editing the .vmx file directly by browsing the datastore from the command-line or downloading the file from the datastore making the changes and uploading the file again.

*using Configuration Parameters option from the VM's settings in the vSphere or VI client to Add a row.

See http://kb.vmware.com/kb/1189 for more information.
Also it is also good practise to:

*

*Configure an external time source for you Windows DC. See http://support.microsoft.com/kb/816042

*Configure youyr ESX/vSphere hosts to get time from the DC. See http://kb.vmware.com/kb/1035833
3. Check Event Logs
There would most likely be a lot of errors and warnings logged in the event log.
4. Re-establish Trust
If all else fails you can re-establish the trust between the file server and the DC be disconnecting it from the domain, rebooting and rejoining it again.
Don't do this though if you have outstading time or DNS issues.
5. VM might have duplicate SIDs with another
When you build a Windows VM from a template in VMware vCenter you can choose to "customise" it. This reseals the operating system with sysprep when it starts for the first time after it is deployed from a template. Resealing an operating system when cloning or deployment templates is important because each Windows install has unique information such as security identifiers (SIDs) that is uses when connected to a domain. These can't be duplicated on another VM.
To read more about customisation in VMware vCenter see Sysprep file locations and versions.
If you don't have this option you can do it manually by using sysprep and using the generalize option, which will remove the computer SID and put the computer into the welcome wizard. Sysprep can be found C:\Windows\System32\sysprep\sysprep.exe
As a note, don't generalise your base template, because you can only do it 3 times and most people want to apply updates to their template on a monthly basis.
RDP to DC
It's hard to say exactly without more information, like event logs (may be you can post some error event IDs). But I would suggest that you check the file server issue first because it may be indicative of another issue. When the file server is working try to RDP from the file server to the DC.
I would also check http://technet.microsoft.com/en-us/library/cc794832(v=ws.10).aspx if you are attempting to connect to the DC using an older RDP client or operating system.
If that doesn't help please provide more information like where you are trying to connect from (is it across a RAS connection?) so we can help.
Hope that helps.

A: This is already said in Bernie White's answer comments, but just to make it clearer for newcomers:
Execute:
C:\Windows\System32\sysprep\sysprep.exe /generalize /oobe /reboot

Then rebind to the domain and reboot.


text:
Q: In GCP, is there a canonical way to scrape data from an API? I'm building an application that will periodically pull data from several APIs and write them to cloud storage for later processing by Dataflow. There are many different ways to do this so I wanted to sanity check before I jumped in.
My plan is this:

*

*For each API, Cloud Scheduler will hit an endpoint for an App Engine app

*The app will create a Compute Engine VM instance with a startup script that pulls the data from the API and writes it to storage

*When done, the VM will hit another endpoint on the App Engine app that shuts down the VM.

Is this a reasonable way to perform this sort of action? Is there a simpler or more straight-forward method? Thank you in advance for the replies.

A: Cloud Scheduler can schedule Compute Engine without App Engine however it seems that you cannot create and delete the VM with this method.

A: You can just use App Engine cron jobs to schedule the tasks. Your App Engine app cron handler can simply run the script that pulls data from the APIs. Maybe I am missing something, why do you need to use a Compute Engine instance to run the script?


text:
Q: Merge contents of a hash containing array of arrays in jQuery/JS for Highcharts I have two hashes:
var hash1 = { name: "hello1", data: [ [1, 1], [2, 1] ] };
var hash2 = { name: "hello2", data: [ [3, 1], [4, 2] ] };
var hash3 = {};

What I would like is to combine the hash into a new one (hash3) in such a way, as to only merge the array of arrays for the data object/key. The result should ideally be sorted based on the first element of the array (which really is a time value):
hash3 = { name: hello1, data: [ [1, 1], [2, 1], [3, 1], [4, 2] ] };

Prefer jQuery. But JavaScript and/or jQuery would both work.
Also, if someone could recommend a good book on manipulating data structures in JavaScript, I would appreciate it.
PS: All that manipulation is basically intended to combine two series into one for the Highcharts graphing library.

A: I don't know any good books about what you need, but simple solution will be to create function to merge series, see:
function mergeSeries(s1, s2) {
    var r = {};
    r.name = s1.name; // use first name
    r.data = s1.data.concat(s2.data); // merge arrays
    r.data.sort(function (a, b) {
        return a[0] - b[0];
    }); // sort data in series to be ascending by x-value
    return r;
}

Then use will be simple:
var hash3 = mergeSeries(hash1, hash2);

A: If you don't mind modifying hash1 in place it's as simple as:
> $.merge(hash1.data, hash2.data);
> hash1
Object {name: "hello1", data: Array[4]}

If you want to leave hash1 as is:
> hash3 = {'name': hash1.name, 'data': $.merge($.merge([], hash1.data), hash2.data)};
> hash3
Object {name: "hello1", data: Array[4]}

Or:
> hash3 = $.extend({}, hash1);
> $.merge(hash3.data, hash2.data);
> hash3
Object {name: "hello1", data: Array[4]}


text:
Q: How to turn grayscale into false color using PIL? I can't seem to figure out how to take my grayscale function and change it to give me false color. I know I need to break each color (R,G,B) into ranges and then assign colors based on the range for each color. Does anyone have any idea how this can work?
def grayscale(pic):
    (width,height) = pic.size
    for y in range (height):
        for x in range(width):
            pix = cp.getpixel((x,y))
            (r, g, b) = pix
            avg = (r + g + b)//3
            newPix = (avg, avg, avg)
            cp.putpixel((x,y),newPix)
    return cp

A: Since you never answered my final follow-on question in the comments, I've made a few guesses and implemented something to illustrate how it might be done using only the PIL (or pillow) module.
In a nutshell, the code converts the image a grayscale, divides up the resulting 0% to 100% luminosity (intensity) pixel range into equally sized sub-ranges, and then assigns a color from a palette to each of them.
from PIL import Image
from PIL.ImageColor import getcolor, getrgb
from PIL.ImageOps import grayscale

try:
    xrange
except NameError:  # Python 3.
    xrange = range

def falsecolor(src, colors):
    if Image.isStringType(src):  # File path?
        src = Image.open(src)
    if src.mode not in ['L', 'RGB', 'RGBA']:
        raise TypeError('Unsupported source image mode: {}'.format(src.mode))
    src.load()

    # Create look-up-tables (luts) to map luminosity ranges to components
    # of the colors given in the color palette.
    num_colors = len(colors)
    palette = [colors[int(i/256.*num_colors)] for i in xrange(256)]
    luts = (tuple(c[0] for c in palette) +
            tuple(c[1] for c in palette) +
            tuple(c[2] for c in palette))

    # Create grayscale version of image of necessary.
    l = src if Image.getmodebands(src.mode) == 1 else grayscale(src)

    # Convert grayscale to an equivalent RGB mode image.
    if Image.getmodebands(src.mode) < 4:  # Non-alpha image?
        merge_args = ('RGB', (l, l, l))  # RGB version of grayscale.

    else:  # Include copy of src image's alpha layer.
        a = Image.new('L', src.size)
        a.putdata(src.getdata(3))
        luts += tuple(xrange(256))  # Add a 1:1 mapping for alpha values.
        merge_args = ('RGBA', (l, l, l, a))  # RGBA version of grayscale.

    # Merge all the grayscale bands back together and apply the luts to it.
    return Image.merge(*merge_args).point(luts)

if __name__ == '__main__':
    R, G, B = (255,   0,   0), (  0, 255,   0), (  0,   0, 255)
    C, M, Y = (  0, 255, 255), (255,   0, 255), (255, 255,   0)
    filename = 'test_image.png'

    # Convert image into falsecolor one with 4 colors and display it.
    falsecolor(filename, [B, R, G, Y]).show()

Below is a composite showing an RGB test image, the intermediate internal 256-level grayscale image, and the final result of changing that into a false color one comprised of only four colors (each representing a range of 64 levels of intensity):

Here's another composite, only this time showing the conversion of an image that's already grayscale into the same palette of 4 false colors.

Is something like this what you're wanting to do?

A: It looks like that all you want to do is to determine the average brightness per pixel, and make each pixel grey. I would use either native Image functionality for that, or if you want to manipulate individual pixels, at least use numpy for that instead of a nested for loop. Example:
from PIL import Image, ImageDraw
import numpy as np

def makeGrey():
    W = 800
    H = 600
    img = Image.new('RGB', (W, H))
    draw = ImageDraw.Draw(img)

    draw.rectangle((0, H * 0 / 3, W, H * 1 / 3), fill=(174, 28, 40), outline=None)
    draw.rectangle((0, H * 1 / 3, W, H * 2 / 3), fill=(255, 255, 255), outline=None)
    draw.rectangle((0, H * 2 / 3, W, H * 3 / 3), fill=(33, 70, 139), outline=None)

    img.show()

    pixels = np.array(img.getdata())
    avg_pixels = np.sum(pixels, axis=1) / 3
    grey_img = avg_pixels.reshape([H, W])

    img2 = Image.fromarray(grey_img)
    img2.show()

if __name__ == '__main__':
    makeGrey()


text:
Q: fuzzy match and extract strings from a string vector to complete a dataframe I have a liste of french names with some small syntaxic differences.
names <- c("Benoit", "Arnoud (son)", "Arnoud", "Arnous", "Archer, Patrice*", "Archer", "Archer (father)", "André" )

"Arnoud (son)", "Arnoud", "Arnous" all these names belong to the same family. I would like to be able to create a dataframe object to group individuals by family
people1           |people2 |people3  |people4|
"Benoit"          | NA     |NA       |NA
"Arnoud (son)",   |"Arnoud"|"Arnous" | NA
"Archer, Patrice*"|"Archer"| "Archer"|"Archer (father)"
"André"           | NA     | NA      |NA


text:
Q: Why does Bootstrap Collapse keep removing the "collapse" class after expanding? I am using jQuery Collapse on an element that's inserted via Ajax.
When I apply the line below, it removes the collapse class. I need the class to remain so I can call collapse('hide') when the Ajax content needs to be closed.
$ajaxContent.html(data).find('.collapse').collapse();

Here's what I have in my .php file:

Here's what it ends up with after the jQuery is applied:

Why is it doing this and how do I fix it so the collapse class doesn't get removed?

A: Avoid calling your element's class collapse as it's being used by the plugin. Call it something else (eg. give it an id of collapse instead of class) and it should work.
EDIT: Alternatively you can use the plugin via data attributes (data-toggle="collapse"); I'd still refrain from calling the element's class collapse to avoid confusion.
EDIT #2: Following @friedi's comment to the question, I had a look at the example provided on Bootstrap's documentation on collapse and realized that they are actually using the collapse class too. Going out from the fact that you accepted my answer, I'm assuming that renaming / removing it still resolved the issue for you for some reason, but the origin of the issue may be laying somewhere else in your code (maybe another bit of js or the structure of your HTML, not sure).
EDIT #3: I think the culprit is probably in whatever your data variable is holding; I'm guessing that it doesn't have the class collapse added to whatever structure you're applying to $ajaxContent using the html function, and it's actually missing from there instead of it getting removed by the collapse function (which it is not, as it's not removing that class).


text:
Q: How to update a column with IDs partitioned by another column? I have table ACCOUNT with following two columns
id,acct_num
1,123
2,123
3,456
4,121
5,123

I want to assign integer value in id column partitioned by acct_num
This is what I want -
id,acct_num
1,121
2,123
2,123
2,123
3,456

The IDs should be ordered by acct_num, identical for multiple occurrences of acct_num and unique within their column.
I have tried this -
update a
set a.id = row_number() over (partition by acct_num order by acct_num)
from account a

It is throwing error that windowed functions can be used only in SELECT. Can anybody help me?

A: You could use a Common Table Expression (CTE):
;WITH CTE AS(
    SELECT *,
        RN = DENSE_RANK() OVER(ORDER BY acct_num)
    FROM account
)
UPDATE CTE SET id = RN

SQL Fiddle


text:
Q: Generate PNG with custom text from font file I have ~200 font files and need to generate .png files that have text inside them rendered using the font in question.
Example:
Roboto.ttf (or any font format)

=> .png file that has text "Roboto"

I'm wondering if anyone is aware of a quick way to do this (i.e. not creating the png's manually in graphic design software).
Thank you.

A: One possible solution is to use PrintMyFonts. This software offer great flexibility in sense of visualisation of font samples. You can show them on the screen, export to JPG, PNG, MS Word, RTF, html. Also you can preview fonts not installed in the OS. And of course you can select a lot of fonts and do the operation (review, export) over all of them. I test the software with >1000 fonts (not installed) and it work quite fast. This software can be run under Windows, Linux, MacOS.
P.S. No affiliation with the software author.


text:
Q: Deserialize JSON with multiple DefaultContractResolvers I can (mainly) deserialize json using a custom DefaultContractResolver, StudentPaginatedResultContractResolver. The only issue is that each property in every Student object in the collection Students is null.
How do I use the StudentContractResolver (or any other recommended method) to resolve these values correctly?
var json =
@"{
    'TotalCount': 854,
    'TotalPages': 9,
    'CurrentPage': 1,
    'PageSize': 100,
    'Result': [
        {
            'FName': 'Adam',
            'Mi':'A',
            'LName': 'Ant',
        },
        {
            'FName': 'Bob',
            'Mi':'B',
            'LName': 'Benson'
        }
    ]
}";

var settings = new JsonSerializerSettings
{
    ContractResolver = (StudentPaginatedResultContractResolver) Activator.CreateInstance(typeof(StudentPaginatedResultContractResolver))
};

var result = JsonConvert.DeserializeObject<StudentPaginatedResult>(json, settings);

DTOs:
public class StudentPaginatedResult
{
    public int TotalCount { get; set; }
    public int TotalPages { get; set; }
    public int CurrentPage { get; set; }
    public int PageSize { get; set; }
    public IEnumerable<Student> Students { get; set; }
}

public class Student
{
    public string FirstName { get; set; }
    public string MiddleInitial { get; set; }
    public string LastName { get; set; }
}

Contract resolvers
public abstract class ContractResolverBase : DefaultContractResolver
{
    protected Dictionary<string, string> PropertyMappings { get; set; }

    protected override string ResolvePropertyName(string propertyName)
    {
        PropertyMappings.TryGetValue(propertyName, out var resolvedName);
        return resolvedName ?? base.ResolvePropertyName(propertyName);
    }
}

public class StudentContractResolver : ContractResolverBase
{
    public StudentContractResolver()
    {
        PropertyMappings = new Dictionary<string, string>
        {
            {nameof(Student.FirstName), "FName"},
            {nameof(Student.MiddleInitial), "Mi"},
            {nameof(Student.LastName), "LName"}
        };
    }
}

public class StudentPaginatedResultContractResolver : ContractResolverBase
{
    public StudentPaginatedResultContractResolver()
    {
        PropertyMappings = new Dictionary<string, string>
        {
            {nameof(StudentPaginatedResult.Students), "Result"}
        };
    }
}

A: You could change your StudentPaginatedResultContractResolver to inherit from StudentContractResolver instead of ContractResolverBase.  Then make its constructor add to the existing PropertyMappings dictionary rather than replacing it:
public class StudentPaginatedResultContractResolver : StudentContractResolver
{
    public StudentPaginatedResultContractResolver()
    {
        PropertyMappings.Add(nameof(StudentPaginatedResult.Students), "Result");
    }
}

Fiddle: https://dotnetfiddle.net/APSRfn


text:
Q: SPF Record for Multiple DKIMs (including MX) I know very little about mail server administration. I'm piecing together user guides. I've bought a domain name, and [paid] Protonmail which allows using a custom domain. I've had this working for a while, but now I'm having trouble extending it for another DKIM record.
Objectives:

*

*Send and receive email using Protonmail from the custom domain

*Send-only email from a Postfix server I'm running

In order to send/receive email using Protonmail through my domain name, I've set up the following TXT records:
Host=@   protonmail-verification=e954fa...

Host=protonmail._domainkey    v=DKIM1; k=rsa; p=MGM0....

Host=@   v=spf1 include:_spf.protonmail.ch mx ~all

This has been working for months. Now I'd like to implement objective 2 (above). I created a DKIM key using opendkim:
sudo opendkim-genkey -b 8192 -h rsa-sha256 -r -v --subdomains -s postfix -d $(hostname --domain) && \
sudo sed -i 's/h=rsa-sha256/h=sha256/' postfix.txt

Then I've added the contents from postfix.txt, concatenating the long p string, to my DNS provider with another TXT record:
Host=[MY DOMAIN NAME]._domainkey      v=DKIM1; h=sha256; k=rsa; s=email; p=MEEij...

Where I think I'm struggling is with updating the spf record. How should it look? I thought it should be like so:
v=spf1 include:[MY DOMAIN NAME] include:_spf.protonmail.ch mx ~all

However, when testing sending an email from my Postfix server, some client servers reject the email, with the following log in my Postfix server:
E543D5E0003: host mail.tutanota.de[81.3.6.165] said: 450 4.7.1 Client host rejected: cannot find your reverse hostname, [MY POSTFIX SERVERS IP] (in reply to RCPT TO command)

I'm quite sure there is something wrong in my spf record. Are the arguments correct? And does the order matter? How can I use the Protonmail records for sending and receiving, but restrict my Postfix server to send-only? (does DNS even care about this directionality?)

A: Ok, let's start debugging this anyways ... (quite frankly, this is not a programming question so superuser would have been the better choice there, but I like that you wanna host your own mail :) )
Your SPF record should look like the following. Your own domain is not needed, cause the SPF record is saved in it's DNS records. Otherwise, that would (but won't) build a loop.
v=spf1 include:_spf.protonmail.ch mx ~all

The error itself you are seeing is related to the PTR lookup of your public IP, but could also be caused by the extra include and be a false positive here.
To make sure it's correct anyway, look it up manually:
On linux
dig -x <public ip of mail domain>

that will (should) print multiple lines, the one you're interested in:
;; ANSWER SECTION:
XXX.XXX.XXX.XXX.in-addr.arpa. 43200 IN    PTR     my-domain.com.

On windows:
nslookup <public ip of mail domain>

prints:
Server:  some.dns.server.com
Address:  XXX.XXX.XXX.XXX

Name:    my-domain.com
Address:  <public ip of mail domain>

crucial here is the "my-domain.com." part - if that is not your mail domain, then your hosting provider will most likely give you a way to change the PTR somewhere.
Try this and then we will look futher into it if necessary, of course it's hard to debug without being able to lookup all the information ;)


text:
Q: WPF TabControl: Mouse click event on (empty area of) tab bar In Firefox, double clicking the empty area of the tab bar creates a new tab. I want to implement this feature on WPF TabControl.
But how to handle the mouse click event?
I tried to handle the MouseDoubleClick event of TabControl, but unfortunately I got the opposite result: clicking on the empty area of tab bar has no effect, it works only when I click on other areas.
    <TabControl MouseDoubleClick="TabControl_DoubleClick">
        ...
    </TabControl>

Thanks.

A: You need to handle the event for the TabItem and not the TabControl.For example, this worked for me:
private void tabItem1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
           . . .
        }

A: The TabControl contains a TabPanel, but even if you attach a Mouse-event to it (it is no control so there is no DoubleClick but you can use MouseUp and check the ClickCount for example) that event will not fire in the "empty space".
The easiest way to do this then might be to copy the default template (See MSDN, Default WPF Themes link) and add a lookless button or something like it in that area.

A: Give your "empty space" a background.
In the code below, I've set the TabItem control template to a StackPanel whose background is not defined. If the StackPanel has a background defined, even Transparent, you can click on the empty space.
However, if you set the background on the StackPanel element itself it will use that background on the selected tab item as well as the unselected items, which is probably not what you want (since background is usually a major way to show which is item selected). So you need to set a trigger for the background for IsSelected=False.
<ControlTemplate TargetType="TabItem">

    <Border BorderBrush="Black" BorderThickness="{TemplateBinding BorderThickness}">
        <StackPanel Name="Panel">
            <Ellipse Margin="0 20 0 10" Height="30" Width="30" Fill="Gray"/>
            <Label Name="Header" Content="{TemplateBinding Header}" HorizontalAlignment="Center" FontWeight="Bold"/>
        </StackPanel>
    </Border>

    <ControlTemplate.Triggers>
        <Trigger Property="IsSelected" Value="False">
            <Setter TargetName="Panel" Property="Background" Value="White"/>
        </Trigger>
        <Trigger Property="IsSelected" Value="True">
            <Setter TargetName="Panel" Property="Background" Value="Blue"/>
            <Setter TargetName="Header" Property="Foreground" Value="Transparent"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>


text:
Q: FluentValidation checking for duplicate entity in a sub-collection I have a MainEntity class and it has a collection of SubEntity. The following is the current validation:
public class MainEntityValidator : AbstractValidator<MainEntity>
{
    public MainEntityValidator()
    {
        RuleFor(x => x.SubEntities).SetCollectionValidator(new SubEntityValidator());
    }

    public class SubEntityValidator : AbstractValidator<SubEntity>
    {
        public SubEntityValidator()
        {
            RuleFor(x => x.Field1).NotNull();
            RuleFor(x => x.Field2).NotNull();
        }
    }
}

How can I add a validation rule so that only unique SubEntity objects (based on Field1 and Field2) must be in the collection?

A: If you need to apply validation rule to collection property but still need access to main model and(or) whole collection, not only item being validated, then RuleForEach method is your choice:
var comparer = new SubEntityComparer();

RuleForEach(x => x.SubEntities)
    .Must((model, submodel) => model.SubEntities.Count(xsub => comparer.Equals(xsub, submodel)) == 1) // one match that ReferenceEquals hit
    .WithMessage("The item with values {0}, {1} has duplicates in collection of {2} items",
        (model, submodel) => submodel.Field1,
        (model, submodel) => submodel.Field2,
        (model, submodel) => model.SubEntities.Count); // in validation message generation you can access to current item as well as to main model

If you need only one error message for validation rule you described — you can apply simple predicate rule to collection property SubEntites:
RuleFor(x => x.SubEntities)
    .Must(coll => coll.Distinct(new SubEntityComparer()).Count() == coll.Count)
    .WithMessage("One or more items in collection of {0} items are duplicates",
        (model, coll) => coll.Count); // has access to collection and to main model

In both cases I used the same equality comparer, but you can override Equals method as well, and use overloads of IEnumerable extension methods with overload, that exclude EqualityComparer parameter.
Code of EqualityComparer listed below:
public class SubEntityComparer : IEqualityComparer<SubEntity>
{
    public bool Equals(SubEntity x, SubEntity y)
    {
        if (x == null ^ y == null)
            return false;

        if (ReferenceEquals(x, y))
            return true;

        // your equality comparison logic goes here:
        return x.Field1 == y.Field1 &&
               x.Field2 == y.Field2;
    }

    public int GetHashCode(SubEntity obj)
    {
        return obj.Field1.GetHashCode() + 37 * obj.Field2.GetHashCode();
    }
}

Update:
In both ways to implement validation for collection you still can use SetCollectionValidator(new SubEntityValidator()) to validate each item with simple rules independently.

A: I suppose the answer to your question is to compare every item in your collection to every other item and fail validation when to objects are "equal".  Though I would not recommend doing that if your collection could contain more than a trivial number of items.  A better approach would be to implement Equals() and GetHashCode() so that the collection types in the base class library will handle your SubEntity objects predictably.  I would post an example but I don't know what your objects look like as you have not posted them.  At any rate, if you implement those methods in a meaningful way you can define your collection as a type that already has the appropriate unique constraints (HashSet of T for instance).


text:
Q: What does "⌅" symbol mean? I know this is a horribly simplistic question, but.... what does this key symbol mean:
And I have a valid reason for asking... Textmate says it's a shortcut key and I can't figure out how to trigger it other than via mouse-menus :)

A: ⌅ is enter, which is not the same as return (↩): http://blog.macromates.com/2007/textmates-many-key-shortcuts/

A: I believe it's "Enter" (not to be confused with "Return").


text:
Q: Java, when I put my User in a Map, it's not working I'm developing two api for a minecraft server, a proxy, and a spigot, when a player connects, the proxy API fetches the player on the database, then sends it on redis, then the api spigot will look for the player on redis, and save it in a Map, and that's where the problem is, I have a "User#get" method like this:
public static User get(UUID uuid) {
    return users.getOrDefault(uuid, fetchUser(uuid));
}

And a "User#fetchUser" like this:
private static User fetchUser(UUID uuid) {
    return Main.instance.getRedisAPI().get(uuid.toString(), User.class);
}

The key redis is the uuid of the player, and the value, is the user class serialized in JSON, with the api Gson
I recently knew that Gson, to deserialize, created his own empty constructor, and filled the fields by reflection, which I do not want, because it is in my constructor that I put the User in the map. So I created my own TypeAdapter that implements JsonDeserializer, in order to run the constructor. it works, the constructor is well executed, but the user is not put in the map! So every time I make a User#get, it runs the fetchUser, and it ends up crashing because it's too many requests. I'm putting my classes in a pastebin for you to watch. (sorry if that's not the way to do it, it's the first time I'm posting on stackoverflow, and sorry for my english, I'm french and I use google translation)
User.java > https://pastebin.com/4ta4XDqX
RedisAPI.java > https://pastebin.com/GjWPUf4m
Serializer.java > https://pastebin.com/k6g1KYYF
UserDeserializer.java > https://pastebin.com/0LF7trSR
Thank you in advance.

A: Map::getOrDefault does:

Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

So, it does not add any value to the map at all. You're also always eagerly executing the User::fetchUser method, whether the UUID exists in the map or not.
It sounds like you need Map::computeIfAbsent instead, which:

If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.

i.e.
public static User get(UUID uuid) {
    return users.computeIfAbsent(uuid, User::fetchUser);
}

Where User::fetchUser is only executed if the UUID was not found in the map already.


text:
Q: C++ Find all .wav files I'm trying to create an application in C++ that would search all .wav files on the disk (including all subfolders and their subfolders and so on..., whole disk search, like antivirus search on Avast and similar) and store them in a string and save to a text file later on. I'm having troubles figuring out the way on how to actually do this and I could use some help.
This is what I done so far, it's only searching the C drive root folder and I don't know what to do now. I know I should use a loop of some sort but I don't know how to actually do it, there's no logical way that I can think to do it.
void finddata()
{
    MessageBox(NULL, "finddata called", "Started", MB_OK | MB_ICONINFORMATION);
    WIN32_FIND_DATA FindFileData; // A pointer to the WIN32_FIND_DATA structure that receives information about a found file or directory.
    HANDLE hFind; // Used to check the return value
    hFind = FindFirstFile("C://*.wav", &FindFileData);
    if(hFind == INVALID_HANDLE_VALUE)
    {
        MessageBox(NULL, "INVALID_HANDLE_VALUE", "Failed", MB_OK | MB_ICONINFORMATION);
    }
    else
    {
        string file;
        file = FindFileData.cFileName;
        file.append("|");
        MessageBox(NULL, file.c_str(), "YO", MB_OK | MB_ICONASTERISK); // string.c_str() to conv to LPCSTR
        FindClose(hFind);
    }
}

The MessageBox at the end is just there as a test, I'll remove it later on. I'm currently learning C++ and this is a sort of a beginner's project so I can get a hang of it.
Also, are there any limitations in size for the string data type? Thanks.

A: Obviously, you do indeed need a FindNextFile call, and repeat that using a loop of some sort, until it returns a "no more files" return code.
To then search the entire disk, you will need to look for directories in the "current directory" (the root directory), and for every directory search into it - you can do that either by calling finddata recursively (adding the name of the directory as an argument to the function), or implement a stack in the code to track which directory you are in, and which one to "walk back to" for the next level.
I'm intentionally NOT writing the code for you, but describing what you need to do, since you are the one learning programming. I did this sort of thing in 1985 or so.

A: Recursivity is the way.
Here is a possible implementation (for inspiration, but do it your own way):
// Filtering by the given extension
void AppendFile(list<string>& fileList, const string& directory, const string& fileName, const string& extFilter)
{
    string fileExtension = fileName.substr(fileName.find_last_of(".") + 1);
    if (!fileExtension.empty())
    {
        // Extension doesn't match: return
        if (extFilter.find(fileExtension) == string::npos)
            return;
    }
    // If we have a match: append file to list
    fileList.push_back(directory + fileName);
}

// Getting the files of the given extension recursively (or not)
void GetFiles(list<string>& fileList, string directory, const string& extFilter, bool recursively = true)
{
    string filePath;

    directory += "\\";
    string filter = directory + "*";

    WIN32_FIND_DATA FindFileData;
    HANDLE hFind = FindFirstFile(filter.c_str(), &FindFileData);

    if (hFind == INVALID_HANDLE_VALUE) return;

    do
    {
        // If we find a (sub-)directory
        if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
            // Here comes the recursive call
            if ((recursively) && (lstrcmp(FindFileData.cFileName, TEXT(".")) != 0) && (lstrcmp(FindFileData.cFileName, TEXT("..")) != 0))
                // The 'GetFiles()' calls itself on the sub-directory
                GetFiles(fileList, directory + FindFileData.cFileName, extFilter);
        }
        else
            // If we find a file: simply append it to the list
            AppendFile(fileList, directory, FindFileData.cFileName, extFilter);
    }
    while (FindNextFile(hFind, &FindFileData) != 0);

    FindClose(hFind);
}

Usage :
list<string> fileList;
GetFiles(fileList, "C:\\root_dir", "wav");

for(list<string>::iterator it = fileList.begin(); it != fileList.end(); ++it)
{
    cout << (*it) << endl;
}


text:
Q: How can I avoid having a separate custom TypeDescriptorProvider for each of my classes? I've added functionality to my project that allows the users to add their own custom properties to objects. I've created my own custom TypeDescriptor, PropertyDescriptor and TypeDescriptorProviders etc.. etc.. to do this.
Here's my problem. Right now I have it all working, but had to create a separate TypeDescriptionProvider for each object object type that can have the custom properties. Here's what my TypeDescriptionProviders look like
//type AClass Custom Provider
class AClassTypeProvider : TypeDescriptionProvider
{
    private static TypeDescriptionProvider defaultTypeProvider = TypeDescriptor.GetProvider(typeof(AClass));

    public AClassTypeProvider (): base(defaultTypeProvider)
    {

    }

    public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
    {
        ICustomTypeDescriptor defaultDescriptor = base.GetTypeDescriptor(objectType, instance);

        //returns a custom type descriptor based on a UserPropertyHostType enum value, and the default descriptor
        return new InfCustomTypeDescriptor(UserPropertyHostType.SiteRegion, defaultDescriptor);
    }
}

//type BClass Custom Provider
class BClassTypeProvider : TypeDescriptionProvider
{
    private static TypeDescriptionProvider defaultTypeProvider =   TypeDescriptor.GetProvider(typeof(BClass));

    public BClassTypeProvider (): base(defaultTypeProvider)
    {

    }

    public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
    {
        ICustomTypeDescriptor defaultDescriptor = base.GetTypeDescriptor(objectType, instance);

        //returns a custom type descriptor based on a UserPropertyHostType enum value, and the default descriptor
        return new InfCustomTypeDescriptor(UserPropertyHostType.Building, defaultDescriptor);
    }
}

So each of my custom TypeDescriptionProviders calls the base(TypeDescriptionProvider parent) base constructor by passing it the default TypeDescriptionProvider of a specific type.
The GetTypeDescriptor() method calls base.GetTypeDescriptor() to get the default descriptor which is then used by my custom type descriptor to add on the custom properties.
Is there some way to combine these into a single generic custom TypeDescriptionProvider that has the same functionality, but is not tied to a specific type? Can I skip providing the parent TypeDescriptionProvider in the constructor but later set it in the GetTypeDescriptor() method when I know specifically what type of object is being queried? Or is there some other way of getting the default descriptor of a type other then calling the base.GetTypeDescriptor(Type t,object ins) method?

A: This generic class should do what you want :
class CustomTypeProvider<T> : TypeDescriptionProvider
{
    private static TypeDescriptionProvider defaultTypeProvider = TypeDescriptor.GetProvider(typeof(T));

    public CustomTypeProvider(): base(defaultTypeProvider)
    {

    }

    public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
    {
        ICustomTypeDescriptor defaultDescriptor = base.GetTypeDescriptor(objectType, instance);

        //returns a custom type descriptor based on a UserPropertyHostType enum value, and the default descriptor
        return new InfCustomTypeDescriptor(UserPropertyHostType.SiteRegion, defaultDescriptor);
    }
}

A: I have handled this in the past by using a generic type:
public class MyTypeDescriptionProvider<T> : TypeDescriptionProvider
{
  public MyTypeDescriptionProvider()
    : base(TypeDescriptor.GetProvider(typeof(T)))
  {
  }
}

I am pretty sure you could handle it similarly in a non-generic type by passing the type as a constructor parameter:
public class MyTypeDescriptionProvider : TypeDescriptionProvider
{
  public MyTypeDescriptionProvider(Type t)
    : base(TypeDescriptor.GetProvider(t))
  {
  }
}

This is probably preferable if you don't need to use the type within the provider -- haven't tested it though.
Then when using this provider, classes are registered along the lines of:
TypeDescriptor.AddProvider(new MyTypeDescriptionProvider<ClassA>(), typeof(ClassA));
TypeDescriptor.AddProvider(new MyTypeDescriptionProvider<ClassB>(), typeof(ClassB));

etc.


text: Q: Constant boolean variables in multivariate time series observations I am observing multivariate time series with some of its variables being boolean. One example of such observing multivariate time series observation has one of its features f1=1 during all time series, and another observation has f2=0 all time series, and in all off the observations I gathered boolean variables are constant. My question is should these variables be somehow preprocessed or it is totally fine to fit nn with such multivariate time series data with constant boolean features? Thank you in advance. I am newbie in these things.


text:
Q: Changing column data type recursively for all tables without affecting constraints How to convert all varchar columns in schema to nvarchar effectively, without dropping constraints
I am using this procedure
CREATE PROCEDURE VarCharToNvarChar
AS
BEGIN
DECLARE curChangeTypes CURSOR FOR
     SELECT column_name,
            table_name,
            character_maximum_length
     FROM INFORMATION_SCHEMA.COLUMNS
     WHERE DATA_TYPE='VARCHAR'
       AND table_name IN (SELECT DISTINCT table_Name
                          FROM INFORMATION_SCHEMA.COLUMNS
                          WHERE DATA_TYPE='VARCHAR');

OPEN curChangeTypes;
DECLARE @cn VARCHAR(50),
        @tn VARCHAR(50),
        @cml INT;
DECLARE @str VARCHAR(8000);

FETCH NEXT FROM curChangeTypes INTO @cn,@tn,@cml;

WHILE(@@FETCH_STATUS = 0)
BEGIN
  IF(@cml = -1)
     SET @str = 'ALTER TABLE ' + @tn + ' ALTER  COLUMN ' + @cn + ' NVARCHAR(MAX)';
  ELSE
     SET @str = 'ALTER TABLE ' + @tn + ' ALTER  COLUMN ' + @cn +
                ' NVARCHAR('+CAST(@cml AS VARCHAR)+')';

  EXEC(@str);
  FETCH NEXT FROM curChangeTypes INTO @cn,@tn,@cml;
END
CLOSE curChangeTypes;
DEALLOCATE curChangeTypes;
END

It fails due to constraints on fields
If we drop constraints procedure executed successfully
But constraints need to be intact
Suggest the best way to achieve the alter query [ varchar-->nvarchar ] without dropping constraints


text:
Q: Bash Date error between 0 to 1 am I'm working on bash and date values, now I have a problem when the hours are between 00 to 00:59:59, bash give me a 'invalid date error'
How can I work with thats values?
Ex:
date --date="2014/09/07 00:59:00" +%H
date: invalid date '2014/09/07 00:59:00'

A: In your timezone (check the $TZ variable), there was a switch between daylight saving time and normal time. The hour you specified was skipped and never existed.
cf.
TZ=America/Godthab date --date="2013-03-30T22:32:00.000"

taken from The time that never was.


text:
Q: memtest86 5.31b Memory Type Unknown I have HP c7000 chassis with gen9 blade and have 4x16G (total 16GB) memory. HP iLO saying you have degraded so i start running memory test using memtest86 5.31b and its been 1 hour and it did 5 test but didn't detected anything wrong so does memtest86 5.31b is lying?

Does using latest version of memtest86 will help, reason i am running older because its already configured for PXE boot. (newer version doesn't support PXE until you buy it)


text:
Q: Como alterar formato de data em PHP Olá, não sou expert em PHP, e tenho uma dúvida. Tenho este trecho de código:
Quartos disponíveis para

<?php echo isset( $_GET['start-date']) ? $_GET['start-date'] : ''; ?> à

<?php echo isset( $_GET['end-date'] ) ? $_GET['end-date'] : ''; ?>

Que me retorna tipo assim, exemplo:
" QUARTOS DISPONÍVEIS PARA  2018-07-20 À  2018-07-24

Como faço pra data fina no formata dia/mês/ano ?

A: Exemplo ideone
//verificação se foram iniciadas
if ((isset($_GET['start-date']) && isset($_GET['end-date'])){

  // As datas
  $dataInicial = $_GET['start-date'];
  $dataFinal = $_GET['end-date'];

  // Quebra as strings nos "-" e transforma cada pedaço numa matriz
  $divisorIni = explode("-", $dataInicial);
  $divisorFin = explode("-", $dataFinal);

  // Inverte os pedaços
  $reversoIni = array_reverse($divisorIni);
  $reversoFin = array_reverse($divisorFin);

  // Junta novamente a matriz em texto separado por tracinho (-)
  $dataIni = implode("-", $reversoIni);
  $dataFin = implode("-", $reversoFin);

      echo 'Quartos disponíveis para';
      echo '';
      echo $dataIni;
      echo ' à ';
      echo $dataFin;

}

Outra forma:
$dataInicial = $_GET['start-date'];
$divisorIni = explode("-", $dataInicial);
$dataIni = $divisorIni[2]."-".$divisorIni[1]."-".$divisorIni[0];


text:
Q: Want to write my own program. Need to ask if similar programs exist Can I ask people if a similar program already exists?   If not, any ideas where to ask?  It is something that people might use a certain vocabulary for, but maybe I don't know that vocabulary, so it is kind of hard to search for it.

A: Is it a programming related program, like a parser, a library or some other development tool?
If it is, it should be fine on SO.
Otherwise, I would say Superuser.com is the right choice.


text:
Q: Login user at startup public class MvcApplication : HttpApplication
{
    protected void Application_Start()
    {
        FormsAuthentication.SetAuthCookie(1.ToString(), true);
    }
}

An exception of type 'System.Web.HttpException' occurred in
  System.Web.dll but was not handled in user code
Additional information: Request is not available in this context

How else can I automatically login a user without having to do a whole new page request?

A: What part is confusing you? Forms Auth requires a request in order to work. Part of what it does is send a cookie to the client, and it can't very well do that if there's no client. Application_Start runs outside of the request, so you can't access the request object from there. Even if you could, this isn't run for each request, so it would only work for the first user that caused it to activate.
If you want to do this in a global way, but within the request scope, you'll need to use something like a custom action filter or a custom membership provider. Not sure which would be best for something like or even if an action filter would work, but that's your options.


text:
Q: Keycloak java admin client verification email use standard emailVerification template in keycloak's java admin client its possible to send verify email to the user:
realmUsersResource.get(userId).executeActionsEmail(List.of(startingAction))

or by
realmUsersResource.get(userId).sendVerifyEmail(keycloakResource)

but as we see the email content is different vs standard verification email being send by standard Keycloak UI registration form.
While using standard form it sends email using emailVerificationSubject, emailVerificationBody taken from messages_en.properties ( in keycloak/theme/base/email/messages folder )
but when its send using admin client it uses executeActionsSubject, executeActionsBody.
I am registering user on my backend side, using admin client but I would like to use this emailVerification(Subject/Body) for emails.. how to do it ? is it possible ?
thanks


text:
Q: Why is ratio constraint not respected on iPhone XR/Xs Max? I have a small UIImageView for displaying a user's profile photo. This looks fine on iPhone 6S, but when I run it on iPhone XR, the image is reduced to a tiny dot on the screen. I tried with simulators of different models, this problem only appears on XR/Xs Max simulators.
In the end, I found the problem: I had 2 constraints on this UIImageView: a width constraint of 32 points and a ratio constraint of 1. When I delete the ratio-constraint and add a height constraint of 32 points, all works fine.
I am wondering what causes iPhone XR/Xs Max to fail to respect the ratio-constraint? Is ratio constraint no longer supported in new models?
The simulators are all running iOS 12.2.
--EDIT--
Another UI layout issue only on XR/Xs Max, not related to ratio. I put a UIImageView into a container View, and set its frame like this:
imageView.frame = self.containerView.bounds
imageView.contentMode = .scaleAspectFit

The imageView look fine on all other models, filling the containerView. But on XR/XsMax, there is a margin on the right and bottom:

What am I missing here?

A:
In the end, I found the problem: I had 2 constraints on this UIImageView: a width constraint of 32 points and a ratio constraint of 1.

That does work. In all probability you configured the aspect ratio constraint incorrectly.

imageView.frame = self.containerView.bounds

Here, everything depends on when you say this. If you say it too early, such as in viewDidLoad, the containerView itself does not yet have its real bounds, so you'll end up with a wrong result. This is why using constraints is so much better. Using constraints, you can guarantee that the image view will fit its superview.
So go back to using constraints, configure the aspect ratio correctly, and all will be well.


text:
Q: How to check if a column is equal to a variable which can be null I have a table that contains a varchar column that allows null or empty values.
I'm writing a stored procedure that contains a variable that can be assigned to a null value or a regular string (not empty)
It's defined like this:
declare @myvar varchar(50)

Now I'm trying to write a query that returns the rows where the column is equal to this variable or it is empty or null. So far I thought this was going to work:
select * from mytable where mycolumn =@myvar or mycolumn =''

However if the column is null and the variable is null it will not return any values.
I know I can make it work doing something like this:
select * from mytable where (mycolumn = @myvar and mycolum is not null) or mycolumn is null or mycolumn =''

Is there a better way of doing this?
PS: I would prefer not to do ANSI_NULLS OFF
Thanks

A: You don't need this part: and mycolum is not null since, as you said, if your variable is NULL it still won't match. So I think that this is actually the best way:
select *
from mytable
where mycolumn = @myvar or mycolumn is null or mycolumn =''

If you want to do the same, but with less conditions, you could do:
select *
from mytable
where mycolumn = @myvar or ISNULL(mycolumn,'') = ''

but this will not use an index (if there is one) on mycolumn.

A: You're writing
select * from mytable where (mycolumn = @myvar and mycolum is not null) or
   mycolumn is null or mycolumn =''

Since if mycolumn is NULL, it'll be true, you don't need to guard against it using and mycolum is not null, so it can be simplified to;
SELECT * FROM mytable
WHERE mycolumn IS NULL OR mycolumn ='' OR mycolumn = @myvar

A: If you want the column to exactly match the parameter (including null value)
DECLARE @myVariable varchar(10)

SELECT *
FROM mytable
WHERE ((@myVariable IS NULL AND myColumn IS NULL) OR myColumn = @myVariable)


text:
Q: Need to create separation between floated divs, but keep breaking them when adding margin I'm using bootstrap and trying to float together three divs and then add some separation between them. when i try to add any margin, the divs break and collapse below each other.
If this involves using a clearfix, could you please explain it to me as well as help me solve it?
Here's the code...thank you :)

.quick-fact-boxes {

    #quick-fact-box-one {
        height: 500px;
        background: #34495e;
        float: left;
    }

    #quick-fact-box-two {
        height: 300px;
        background: #bdc3c7;
        float: left;
    }

    #quick-fact-box-three {
        height: 200px;
        background: #95a5a6;
        float: left;
    }
}

A: While you are using bootstrap you don't need to add float and margin in CSS, you just need to use correct classes in HTML