Can't connect to DAX from EC2 instance in same VPC

Question: I'm in my EC2 instance in the same VPC as my DAX cluster....the cluster's SG is default (allow all) and I still can't connect
Here's an abbreviated code sample:
from amazondax import AmazonDaxClient

dax = AmazonDaxClient(
    endpoint_url="mycluster.i5cagb.clustercfg.dax.use1.cache.amazonaws.com:8111"
)

After waiting a bit, I get this error:
Failed to configure cluster endpoints from
[('mycluster.i5cagb.clustercfg.dax.use1.cache.amazonaws.com', 8111)]

I tried diagnosing with nc too:
$ nc -zv mycluster.i5cagb.clustercfg.dax.use1.cache.amazonaws.com 8111
Ncat: Version 7.50 ( https://nmap.org/ncat )
Ncat: Connection to 172.31.43.69 failed: Connection timed out.
Ncat: Trying next address...
Ncat: Connection to 172.31.58.224 failed: Connection timed out.
Ncat: Trying next address...
Ncat: Connection timed out.

Comment: What do you mean by "allow all"? Do you have an inbound rule on the SG that allows all traffic? What is the network topology of the EC2 instances and cluster within the VPC? Are the EC2 instances in the same SG as the cluster? It does look like a network reachability problem. Basically you need to ensure that there is nothing blocking the traffic between the EC2 instance and the cluster network interface. There is a step in the [documentation](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.create-cluster.console.configure-inbound-rules.html) about configuring the SG rules
Comment: Thanks @AbdelrahmanElhaddad it ultimately did end up being a SG issue.
Answer: As @AbdelrahmanElhaddad pointed out in his comment, this ended up being a security group issue.
Comment: Specifically, I hadn't set a `SecurityGroupIds` entry on my cluster.


RuntimeException: Failed to start the session because headers have already been sent by

Question: New to Drupal, I just created a new custom module in Drupal 9 to see how it works I was trying to test with a minimal piece of code. I just enable this module and got this error, now I can't open anything and getting this error on every page nothing is happening even if I change anything in code. This is my custom module code.
check_hookcalls.info.yml
name: hook calls checking
description: module for testing hooks
core_version_requirement: ^8 || ^9
type: module

check_hookcalls.module
<?php

function check_hookcalls_node_presave() {
  die;
}

?>

The error I get is the following one.

[13-Jul-2021 15:34:49 Europe/Berlin] RuntimeException: Failed to start the session because headers have already been sent by
"C:\softwares\xampp\htdocs\d9_firstexperience\2\modules\check_hookcalls\check_hookcalls.module" at line 10. in
C:\softwares\xampp\htdocs\d9_firstexperience\2\vendor\symfony\http-foundation\Session\Storage\NativeSessionStorage.php on line 152
Comment: Remove the closing php tag
Comment: Drupal coding standards say not to add the closing PHP tag exactly to avoid that issue.
Comment: The [Coding standards](https://www.drupal.org/docs/develop/standards) guide and its sub-guides are a start.
Comment: Yes, I just removed the tags, and restarted apache it start working but it's strange.
You can post it as an answer I will accept.
Comment: Okay, thank you I have to learn standards.
Answer: Per the Drupal coding standards, the closing php tag should be omitted.
The PHP Code Tags section of the coding standards (as well as this stackoverflow answer) give a good overview of why it's a good practice to omit them in general:

Removing it eliminates the possibility for unwanted whitespace at the
end of files which can cause "header already sent" errors, XHTML/XML
validation issues, and other problems.
The closing delimiter at the
end of a file is optional.
PHP.net itself removes the closing
delimiter from the end of its files (example: prepend.inc), so this
can be seen as a "best practice."


How to generate secure private urls in CakePHP?

Question: I like to create a secure URL for a user for his entries (delete and edit links).
for ex, this is my actual URL
http://localhost/project/blogs/delete/1/test-title

what i want to do is,
http://localhost/project/blogs/delete/4324143563443/test-title (some hash made of salt+user auth id)

My main purpose is to create a secure hash along with the URL for delete and edit method.
Is there any custom method's available?
I searched in CakePHP Security functions http://book.cakephp.org/2.0/en/core-utility-libraries/security.html and not sure whether its the right way to do it or not sure which algorith to use)
Comment: Why are you doing this? So the user cannot see the id of the post they are about to delete? Generally speaking, you cannot un-hash a hash.
Comment: Only for delete and edit links i meant. So anyone user cannot delete or edit my post. Ofcourse, i can do that check in my controller itself, but, i want to make the URL look secure.
Comment: I can't say I can see a light at the end of the tunnel for this technique. You could pass a named param such as `http://localhost/project/blogs/delete/1/hash:4324143563443` but it wouldn't really serve much purpose. I personally would create a `roles` table and assign roles to users.
Comment: just found this: https://github.com/signified/CakePHP-Crypt-Component. Is it what you are looking for?
Comment: You can use varchar(36) as a table's primary key data type.
Cakephp will generate UUID for the all new records.
Answer: Firstly, although I am not quite clear on how/why you want to do this, it sounds like you want to "protect" these links through obscuring their URL's. This is known as "Security through Obscurity" and is generally frowned upon.
In Cake (and most apps), the usual way to achieve this is to allow users to login (see: Auth Component) and then, for example, in your delete action (i.e. for the URL /delete/1) requests would be checked for a valid user session, and that the user has sufficient permissions to delete.
Although I would strongly reccommend otherwise, if you did wish to create these obscure URLs then you should probably use Security::hash();. The problem with this is that you wouldn't be able to just hash the id and then determine the id from the hash directly (thats the whole point!). Instead you would need to store the hashes in the database and then query for the hash (each post could have a unique hash generated either from the id or just random data, either would do).
Answer: As already mentioned "Security by obscurity" isn't very smart. Nevertheless easiest way to achieve what you want is use UUID's for your table's primary key instead of numeric auto increment.
Comment: It's probably worth noting that whilst using UUID's would mean the sequence of primary keys was unpredictable, the "protected" URL would still be predictable from the "public" URL, which i'm fairly sure is what the OP want's to avoid. I think the easiest way to bind something unpredictable to each id would be by storing something (hash etc.) in the db.
Comment: Right. Anyways his approach is crappy in the first place so whatever way you generate the url it's not going to be truly secure :)


Read contents of uploaded file before saving

Question: I am using hook_node_presave() to build a module (which I am new to) in Drupal 7. I am able to reference fields via $node->field_foo[$node->language][0]['value'] (which I have seen mentioned several times here in Drupal Answers).
This particular content type I am working on has the ability to upload files. I am new to Drupal 7, but I noticed that:

First, the user uploads the file
Then, the user saves the node (with a reference to the file)

How do I access the content of that file after it has been uploaded, with hook_node_presave()?
Answer: The ['value'] value is typically found on fields that just store 1 kind of thing, like a text field. Other field types use whatever they need – case in point, the file field type will have an array of many values:
$node->field_some_file_field_name['und'][0] = array(
  fid => 650, // The file ID, which is important and cool.
  display => 1, // Show the file when a user views the node.
  description => 'foo',
  uid => 7, // The user ID who uploaded this file.
  filename => some_file.pdf, // The **original** filename.
  uri => public://some-dir/some_file.pdf, // The URI to access the actual file.
  filemime => application/pdf,
  filesize => 3067583,
  status => 1,
  timestamp => 1352331360,
);

The FID is a cool thing, because the file_managed table stores the references to files (including all of the info above) and an entity only needs to know the FID in order to join with this table and get all of the file's metadata without reading the file.
To read the contents of the file, you have a few options:

drupal_realpath($uri) function to generate the server path to
the file
file_create_url($uri) function to generate an HTTP path
to the file (i.e. an image to be displayed in an  tag.

Not sure what you mean explicitly by "read contents", but a literal file_get_contents() would look like this:
$filepath = drupal_realpath($node->field_some_file_field_name['und'][0]['uri']);
$file_contents = file_get_contents($filepath);

If you want to check the MIME or filesize or something like that, you already have that data available to you in the field's array.
If you can elaborate on "reading" the file and what you might like to do before the file field is attached to the node, please update your post and I'll try to update this answer accordingly. There may be another, better place for your work to happen.


How to calculate this sum of inverses?

Question: I want to calculate this sum:
$$-m u \sum_{i=1}^N \frac{1}{M+im}$$
I tried a substitution like this:
$$-m u \sum_{k=M+m}^{M+Nm} \frac1k$$
But it seems to have become complicated!
Does anyone have an idea how to evaluate the sum?
Comment: You need something called harmoic numbers.
Comment: Yes, there is no closed formula for your sum, see the [answer](http://math.stackexchange.com/q/1896995) of @Claude Leibovici
Answer: As Zack Ni commented, this corresponds to generalized harmonic numbers
$$\sum_{i=1}^N \frac{1}{M+im}=\frac 1m\sum_{i=1}^N \frac{1}{\frac Mm+i} =\frac 1m\left({H_{\frac{M}{m}+N}-H_{\frac{M}{m}}}\right)$$

How to calculate this sum of inverses?


How Do I approach this geometrical locus problem?

Question: Let the equal sides $AB$ and $AC$ of an isosceles triangle be produced to $E$ and $F$ so that $$BE\times CF = AB^2.$$
Show that the line $EF$ will always pass through a fixed point.
Comment: Are you saying that $$BE\times CF=AB^2?$$
Comment: Yes, that's right!
Answer: Since you asked for an approach I'm not giving a full solution.
Let P and Q be the points on AB and AC produced such that AB=BP and AC=CQ. Join EF  and let it intersect PQ at R. Using whatever way you wish, find the ratio PR:RQ.
Spoiler: The ratio will come out a constant.
Comment: It's a pain to type math on phones so if someone wants to (constructively) edit this they're more than welcome.


How to set focus to the datatable filter?

Question: I'm using a Webix datatable with some filters and want to be able to set the focus to some particular filter input, for instance, after initialization. Unfortunately, I can't find a way to do so.
A minimal required configuration is
<code>{
  view:"datatable",
  columns:[
    { id:"id"},
    { id:"value",   header:{content:"textFilter"}, fillspace:true}
  ],
  data:list_data,
  ready:function(){
    alert("datatable loaded")
  }

}
</code>
http://webix.com/snippet/ba52bfc1
But how can I get filter's id or object and set the focus to it?
Answer: <code>ready:function(){
    this.getFilter("value").focus();
}
</code>
Updated snippet : http://webix.com/snippet/b4f50020


Eliminar Linha com e-mail

Question: Existe um formulário em PHP, que as empresas utilizam para postar as vagas.
As vezes elas colocam dentro do textarea algo como:
Enviar vaga para firstname.lastname@example.com
Eu gostaria de VIA PHP, eliminar todas as linhas (apenas a linha, por inteiro) que contive-se um e-mail. Segue o exemplo abaixo:

Vaga para Pedreiro
Salario: XXX
Cidade: XXXX
Enviar e-mail com curriculo para firstname.lastname@example.com
Tarefa: XXXXXXXXXXXXXXXXXX

Deveria ficar:

Vaga para Pedreiro
Salario: XXX
Cidade: XXXX
Tarefa: XXXXXXXXXXXXXXXXXX

Lembrando que nem sempre vai ser Enviar curriculo para firstname.lastname@example.com. As vezes, eles escrevem diferente, como enviar dados para, envie um e-mail com se dados. Em fim.
Comment: Isso não é um placeholder ?
Comment: Eles quem? De onde é esse formulário? Se não é seu, por que vc acha que vai conseguir alterá-lo em PHP (uma vez que o formulário já vai estar no navegador após a consulta)? Vc sabe o nome do objeto com o textarea? Se sim, por que simplesmente não apaga totalmente seu conteúdo? Veja quantas dúvidas. Sinal de que a sua pergunta realmente não está clara. Por favor, edite-a para melhorar a explicação. :)
Answer: Explode a text area em linhas diferentes.
Percorre o array resultante imprimindo apenas as linhas que não têm email
$linhas = explode("\n", $textarea);
foreach ($linhas as $linha) {
    // teste básico para presença de email
    if (!preg_match('/[a-z0-9]+@[-a-z0-0]+\.[a-z]+/', $linha)) {
        echo $linha;
    }
}

Comment: Para http: `preg_match('/https?:\/\//', $linha)`; para telefone (ou melhor, para 9 digitos seguidos): `preg_match('/[0-9]{9}/')`, se quiseres reconhecer números com espaços ou traços vai ser preciso complicar a *regular expression*.
Comment: Obrigada. Como seria a preg_match para http e telefone?
Answer: A pergunta está muito mal formulada, por isso você recebeu tantos negativos, espero que você edite ele para que as pessoas voltem a lhe positivar. Mas pelo que entendi, você quer filtrar o e-mail do campo textarea, para fazer isso, há duas maneiras, você pode bloquear a digitação de email usando javascript:

Html:
<textarea onkeyup="removerEmail(this)" onkeypress="removerEmail(this)">
</textarea>

Veja esse exemplo.
E no PHP usando um filtro para a linha que contiver o e-mail:
function filterEmail($text)
{
   return preg_replace('/(.*)[a-z0-9\.\_\-]+@[a-z0-9\.\_\-]+\.[a-z]+(.*)/i','', $text);
}

Answer: Não sei ao certo onde irá utilizar, mas quando eu preciso inibir o usuário de escrever, postar, enviar ou sei lá o que com o e-mail dele, eu uso um preg_replace com especificações como a baixo. e então o e-mail digitado é substituido por [O E-MAIL NAO PODE SER EXIBIDO]
$text = preg_replace('/([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/','[O E-MAIL NAO PODE SER EXIBIDO]', $text);

Comment: No caso ele não deleta a linha, pois as vezes além de apenas o e-mail, ele pode ter colocado alguma outra informação importante na linha!

Eliminar Linha com e-mail


HTML/CSS - How can I center two divs that are `sticky` and `inline-block`?

Question: I have the following code: JSFiddle. The title is a sticky element and everything works fine. However, I would like to center the title and icon, so I added a wrapper div: JSFiddle. The problem here is that the title is now sticky to the wrapper div instead of the content div. How can I make sure the positioning works while also having the title and icon centered?
Here's the code from the second JSFiddle:
HTML:

Title

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

CSS:
.menu-wrapper {
  display: inline-block;
  border: thin red solid;
  margin-left: 50%;
  transform: translate(-50%, 0);
}

.menu {
  position: sticky;
  display: inline-block;
  width: 150px;
  top: 15px;
  background-color: #000000c7;
  border-radius: 10px;
  padding-top: 14px;
  padding-bottom: 14px;
  padding-left: 25px;
  padding-right: 25px;
  margin-bottom: 10px;
}

.menu-title {
  color: white;
  font-family: "Roboto";
  font-size: 18px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  margin: 0px;
  margin-left: 15px;
}

.icon {
  display: inline-block;
  width: 50px;
  height: auto;
  margin-left: 50px;
}

Edit: I only want the title to be sticky, not the icon
Comment: You are required to post a [mcve] here, **within your question**, and [not a link](https://meta.stackoverflow.com/questions/254428/something-in-my-web-site-or-project-doesnt-work-can-i-just-paste-a-link-to-it) to any third party site.
Comment: @Rob Just added the code from the second JSFiddle
Comment: Note: the `` tag does not use and does not need a closing slash and never has in HTML.
Comment: @Rob Oh my bad, it works in React and I just moved my code over and changed things like `className` to `class`
Answer: You can just use regular text alignment to get your centering. Like this:

.content {
  text-align:center;
}
.content > * {
  text-align:left;
}

.menu {
  position: sticky;
  display: inline-block;
  width: 150px;
  top: 15px;
  background-color: #000000c7;
  border-radius: 10px;
  padding-top: 14px;
  padding-bottom: 14px;
  padding-left: 25px;
  padding-right: 25px;
  margin-bottom: 10px;
}

.menu-title {
  color: white;
  font-family: "Roboto";
  font-size: 18px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  margin: 0px;
  margin-left: 15px;
}

.icon {
  display: inline-block;
  width: 50px;
  height: auto;
  margin-left: 50px;
}

Title

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Filler text

Answer: Make the wrapper sticky, instead of the title.
.menu-wrapper {
  display: inline-block;
  border: thin red solid;
  margin-left: 50%;
  transform: translate(-50%, 0);
  position: sticky;
  top: 15px;
}

https://jsfiddle.net/m0khwxan/
Comment: Oh I should've mentioned that the icon shouldn't be sticky. Just edited my post


Show it is a field

Question: Suppose that $\Omega \in \mathcal{F}$ and that $A,B \in \mathcal{F}$ implies $A-B = A\cap B^c \in \mathcal{F}$ .
Show that $\mathcal{F}$ is field
My solution:
i)  $\Omega \in \mathcal{F}$
ii) $B \in  \mathcal{F}$   ,  $A \cap B^c \in \mathcal{F}$ , because {$A \cap B^c  \subset  B^c  $ } Thus  $B^c \in \mathcal{F}$
iii) IF $A,B  \in \mathcal{F} $, from assumption, implies  $A \cap B^c \in \mathcal{F}$  , I am not sure how to show $A  U B \in \mathcal{F}$
I also think I have done an error in ii)
Answer: Yes, your explanation for part $2$ is unclear. But it is easy, just note that $B^c=\Omega\cap B^c$.
As for part $3$, let $A,B\in\mathcal{F}$. By part $2$ we know that $A^c,B^c\in\mathcal{F}$ as well. Then $A^c\cap B^c\in\mathcal{F}$ (because $A^c,B\in\mathcal{F}$), and again by part $2$ $A\cup B=(A^c\cap B^c)^c\in\mathcal{F}$.
Comment: @GAGA No, I mean exactly $A^c,B\in\mathcal{F}$. Then by what is given we conclude that $A^c\setminus B=A^c\cap B^c\in\mathcal{F}$ as well.
Answer: For ii) just write $B^{c}$ as $\Omega \setminus B$.  So $B^{c} \in \mathcal A$ for all $B \in \mathcal A$
For iii) note that $A\cap B =A\setminus B^{c} \in \mathcal A$ (where we have used ii). Now $(A\cup B)^{c}=(A^{c}\cap B^{c}) \in \mathcal A$ so $ A\cup B \in \mathcal A$.

Show it is a field


Union of infinite closed intervals contained in an open one

Question: I'm studying sets of convergence for series of functions in $\mathbb{R}$.
Now I've noted that, let's say we have an open set $(-R,R)$ with $R > 0$:
Saying that we have uniform convergence in $(-R,R)$ is not equal to say we have uniform convergence in any closet subset $[a,b] \subset (-R,R)$.
Now, my question is, what is right and what is wrong, and why, in saying:

"This property is true for any closet subset $[a,b] \subset (-R,R)$ and so it's true for $\cup^{\infty} [a,b] \subset (-R,R)$, but
  $\cup^{\infty} [a,b] \subset (-R,R) =   (-R,R)$ so this property is true also on $(-R,R)$"

Thank you so much, I'm sorry if I haven't made myself clear.
Comment: But what is the property the quotation is about?
Comment: @Adayah In this case is about uniform convergence but if it's possibile I would like a more general answer
Answer: I'm not exactly sure what you mean, but lets see:
When you say that a sequence of functions $\{f_n\}$ is convergent on a set $E$, this means that for every $\varepsilon>0$ you have an $N\in\mathbb{N}$  such that etc. If you consider uniform convergence on another set $F$, then you'll have another $N$, so we can think of this $N$ as depending on the set in question, and note it $N(F)$ (or $N(E)$ in the case of $E$). If you know that $\{f_n\}$ converges uniformly on $E$ and on $F$, given $\varepsilon>0$ you can take the maximum of $N(E)$ and $N(F)$, and the definition of uniform convergence on $E\cup F$ will be verified. This goes through for any finite collection of sets $E_1,\dots,E_n$, just take the maximum of $N(E_1),\dots,N(E_n)$. However, this breaks down for infinite collections of sets, since an infinite set of natural numbers need not have a maximum. Intuitively, the $N(E_k)$ could become bigger and bigger, and so there is no $N^*$ which lies above all of them.
Comment: That's exactly what I wanted! And It's correct that the union of all possible closed subset in (-R,R) is equal to (-R,R)?
Answer: Let $(f_{n})_{n}$ be a sequence of real-valued functions on $(-R,R)$.
Suppose that $(f_{n})_{n}$ converges uniformly to some function $f$ (defined on $(-R,R)$). Then, it is trivial that for each closed subset $[a,b]$ of $(-R,R)$, $(f_{n}|_{[a,b]})_{n}$ converges uniformly to $f|_{[a,b]}$.
Conversely, suppose that for each closed subset $[a,b]$ of $(-R,R)$, $(f_{n}|_{[a,b]})_{n}$ converges uniformly to some function (defined on $[a,b]$). Now, let $x\in(-R,R)$ be arbitrary. Let $m$ be the smallest positive integer such that $x\in X_{m}=[-R+\frac{1}{m},R-\frac{1}{m}]$. Define $f(x)$ to be the limit of $(f_{n}|_{X_{m}}(x))_{n}$. This uniquely defines a function $f$ on $(-R,R)$. Moreover, the sequence $(f_{n})_{n}$ converges pointwise to $f$. However, we cannot say anything about uniform convergence here!
Comment: So the fact is: pointwise covergence is a property of points, while uniform convergence is a property of sets. The fact that after we have chosen a point we can find convergence cannot say anything about uniform convergence in the set where the point lives, right?


Can a NBA team buy a draft pick?

Question: Can a NBA team buy a draft pick for cash from another nba team?
Answer: It is legal in the NBA CBA to trade a player for cash (see pages 169-173). Larry Coon's excellent site covers this in detail.  There is a limit for the total amount of cash that can change hands during the salary cap year per team; it changes each year but is between $3MM and $4MM total.  As such it's not a whole lot of money compared to the total value of a team, so it's not exactly a lucrative way to make money.
Draft picks aren't explicitly mentioned as being able to be traded for cash or not being able to be traded for cash, so I believe they are able to be traded (as they're not particularly different from players), subject to the Ted Stepien Rule. They count as $0 towards the salary cap, though, until drafted.  Given the fact that draft picks tend to be how you build a lower-salary team [as drafted players tend to overperform their salary due to rookie scale contracts], it wouldn't make a lot of sense to 'sell' a draft pick for cash directly.  More effective would simply be trading down - say, a 1st rounder for 2 second rounders.  Occasionally a team won't have room for a draft pick (particularly teams with a lot of picks, see the 76ers lately), and they'll trade it for cash in that situation (or a next-year pick) to a team who wants to take a flyer on a guy.
What you do find fairly commonly is the concept of trading for a player with an expiring contract; that's quite easy to do and benefits the team losing the pick immensely, as they are then able to clear salary cap space more easily.  They also might be more able to trade for another player, as you need to match salaries to make it work.
You also see teams trade players after they've been drafted; this is better than trading before they're drafted, as the salary now counts - so they get a trade exception for that amount which they can then use later.  For example, the 2015 draft saw the Pelicans trade their 2nd rounder to the Clippers for cash after he'd been selected (though they may well have had an agreement to select that player beforehand).

Can a NBA team buy a draft pick?


How to merge two rows in SSIS Excel SQL Command

Question: I have a table in the middle of an excel sheet. The table is given below, here the header is defined in two rows so I need to capture both of them together.
For an example the header for the second column has to be Management JG8

For this purpose I'm using the SQL command option in SSIS and I executed the following query and the output is shown below.
<code>SELECT * FROM [Monthly SSC Report$W7:AJ31]
</code>
The headers are not what I'm expecting, I require assistance in modifying the sql query to get the header by merging those two rows.
Answer:
Connect your Excel file normally to the Source Data Flow
Your Source data should look like this:

In the Excel Source Editor, Rename the required columns. For Example:

To ignore the first row., add a conditional split that filters rows with Grand Total = NULL.
Comment: This approach seems better, but if I hard code like this I must ask the client to stick to the same column order.


How to disable resizing and reordering of columns in NSTableView

Question: I am using NSTableView in an OS X app, using Swift 3. I am not able to figure out how to disable reizing of columns and also reordering of columns
Comment: You can literally google the title of this question, and the third hit is an Apple developer page which has the answer.
Comment: I don't understand why I am getting downvoted :| Any reasons? I did search and I couldn't find anything useful.
Comment: most likely why is because you are not giving enough information in your question. Take a look at this article here to help you get an idea of how to structure your answer - https://stackoverflow.com/help/how-to-ask
Comment: You don't provide sufficient information.  We don't know whether you are trying to do it programmatically or through the interface builder.
Comment: @Ssswift I can't see here :| I did literally google the title - http://i.imgur.com/9WTHRZ4.png I would appreciate if you can give me the link
Comment: Did you check the properties of the table view and columns in IB (Xcode) and in the documentation?
Comment: @Willeke figured out how. Earlier I was checking in XCode's documentation and I didn't know why it was not showing. But I found it on web version - https://developer.apple.com/documentation/appkit/nstableview Thank you!
Answer: Found the answer on official docs :
<code>tableView.allowsColumnResizing = false
tableView.allowsColumnReordering = false
</code>


Get sum of the values in multiply lists generated by comprehension list in the loop

Question: I have a comprehension list inside a loop that will result in multiply lists, like below:
[1,3,5,7,9,12]
[7,9,0,4,12,3]
[9,4,8,3,1,6]
[21,11,12,32,2,12]
I don't need this lists themselves, but only the sum of same index values in this lists, like this:
[38,27,25,54,33]
(where, for example, 38 is first values in every list 1+7+9+21)
I have tried to do it with combination of list/map/sum/zip:
list(map(sum,zip([func(data,x) for x in list(range(num)])))

where "list(range(num)" is number of lists that need to be summed,
and "func(data,x)" is function that generates the lists itself
but its not workings, as zip(), only takes data like zip(a,b,c)
It looks simple, but i already spent two days trying to understand how to solve this case.
is there is any way i can get the sum of these lists?
Comment: is the `[46,27,26,54,33]` just a random example? that does not correspond with your list examples, `sum` of `[1,3,5,7,9,12]` is not 46
Comment: You want the sum of elements inside every list or the sum of l[0] for every list, then the sum of l[1] of every list etc?
Comment: Sorry for misleading description. I need a list with sum of the same index values from lists that was generated in loop (you can check my update in the question)
Answer: Once you have your results list, and all sublists in said list are of the same length - put them all in a list together and simply-
[sum(item[i] for item in results) for i in range(len(results[0]))]

Where results is your list of results.
Not entirely sure how you're generating these results but I'm assuming this is how you get said list of results-
[func(data,x) for x in range(num)]

(please do not list(range(num)), range returns a generator that is efficient for list comprehension)
You simply have to do
results = [func(data,x) for x in range(num)]
print([sum(item[i] for item in results) for i in range(len(results[0]))])

again, this is assuming func(data, x) returns a list (of constant length across this process)
Input
# assume results = [[1,3,5,7,9,12],[7,9,0,4,12,3],[9,4,8,3,1,6],[21,11,12,32,2,12]]
print([sum(item[i] for item in results) for i in range(len(results[0]))])

Output
[38, 27, 25, 46, 24, 33]

Answer: Let me make a simple conceptual program. See if it helps:
# Inputs
l1 = [3,4,5]
l2 = [6,7,8]

input_lists = []
input_lists.append(l1)
input_lists.append(l2)
print(input_lists)
# prints [[3,4,5], [6,7,8]]

#Output
print([sum(i) for i in input_lists])


Let $E \subset \mathbb{Z}$ be non-empty, bounded below. Prove that $\inf{E} \in E$

Question: I know that since $E$ is non-empty and bounded below that $\inf{E}$ exists, but I'm not sure how to show that it is in $E$.
Answer: Since $E$ is bounded below, we know that $\inf E > -\infty$.
Now assume for contradiction that $\inf E$ is not in $E$.
If $\inf E$ is integral then $\inf E +1$ is a greater lower bound than $\inf E$, contradicting the definition of infimum.
If $\inf E$ is not an integer then $\inf E = k - f$, for some integer $k$ and $f \in (0,1)$. By definition, $\inf E$ is the greatest lower bound of $E$. Note that since $E \subset \mathbb{Z}$, $k$ is a lower bound of $E$ that is greater than $k-f$. This is contradictions the definition of infimum, so that $\inf E$ must be in $E$.
Alternatively, this follows from the Well Ordering Principle
http://en.wikipedia.org/wiki/Well-ordering_principle
by adding a constant integer $x$ so that $E+x \subseteq \mathbb{N}$ and showing that $\inf \{ E+x \} = \inf \{ E \} +x$.
Answer: Since $E$ is bounded below, $p\equiv\inf E$ is finite. Then $q\equiv \lfloor p\rfloor \in \mathbb Z$ has the property that $p\in[q,q+1)$. If it were the case that $p\in(q,q+1)$, the there would exist an element of $\mathbb Z$ in $[p,q+1)\subset (q,q+1)$, which is false. Thus $p\in[q,q+1)\setminus(q,q+1)=\{q\}\subset \mathbb Z$.
Answer: You can get close to the infimum of a set with a convergent succession $x_n$, this succession has values in $\mathbb Z$ so it must be constant after some $n$
Answer: There exists a non-increasing sequence $e_n \in E$ such that $\lim_n e_n = \inf E$. We have $e_n \ge \inf E$ for all $n$, and since $e_n \in \mathbb{Z}$, we have $e_n \ge \lceil \inf E \rceil \ge \inf E$ for all $n$. Hence $\lceil \inf E \rceil$ is a lower bound, and hence $\inf E = \lceil \inf E \rceil$.
Since $e_n \to \lceil \inf E \rceil$, we have some $N$ such that $e_n = \lceil \inf E \rceil$ for all $n \ge N$. In particular, $\inf E = \lceil \inf E \rceil = e_N \in E$.


How to interpret notes outside of the key signature?

Question: Lets make this question a bit clear.
If you're playing Bach's music, it shows you that its' key is E minor, or A major or anything. But, when you play something like:

He add sharp in his notes. First it's G major, and then down to E minor, and then straight to B major(?) then back to A minor and to G major again.
How can he composed that, I mean, is there any technique or it's the style of Baroque music?
Answer: "First it's G major, and then down to E minor, and then straight to B major(?) then back to A minor and to G major again."
No.
As Tim pointed out, this piece is firmly in E minor. The key signature is the first hint - one sharp indicates either G major or E minor. The fact that the piece starts with an Eminor chord is the second clue. (The upbeat starts with 1st inversion E minor, and then on the weak beat we pass through to start firmly on a root position E minor. In both cases the fifth is omitted from the chord, but esp. in 2 voice counterpoint this makes sense, as it is the weakest chord tone, and has the least impact on the identity of the chord.)
Now that we know it is in E minor, we should not be surprised to see a raised 6th and 7th degrees, esp. in ascending melodic lines. These altered degrees are very conventional in diatonic minor mode, this is known as "melodic minor scale".
In m2 (3 if you count the upbeat) we also see that the raised degrees are back to natural in a descending line. This too is part of the entire convention surrounding melodic minor mode. Also the raised 7th degree in measure 5 is completely expected - the raised 7th degree is approached in a descending line from the tonic e, but immediately returns back to the tonic again. This is also expected - a raised seventh like this has the effect of making it a "leading tone", which "wants" to go back to the tonic, thus again reinforcing e as the tonic. The first chord in m6 is again E minor - exactly as expected.
The only place where the center of tonality briefly changes is in measure 8 where we briefly feel a tonality of G major (the relative major of Eminor) This is achieved by the chords of m7. First beat of m7 is G, 2nd beat is C, and least 2 beats are D - so in retrospect this sounds as a I-IV-V progression in the key of G major, which then cadences into G in m8.
It is only a brief escape: since G is only the relative major of E minor, and since the harmony moves real quick, and doesn't overly stress the D chord it is easy to immediately roll back to Eminor (by easy I mean it doesn't offend the ear to continue in Eminor as if this entire cadence didn't happen). If you know this entire piece you'll note that it does - at least, the 1st time around, the 2nd time around the piece moves on in G major for at least a while.
There is no particular Baroqueness with regard to the treatment of the tonality - this kind of harmony was also common in Renaissance, and also in the classical period. What is rather Baroque, or at least, typical for Bach is the lively counterpoint, and systematic persistence of the motive (the duh-duh DUH motive that is characteristic for the Bourree).
Other popular changes in the center of tonality can be to the dominant or subdominant - keys that have all but one tone in common with the key of departure. Whether such a change in tonality persists and can be called a modulation depends on how strong the confirmation of the key is (a strong I IV V7 cadence is a strong confirmation and more likely to establish a new key), and also depends on how long the piece continues in the new key.
Note that a (temporary) change in tonality may or may not be denoted explicitly using a new key signature. In practice you'll find that in Baroque music, the tendency is not to denote those changes explicitly, esp. not within one movement.
Answer: When the key sig. is one sharp, the key will be Gmaj., or its relative minor Em.Here, he's using mainly Emin. with the melodic preferred, as in notes 6 and 7 raised for an upward direction of tune, and left natural when the tune descends. It was the usual way in the Baroque period.
If one is in G/Em, then one will use D, C, Am and B (or Bm) for the harmony. It's not that the piece modulates to each of these keys. It could stay in Emin., or move freely to Gmaj. as here, using the D as dominant to get to the Gmaj.


Hopf invariant and the linking number

Question: The Hopf invariant of a map $f:S^{2n-1}\to S^n$ can be defined in various ways,
in particular:
(1) as the linking number of the preimages of two points and
(2) using the cohomology ring of the space $S^n\cup_f D^{2n}$.
Where can I find a proof of equivalence of these two definitions?
Answer: Historical reference is

Steenrod N. E. Cohomology invariants of mappings // Ann. Math. 1949.
  V. 50. P. 954—988.
Comment: Thank you! Apparently, this is where the definition (2) first appeared.

Hopf invariant and the linking number


Get segno to appear above chord-names in LilyPond

Question: Problem:  The segno appears between the staff and the chord-names, pushing the chord names up, which makes them hard to read:

I'd like to have the segno appear above the chord names (so that the chord names remain close to the staff). Putting the \segno into the ChordNames context doesn't produce any mark.  ChordNames contexts also don't seem to like \markup either (so I can't try the recipes from the documentation).
Code for attached image:

\score{
  <<
  \new ChordNames \chordmode{
    f4. ~ f4 bes8 f2.
  }
  \new Staff {
    \clef "bass"
    \key f \major
    \time 12/8
    f2.\segno f4. f8 c a
  }
  >>
}
Answer: Replacing
\time 12/8
f2.\segno f4. ...

with
\time 12/8
s1*0 \mark \markup{   \musicglyph #"scripts.segno" }
f2.\segno f4. ...

works.  Somehow making the symbol a markup attached to a zero-duration note allows the renderer to push it to the side.   However, some think that the s1*0 construct is bad form.
Answer: Since LilyPond version 2.23, there's been a repeat structure specifically for da capo, dal segno, alla coda, al fine, etc.: \repeat segno N {…}.
It works somewhat like the \repeat volta N {…} structure, and prints the various repeat symbols automatically.  The segno symbol is placed above the chord names by default.
Details can be found on this page of the documentation: https://lilypond.org/doc/v2.24/Documentation/notation/long-repeats#segno-repeat-structure
Code
\version "2.24.1"

\score {
    <<
        \new ChordNames {
            \chordmode {
                R1. |
                \repeat segno 2 {
                    f4. ~ f4 bes8 f2. |
                }
            }
        }
        \new Staff {
            \clef "bass"
            \key f \major
            \time 12/8
                R1. |
                \repeat segno 2 {
                    f2. f4. f8 c a |
                }
        }
    >>
}

NB: I've put in a rest for the first measure so that it produces a dal segno, rather than a da capo repeat.
Image


How to pass variable of paragraphs type to another preprocess function

Question: I want to override the fontawesomeicons.html.twig (Fontawesome Module). But I only want to do this for "my-very-special-paragraphs-type" and not in general. I think it is a good idea to declare a variable of "my-very-special-paragraphs-type" in a preprocess function and use the variable in the twig-file.
function mytheme_preprocess() {
  $var = my-very-special-paragraphs-type
}

the fontawesomeicons.html.twig:
{% if var == 'my-very-special-paragraphs-type' %}

    {{ icons }}

{% else %}

   {% if layers == '1' %}
      {{ icons }}
   {% else %}
      {{ icons }}
   {% endif %}

{% endif %}

But I do not know how to do this. Can anybody help?
This is the hook of fontawesome module:
Answer: This was quite a ride.
First of all: I didn't got this running in the theme. I needed to create a custom module AND move its implementation of the fontawesomeicons hook last.
Next thing was: hook_preprocess_fontawesomeicons doesn't contain a hint of the parent entity the icons are used in. So I used hook_preprocess_field first to pass the paragraph type over to drupal_static() and retrieved it back then in hook_preprocess_fontawesomeicons.
/**
 * Implements hook_module_implements_alter().
 */
function MYMODULE_module_implements_alter(&$implementations, $hook) {

  if ($hook == 'fontawesomeicons') {

    // Run MYMODULE_preprocess_fontawesomeicons() last.
    $group = $implementations['MYMODULE'];
    unset($implementations['MYMODULE']);
    $implementations['MYMODULE'] = $group;
  }
}

/**
 * Implements hook_preprocess_field__FIELD_TYPE().
 */
function MYMODULE_preprocess_field__fontawesome_icon(&$variables) {

  if ($variables['element']['#entity_type'] == 'paragraph') {

    $paragraph = $variables['element']['#object'];

    $ptype = &drupal_static('paragraph_type', TRUE);
    $ptype = $paragraph->getType();
  }
}

/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_fontawesomeicons(&$variables) {

  $ptype = &drupal_static('paragraph_type', FALSE);

  if ($ptype) {
    $variables['paragraph_type'] = $ptype;
  }
}

Inside any variation of fontawesomeicons.html.twig you now can:
{% if paragraph_type == 'my-very-special-paragraphs-type' %}
  {# do your magic here #}
{% endif %}

I never heard of drupal_static() until today. Read more:

How do I pass data between hooks that don't interact?
Share a value between two different hooks
Comment: @lesleyn. – I got it working that way. Would you upload your resulting module maybe on GitHub and ping me the link here, so I can review?
Comment: I can not make it run. I install the module but it is not working. Not with or without s. I use it in a nested paragraph and webfont with CSS. I have cleared allways the cache and tried both paragraph types.


cannot uninstall SharePoint Server 2007

Question: I have installed SharePoint Server 2007 Entrprise. And I want to uninstall it. But each time I select to uninstall it, and at the beginning of the uninstall process (i.e. of the progress bar of uninstall process), the uninstall dialog will suddenly be terminated/disappeared (without any error message). From control panel, I can see the "Size" of installed SharePoint Server 2007 Entrprise is not available (seems very weird). I can also execute the SharePoint Central Administration from start menu -- so seems some SharePoint function still there in my machine?
Any ideas what is wrong and any solutions? Here is a screen snapshot of installed programs (with detailed information) of my control panel.

I am using Server 2008 x64 with SharePoint Server 2007 x64. The SharePoint Server 2007 Server x64 is trial edition (trial period expired) and it is why I want to uninstall it.
Answer: You have to do a few things before you can run the uninstall. Here is the list:
http://www.keirgordon.com/post/Uninstall-MOSS-2007.aspx
Comment: I am confused. If I have any existing web applications/sites running on SharePoint 2007 Server, I have to delete them manually before uninstall SharePoint Server 2007? If yes, do you have any official documents to prove it?
Comment: Thanks Shiraz! I have a related question here, appreciate if you could take a look.

http://serverfault.com/questions/80286/error-editing-sharepoint-page

cannot uninstall SharePoint Server 2007


IBM Cloud DevOps continuous delivery pipeline Node version too low

Question: We need to build an Angular 6 front end project on IBM Cloud using the DevOps pipeline, but the project requires at least Node v8, while IBM Cloud DevOps pipeline only support v6.7. How can we build our project? Is it possible to upgrade or customize a Node version in DevOps pipeline environment?
Answer: It is true that IBM's DevOps Toolchains currently export up to node 6.7.0 as detailed here https://console.bluemix.net/docs/services/ContinuousDelivery/pipeline_deploy_var.html#deliverypipeline_environment.
But you are free to install any version of node. To do so, add the following to your build job and remove any existing export to node supplied by the pipeline.
<code>#!/bin/bash

npm config delete prefix
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.31.2/install.sh | bash
. ~/.nvm/nvm.sh
nvm install 8.9.0

node --version

# build instructions follow
</code>
This approach uses Node Version Manager.
Comment: Also check https://stackoverflow.com/questions/42269590/bluemix-build-pipeline-set-node-and-npm-version?rq=1
Answer: Another different solutions is using a custom Docker image with the Node version required by your service.
So, to configure your Pipeline Step, you need to select as Compilator Type a "Custom Docker image" and then, in the input field for the container name, select one for your Node version, for example "node:10.15.2"


How does SVM classify when test data point lies between the 2 margins

Question: I have understood that SVM classifies points using a hyperplane and a margin. A point is classified +ve when w.x + b >= 1 (margin 1) and -ve when w.x + b <= -1 (margin 2) and the decision boundary has equation as w.x + b = 0. I still don't understand, how would SVM classify a point coming from test data which lies in between the margin?
Comment: it always uses $wx + b = 0$ to do classification (i.e., if $wx + b > 0$ then class A, else class B). The soft margin concept just applies for training, i.e., the algorithm tolerates some missclassification during the training stage.
Comment: @Zhanxiong I think you can convert your comment to an answer
Comment: @Zhanxiong So you mean to say that $wx+b>=1$ and $wx+b<=1$ is only used while training the model and classification on test data is done using $wx+b>=0$ or $wx+b<0$ conditions. Right?
Comment: That's right. Also, if you review the math details in SVM training, I don't think it's necessary to introduce the plane $wx + b = \pm 1$ explicitly. It is the *slack variable* $\xi_n = |t_n - (wx_n + b)| \geq 0$ that enters the optimization formulation. Of course, on the decision plane, $\xi_n = 1$.
Comment: @gunes I am happy to do that when I get time.
Answer: Adding Zhanxiong's comment as an answer.
THE SVM always uses wx+b=0 to do classification (i.e., if wx+b>0 then class A, else class B). The soft margin concept just applies for training, i.e., the algorithm tolerates some misclassification during the training stage.
This means that wx+b>=1 and wx+b<=1 is only used while training the model and classification on test data is done using wx+b>=0 or wx+b<0 conditions.


Prove that ∀Z · ∃Q · (p(Q) → p(Z)) ⊨ ∀Z · (∃Q · p(Q)) → p(Z) does not hold by giving a suitable structure

Question: Prove that ∀Z · ∃Q · (p(Q) → p(Z))   ⊨ ∀Z · (∃Q · p(Q)) →  p(Z) does not hold by giving a suitable structure
I am working on this problem but am frankly stumped.
I read this as "for All Z such that there exists a Q such that if p(Q) then p(Z) has equivalence to all Z such that there exists a Q if p(Z)
Is this reading of the question correct?
What would a "suitable structure" be and how would you find it?
If anyone can help it would be greatly appreciated.
Thank you.
Answer: The right reading would be:
The statement "For all $Z$ there exists a $Q$ such that $p(Q)$ implies $p(Z)$" semantically entails "For all $Z$, if there exists $Q$ with $p(Q)$, then $p(Z)$".
Note that there is no equivalence mentioneed and semantic entailment (or consequence) means that all models with the first property also have the second property. The task is to come up with a model / structure where the first is rue and the second is not.
Assume there are two obejcts $A$, $B$ with $p(A)$ and $\neg p(B)$. Then fir any given $Z\in\{A,B\}$ you can always pick $Q=B$ and from this see that the first statement is true. But for $Z=B$ we can pick $Q=A$ and see that the second statement is not true in this structure.
Comment: I am trying to understand this.  If we take:

∀Z = "all people″

and we look at the three cases:

p(A) = A is a human
p(A) = A is a cat
p(A) = A is a female

the first one will always be true, the second will always be false, and the third will sometimes be true and sometimes be false.

Then the left hand side can read: For all people there exists a Q such that if Q is a female this implies all people are female.

The right hand side is for all people there exists Q with Q being female, then all people are female.

Is this a correct interpretation?
Comment: The left hand side you gave the interpretation to $(\forall Z (\exists Q P(Q))) \rightarrow (\forall P(Z))$, which is obviously not what you meant to say.  I suggest: "for every person Z, there exists a person Q such that if Q is female then Z is female."
Comment: Similar issue with the right hand side.  I suggest "for every person Z, if there is any female then Z is a female".
Answer: It's easier if you consider the three cases:

P is always true
P is always false
P is sometimes true and sometimes false

The left hand side is true in all cases.
The right hand side is true in the first two cases.  In the third case, consider Z for which $P(Z)$ is false.  There still exists a $Q$ for which $P(Q)$ holds, but $P(Z)$ is false, so you get $\text{true} \rightarrow \text{false}$.  So any structure under which $P$ is sometimes true and sometimes false over your universal domain works as a counter example, such as $P(x) = 0$ for a domain of more than 1 element.
Comment: Thanks I have combined a further question in the comments above.


How do I calculate the adjusted percentage of dice out comes.

Question: What I'm attempting to do is construct a spreadsheet to calculate the number of wounds and kills for a tabletop board game I play. To give everyone an idea of the situation. You have figure A shoots at figure B. In this situation you have the "percentage for figure A to Hit figure B" the percentage for figure A to Wound figure B " the "percentage for figure B to Fail an Armor Save ". This is all bases on a D6 die and sometimes multiple D6 rolls.
I have in my spreadsheet already been able to calculate the percentage of "The Percentage to HIT", "Percentage To wound" and the "Percentage to Fail an Armor Save".
Now my issue is where (in the game) the weapon used to wound on a roll of 6 on a six sided roll there is no save possible.
Example: Figure A shoots at figure B and "The Percentage to HIT" is 89%. The Percentage of figure A to wound figure B is 33%. The percentage of Figure B to "fail the Armor Save" is 17%. Now add in the case were on a roll of a 6 on six sided die there is no save possible.
In the end I'm attempting to figure how many wounds Figure B is going to suffer.
A couple of questions

Do I calculate the 1/6 chance off the percentage of figure A to wound figure B? So off the 33%.
So in this example the "To wound percentage" is figured as 5+ so a 2/6 thus .3333 = 33%. In that case is it 1/2 = .5000 thus 50%.
Once I calculate the percentage of the 1/6, where in my calculations should I add that. =SUM(To_hit_% x To_Wound_% x Fail_save_%)

Do I add it to the Fail_save_percentage or the To_wound_percentage.
As you can see it is a bit of a complex question. But at the root it seems pretty simple.
Comment: Do you want the possibility to roll a 1 or 6 on a 6 sided die?
Comment: Well the concept is for a game. I need to calculate the percentage to fail the a saving throw. Which is on a 2+ the character saves and is not hurt. So the percentage to Fail save is 1 in 6 on a six sided die. so 1/6 or .1667 or 17%.
Comment: Well the concept is for a game. I need to calculate the percentage to fail the a saving throw. Which is on a 2+ the character saves and is not hurt. So the percentage to Fail save is 1 in 6 on a six sided die. so 1/6 or .1667 or 17%.
The weapon being used to hurt the character has a ability to not allow a saving throw on a roll of 6 on a six sided die. Which is a 1/6 or .1667 or 17%.
So I assume that in 1/6 time the weapon will not allow the saving throw needs to be appended to the 1/6 chance the character has to Fail the saving throw.
I'm just not sure how to do that.
Comment: This is a rather easy question to answer if you know which game you're speaking about (I think it's Warhammer, though). Most probably you'd get a better answer in BoardGames.SE
Comment: It is 40k that I am speaking of.
Answer: Rending?
You would add it to the failed save, since the save does (auto-)fail, so the probability of a failed save per wound dice roll is 1/6 (.16) + (% to wound * % chance to fail save).
For the total wounds applied it's going to be (%chance_to_hit * (1/6+(%chance to wound * % chance to fail save)) * # of dice.


Lightweight HTML/JavaScript framework for business forms

Question: I need to build multiple business forms with basic validations.
Example field types:

required field
date (datepicker)
time (timepicker)
email
money
integer number (+ optional min/max value)
decimal number (specify precision)
phone number
social security number
zip code
credit card number
masked text (+ optional regex validation)
field with server side validation
etc.

Is there a lightweight library or framework that provides some or most of those field types out of the box as well as the ability to create custom fields with validations?
Comment: Not a framework, but have you ever used HTML's native [pattern matching](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) on inputs? It has [>90% support](https://caniuse.com/#feat=input-pattern) in vendors. It allows for matching a regex client-side. Of course, as with any solution, server-side is necessary as well.
Answer: You can these. I would think that a server-side validation is good too in addition to front-end validation

Use HTML5 (frontend) native validation
https://github.com/Zhouzi/GentleForm
PHP some people have created their own class they shared Easiest Form validation library for PHP?
JQuery validation https://jqueryvalidation.org/
Answer: I recommand you to use vuito, since it's template-based and isomorphic you can share your validations between front and back-end super easily. The package weight less than 1.3kB.


How to run revisions with alembic?

Question: I noticed that one of my columns had the wrong name so I changed it. Then I ran alembic upgrade head in the terminal in PyCharm and that didn't work so I dropped that table and another table that I had to drop so I could drop the table I made changes in. I dropped the tables in a sql query. I then tried alembic upgrade head again and that didn't create the tables I had dropped. How do I create the dropped tables?
Answer: Alembic keeps the latest applied revision in alembic_version table and checks it before upgrading. You need to do a downgrade firstly and then upgrade.
How to do downgrade is described in this answer.
Comment: How do I go about downgrading?
Comment: See this excellent answer https://stackoverflow.com/a/48242325/13782669

How to run revisions with alembic?


imadjust turns all pixels to white

Question: I am using imadjust to enhance image contrast or to stretch, for example:
image = imread(path)
result = imadjust(image, [0.01 0.6], []);

but it turns all image pixels to white. How do I fix it?
Comment: i tried the same code just now with cameraman.tif. It does NOT make all pixels white!
Comment: How do you know that you get white pixels? What are the values of `result`? Can you post a link to an image that you're using?
Comment: Till now i'm using default image in matlab cameraman.tif
Comment: Did you normalize the values in the input image to be between 0 and 1?
Comment: I already convert the image to binary
Comment: If the image is binary, it has only 0s and 1s, hence doesn't contain any values in the range `[0.01, 0.06]`. Therefore, `imadjust` yields a constant image, which I assume that it appears as all-white. I'm not near MATLAB at the moment, but this is my suspicion.
Comment: Ok thank you for help I will try to test it in other images, and if find other thing will help please do
Comment: Try plotting a histogram of the values in your image, using `hist(image(:))` - this will show you what the distribution of values is. Then you can see whether the range you chose makes sense. For example, you could first scale image with `image = (image - min(image(:))) / (max(image(:)) - min(image(:)));` .
Answer: I faced the same problem but when I used imagesc matlab function it works, for example:
subplot(2,1,1);
imagesc(result)
colormap(gray);
axis off
title('Result')

for gray scale image.
I hope this help

imadjust turns all pixels to white


How to check if a JSON output returns 1 or more rows so that either a string or arraylist can be used and mapped accordingly to an object in C#

Question: How can I check if a JSON output returned just 1 row of an element or multiple rows.
For example, I have the below JSON output.
{
    "orders": {
        "order": [
            {
                "id": 100,
                "type": "market",
                "symbol": "AAPL",
                "side": "buy"
            }]
    }
}

I have the below code for deserializing the JSON output:
 dynamic dynObj = JsonConvert.DeserializeObject(response);

 Console.WriteLine("ID: {0}\n Type: {1}\n Symbol: {2}\n Side: {3}\n", dynObj.orders.order.id, dynObj.orders.order.type,dynObj.orders.order.symbol,dynObj.orders.order.side;

But, most of the times I get the output as an array of order object as below
 {
        "orders": {
            "order": [
                {
                    "id": 101,
                    "type": "market",
                    "symbol": "AAPL",
                    "side": "buy"
                },
                {
                    "id": 102,
                    "type": "market",
                    "symbol": "MSFT",
                    "side": "buy"
                },
                {
                    "id": 103,
                    "type": "limit",
                    "symbol": "AMZN",
                    "side": "buy"
                }
            ]
        }
    }

So I deserialize the above Json output as shown:
dynamic dynObj = JsonConvert.DeserializeObject(response);

                    foreach (var c in dynObj.orders.order)
                    {
                        Console.WriteLine("Id : {0}\n", c.id);
                        Console.WriteLine("Type : {0}\n", c.type);
                        Console.WriteLine("Symbol : {0}\n", c.symbol);
                        Console.WriteLine("Side : {0}\n", c.side);
                    }

I have two important questions:

How can I know whether the JSON returned is only 1 row of Order
object or a collection so that I can use the relevant way to loop.
If it is an array, do I need to deserialize as below and if so, how
do I add them to Order Class/Object?
RootObject ord = JsonConvert.DeserializeObject(response);

Any help is greatly appreciated.
Answer: I would highly recommend you stop using dynamic because I think this is an abuse of the type. Instead I would define types to deserialize into. By doing so you give yourself type safety and working with the data becomes trivial. Below are class definitions an example using the generic deserialize method (Deserialize<T>(string input)).
 public class order
 {
      public int id { get; set; }
      public string type { get; set; }
      public string symbol { get; set; }
      public string side { get; set; }
 }

 public class orders
 {
      List<order> order { get; set; }
 }

 JsonSerializer serializer = new JsonSerializer();
 orders myOrders = serializer.Deserialize<orders>(response);

 if (myOrders.order.Count() == 1)
   // we have 1 order

Comment: I Agree with you #evanmcdonnal. btw I did the class def..
`public class Rootobject
{
    public Orders orders { get; set; }
}

public class Orders
{
    public Order[] order { get; set; }
}

public class Order
{
    public int id { get; set; }
    public string type { get; set; }
    public string symbol { get; set; }
    public string side { get; set; }
}`
Comment: @aceventura yeah, I left out that outer most layer of indirection. Please accept answer if it solved your problem :)
Comment: But, how do I check for single/multiple orders? and also I need to map the arraylist to an IEnumerable type of Order object. How can I do that? Thanks in advance.
Comment: @aceventura `List` implements `IEnumerable` so you're good to go there. For checking how many orders there are just use `rootInstance.orders.order.Count()`. If you want you could change `List` to `IEnumerable` or `order[]` but I personally prefer using `List` in most cases.
Comment: Thank You very much #evanmcdonnal. I appreciate your help!
Comment: Hi #evanmcdonnal, I get an error when I get back only 1 record for order list.
`"Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'GetOrder[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) `
Comment: My request is similar to the below existing request.
`http://stackoverflow.com/questions/10118324/how-to-check-if-a-variable-is-array-or-object`
Comment: @aceventura in both of your example json blobs you have an array, it's just in the one case it has a single item in it. I believe if your class were to have both a `List` and a plain old `order` after you deserialize with json.NET one would remain null while the other gets instantiated/populated with the json data. You could just check for nullity afterwards or you could use the `object` approach, my only problem with that is that you give up type safety.
Comment: btw if you want me to be alerted by your comments you need to use @userName rather than #userName
Comment: Thank You @evanmcdonnal. Going by the twitter way..;-)
Answer: Able to fix the issue pertaining to check if the JSON result returned is an object or an array.
Modified my RootObject which has the Array/Object as follows:
 [JsonConverter(typeof(GenericListCreationJsonConverter<T>))]
 public List<T> order { get; set; }

Added the below class which checks for JSON
internal class GenericListCreationJsonConverter<T> : JsonConverter
    {

        public override bool CanConvert(Type objectType)
        {
            return true;
        }

        public override bool CanRead
        {
            get { return true; }
        }

        public override bool CanWrite
        {
            get { return false; }
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.StartArray)
            {
                return serializer.Deserialize<List<T>>(reader);
            }
            else
            {
                T t = serializer.Deserialize<T>(reader);
                return new List<T>(new[] { t });
            }
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }


Extract simple text from HTML on iPhone?

Question:
 TEXT TO EXTRACT

 TEXT & MORE TEXT"TEXT" TEXT

Above are examples of the HTML I wish to extract the text into an NSString, ignoring the div wrapper and any other 'stuff' - Some have
 included and some have ISO codes (can't remember exact name for these e.g &amp)
many thanks
Nik
Answer: Perhaps a stronger solution would be to parse the HTML using a Library.
A link and example in this question.
Simple libxml2 HTML parsing example, using Objective-c, Xcode, and HTMLparser.h
Answer: I ended up using this catagory:
https://github.com/mwaterfall/MWFeedParser/blob/master/Classes/NSString+HTML.m
works great.


Qual a função de carácter ? no tipo de variável em C#?

Question: Vejo muitos códigos de terceiros e vejo frequentemente a utilização do sinal de interrogação no tipo da variável.
Exemplo:
public bool? Status

Alguém poderia me explicar qual a diferença de não se ter esse sinal ? no tipo de dado bool.
Answer: Isso é açúcar sintático pra nullables (tipos anuláveis). Equivale a:
public Nullable<bool> Status

É uma forma de você ter uma variável que pode conter uma referência nula ou um valor. Os tipos por valor (inteiro, booleano, datas etc.), por padrão, não podem conter referências nulas.
Mais informações no manual.
Comment: Hmmm.... entendi boa resposta vou passar a usar isso para poder fazer comparações de nulls. Obrigado!


How to create a matrix with specified row and col names, from a dataframe containing the data and the names

Question: If I have a dataframe like so:
dataframe <- data.frame(Date = seq(as.Date("2018/01/01"), by = "day", length.out = 5),
                        ID1 = c(1, 2, 3, 4, 5),
                        ID2 = c(6, 7, 8, 9, 10))

> dataframe
        Date ID1 ID2
1 2018-01-01   1   6
2 2018-01-02   2   7
3 2018-01-03   3   8
4 2018-01-04   4   9
5 2018-01-05   5  10

What is the best way to convert it into a matrix, with the observations as the data,  Dates as row names, and the IDs as col names?
I'd think there would be a function that converted dataframes and took certain column/rows as arguments for col/row names, but I have not found that.
Bonus question: Do I need to have a distinct matrix for each ID? Do I need to create a 3D array or similar? How could I do that?
Comment: `row.names(dataframe) = dataframe$Date; dataframe = as.matrix(dataframe[,-1])`
Comment: Why do you need this as a matrix?
Comment: Possible duplicate of [in R: Two Way Match to Matrix](https://stackoverflow.com/questions/37739840/in-r-two-way-match-to-matrix)
Comment: G5W's solution above works perfectly. Basically, I just needed to assign rownames based the Date column and then convert the appropriate index of the df into a matrix. The column names are taken are of automatically.
Answer: First set the row names and then convert it to matrix:
as.matrix(data.frame(dataframe[-1], row.names = dataframe$Date))

Another possibility is to use a zoo or xts object.  This will create a matrix for the data and define an index attribute for the dates.  The resulting object is of class zoo and can be manipulated by the functions of the zoo package.
library(zoo)
z <- read.zoo(dataframe)


AWS cognito sso user authentication with django rest framework, react js, and ALB

Question: I am using Okta SSO user authentication in aws-cognito. After authentication it redirects to the Amazon load balancer and the frontend URL is loaded in the browser. To get the user-data I need to get the code that is passed in:
https://example.com/oauth2/idpresponse?code=xxx
This URL, along with other URLs, can be seen in the network tab of my browser's developer console. Is there any way I can access the code that's passed with this URL?
I am using reactjs for frontend and django-rest-framework for backend.
Comment: Thanks @rmlockerd for the edit. Please let me know if you find and answer for this
Comment: created a work around for the issue.
Answer: I have created a work around, redirect api from ABL contains the header, redirect that to a custom api of your choice


Submitting a form sends blank values to API, why?

Question: After integrating Pods with one of my resource address. All seems well, except when I submit the form (with valid values) in app/checkout/address/new/template.js.
I get POST http://localhost:4099/api/v1/addresses in the console tab in Ember Inspector. The Network tab indicates that it sent blank values to the API.
What am I doing wrong?
// app/checkout/address/new/route.js
import Ember from 'ember';

export default Ember.Route.extend({
  model: function() {
    return this.store.createRecord('address');
  }
});

// app/checkout/address/base/controller.js
import Ember from 'ember';

export default Ember.Controller.extend({
  actions: {
    save: function() {
      var _this = this;

      // this.store.createRecord('product').save().then(function(product){
      this.get('model').save().then(function(address){
        _this.transitionToRoute('checkout.addresses.index');
      }, function() {
        console.log('error');
        // Need this promise, so we can render errors, if any, in the form
      });

      return false;
    },
    cancel: function() {
      return true;
    }
  }
});

// app/checkout/address/new/controller.js
import AddressBaseController from '../base/controller';

export default AddressBaseController.extend({
  actions: {
    cancel: function() {
      this.store.unloadAll('address');
      this.transitionToRoute('checkout.address.index');

      return false;
    }
  }
});

// app/checkout/address/new/template.js

Add new address

<form {{action "save" on="submit"}}>

    First name:
      {{input value=firstName}}

    {{#each error in errors.firstName}}

{{error.message}}
    {{/each}}

    Last name:
      {{input value=lastName}}

    {{#each error in errors.lastName}}

{{error.message}}
    {{/each}}

    Address:
      {{input value=address1 placeholder="Foo Street"}}

    {{#each error in errors.address1}}

{{error.message}}
    {{/each}}

    {{input value=address2 placeholder="Bar"}}

    {{#each error in errors.address2}}

{{error.message}}
    {{/each}}

    City:
      {{input value=city placeholder="New York"}}

    {{#each error in errors.city}}

{{error.message}}
    {{/each}}

    Postal code:
      {{input value=postalCode placeholder="213213"}}

    {{#each error in errors.postalCode}}

{{error.message}}
    {{/each}}

    Contact number:
      {{input value=contactNumber placeholder="8888 8888 888"}}

    {{#each error in errors.contactNumber}}

{{error.message}}
    {{/each}}

    Instructions (optional):
      {{textarea value=instructions placeholder="Lorem ipsum dolor"}}

    {{#each error in errors.instructions}}

{{error.message}}
    {{/each}}

  <input type="submit" value="Next"/>
  <button {{action "cancel"}}>Cancel</button>
</form>

{{outlet}}

Comment: If you have your model in `app/checkout/address/model.js`, then your model name won't be `address`, but something like `checkoutAddress`.
Answer: You need to add model before your values in the template, otherwise use ObjectController, which isn't recommended since it's going away in Ember 2.0.

  First name:
  {{input value=model.firstName}}


Replacement for hook_user_presave() for saving values captured in the user form to the user profile

Question: I am porting a module from Drupal 7 to Drupal 9. The code uses hook_user_presave() to save two fields on the fly into the user profile data.
/**
 * Implements hook_user_presave().
 */
function affiliate_user_presave(&$edit, $account, $category) {
  $edit['data']['affiliate_optin'] = isset($edit['affiliate_optin']) ? $edit['affiliate_optin'] : 0;
  $edit['data']['affiliate_homepage'] = isset($edit['affiliate_homepage']) ? $edit['affiliate_homepage'] : FALSE;
}

The similar one in Drupal 9 seems to be hook_entity_presave().
/**
 * Implements hook_ENTITY_TYPE_presave() for user entities.
 */
function uber_affiliate_user_presave(UserInterface $account) {
  // code here
}

However there is only a single parameter to the function and so the edit values in the user profile form submit are not available here. So this means that there are better alternatives in Drupal 9.
I am thinking of writing an event subscriber, but it won't get the form submitted values.
Comment: Does this old change record answer the question? https://www.drupal.org/node/1554986
Comment: Well this looks a good start. However how do I get the values in form submit into presave. This seems to have been predesigned that way in Drupal 7 with the $edit parameter?
Answer: As pointed out from @cilefen, the $edit parameter has been removed from the parameter passed to hook_user_presave(), which (starting from Drupal 8) is now documented under hook_ENTITY_TYPE_presave(). $edit argument removed from hook_user_update/insert/presave() is the relevant change record.
The only way to get the submitted form values is to add a form submission handler to the form with hook_form_alter() or hook_form_FORM_ID_alter(). Form submission handlers, like form validation handlers(), have access to the submitted values via $form_state->getValue(), to get a single submitted value, or $form_state->getValues(), to get an array containing all the submitted values.
Also, what that code saves in $edit['data'] now needs to be saved with UserData::set(). Since that class is used to implement a service, the correct code to use it is similar to the following one.
$user_data = Drupal::service('user.data');
$user_data->set($module, $uid, $name, $value);

The parameters are the following.

$module
the machine name of the module that is saving the data
$uid
the user ID to which the data is associated
$name
the name associated with the saved data
$data
the data to save

To get the already saved data, or to check it has been already saved, there is UserData::get(). Passing $module, $uid, and $name that method will return NULL when the data hasn't been yet saved.
The change record that documents the new user.data service is users.data column replaced with user_data API.
Comment: I think hook_ENTITY_presave is called before form submit is handler is called as I am not able to get the values inside hook_user_presave.
Comment: `hook_ENTITY_TYPE_presave()` is invoked from the form submission handler for the form to edit an entity or create an entity. The answer isn't suggesting to use that hook, but to add a form submission handler to the edit form.
Comment: *The only way to get the submitted form values is to add a form submission handler to the form with `hook_form_alter()` or `hook_form_FORM_ID_alter()`.* How to add a form submission handler has not changed, passing from Drupal 7 to Drupal 8.
Comment: Thanks got it now.


What is the solution for Configuration failed because libmysqlclient was not found.?

Question: <code>Configuration failed because libmysqlclient was not found. Try installing:
 * deb: libmariadb-client-lgpl-dev (Debian, Ubuntu 16.04)
        libmariadbclient-dev (Ubuntu 14.04)
 * rpm: mariadb-devel | mysql-devel (Fedora, CentOS, RHEL)
 * csw: mysql56_dev (Solaris)
 * brew: mariadb-connector-c (OSX)
If libmysqlclient is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a libmysqlclient.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
</code>
Comment: It looks to me like the error message provides a couple of suggestions: 1 install packages if they are missing, 2 If packages are already installed, check the paths. You can check paths using `Sys.getenv("PATH")`.
Answer: Try this:
sudo apt-get install libmysqlclient-dev
intalling mysql client will solve the problem in ubuntu.


Is it a goal if the ball goes through the net?

Question: I was recently debating this with a friend, who argued that a goal does not stand if it goes through the net. I could not find an answer anywhere in the FIFA, FA or UEFA guidelines on the rules of the game.
Does a goal still stand if the ball goes through the net?
Comment: For future reference when a friend makes a claim, ask him/her if he/she can back it up somehow. :)
Comment: I always do, but due to where we were when we were debating it, neither of us could substantiate our claims :)
Comment: There was a famous incident in the EPL when the ball went through a hole in the side of the net and bounced back onto the pitch. The goal wasn't given however the rebound was scored so the officials got away with it.
Answer: Yes, it's a goal. And in fact, the two assistant referees are charged with checking if the net is in correct shape before the start of each period.
The net is only there to help the referee see a goal, but it is a goal even if the ball goes through it, or doesn't touch it, or if the ball rebounds off the net and returns to the playing field.
Law 1 - The Field of Play: 10. Goals states:

A goal is scored when the whole of the ball passes over the goal line,
  between the goalposts and under the crossbar, provided that no offence
  or infringement of the Laws of the Game has been committed by the team
  scoring the goal.

In Law 10 - Determining the Outcome of a Match: 1. Goals Scored the only reference to the net, reads:

Nets may be attached to the goals and the ground behind the goal,
  provided that they are properly supported and do not interfere with
  the goalkeeper.

It says may be, so I suspect it might not be mandatory.
Comment: If you don't play with a net, it's still a goal ;)
Comment: So, even if the net were to have a hole in it that the assistants didn't spot, and the ball were to go through it, it still stands?
Comment: Have you found any official references to back this up? I'm aware what is considered the norm in practice, but he seemed to think that it is not a goal in an official match if the ball goes through the net.
Comment: @OliverG based on your 1st comment are you referring to a ball going through the side netting? this would not count as a goal.  The ball has to pass between the uprights to count as a goal.
Comment: Haha, thanks Aidan, i am aware of that. I am referring to if it penetrates the net having crossed the line between the posts.
Comment: For remarks about @AidanO comment, I will search for a goal just like what you said, in the first division of Argentinian football, around 20 years ago, that the ball his the post that was helping the net, goes through a hole in the net, and since it was a fast movement, the ref call a goal on it.
Answer: As per Law 10 of the FIFA Laws of the Game:

A goal is scored when the whole of the ball passes over the goal line, between the goalposts and under the crossbar, provided that no infringement of the Laws of the Game has been committed previously by the team scoring the goal.

There is no requirement that the ball needs to touch the net for it to be counted as a goal. In fact, a net is not a mandatory requirement in order for a game to be played, as per Law 1 (emphasis mine):

Nets MAY be attached to the goals and the ground behind the goal, provided that they are properly supported and do not interfere with the goalkeeper.

Obviously though, there will be a net 99% of the time as it helps EVERYONE to see that a goal has been scored (most of the time).
It is either the referee or assistant referees job to conduct a check of the nets always before the game. By having the nets not secured properly or with holes in them, it just makes their own job much more harder. EG) A ball enters the goal through a hole in the side of the net when going out for a goal kick.
Hope this answers your question. In 11 years of refereeing, I quickly learnt to check the nets before every game after this kind of incident happened to me.


Interior and accumulation points

Question: Show that every interior point of a set must also be an accumulation point of that set.
Definitions:
Any point $x$ that belongs to $E$ is said to be an interior point of $E$ provided that some interval $(x-c,\ x+c)\subset E$.
Any point $x$ (not necessarily in $E$) is said to be an accumulation point of $E$ provided that  for every $c>0$ the intersection $(x-c,\ x+c)\cap E$ contains infinitely many points.
How do I show that every interior point of a set must also be an accumulation point of that set from these 2 definitions?
Answer: There is $\varepsilon > 0$ such that $(x-\varepsilon, x + \varepsilon ) \subset E$. Let $\varepsilon_n = \frac{\varepsilon}{n}$. Take $x_n \in (x-\varepsilon_n, x + \varepsilon_n ) \setminus (x-\varepsilon_{n+1}, x + \varepsilon_{n+1} )$. The set $\left\{ x_i \right\}_{i=1}^\infty \cap (x-c, x + c )$ is infinite for any $c >0 $.
Comment: It would be clearer to write $\{x_1, x_2, \ldots\}$ where you have written $\{x_n\}$ (which looks like a singleton set at first glance, forcing the reader to look at the context to figure out what you actually meant).
Comment: Thank you for your comment. I changed the notation.
Answer: Let $x$ be an interior point of $E$, $(x-c,x+c)\subset E$. Let $d>0$, $(x-inf(c,d),x+inf(c,d))\cap E\subset (x-c,x+c)\subset E$. Since $(x-inf(c,d),x+inf(c,d))\subset (x-d,x+d)$ contains an infinite number of points, the result follows.
Answer: Let $x$ be an interior point of $E.$ Since $x$ is an interior point of $E$ there exists $c>0$ such that $(x-c,\ x+c)\subset E.$ Now, you have to show that it is an accumulation point. That is, you have to show that for any $d>0$ the set $(x-d,x+d)\cap E$ contains infinitely many points. Of course, it is enough to consider $d\le c.$ But then $(x-d,x+d)\cap E=(x-d,x+d)$ (since $(x-c,\ x+c)\subset E$) which clearly contains infinitely many poitns. (If $d>c$ use that  $(x-c,x+c)\subset (x-d,x+d)\cap E.)$
Answer: If $(x-c, x+c) \subset E$, then $(x-c,x+c) \cap E = (x-c,x+c)$ which is an interval that contains infinitely many points for any $c > 0$.
From the first definition, we know that for small enough $c_0$, we have $(x-c_0,x+c_0) \subset E$. If $c \le c_0$, then $(x-c,x+c) \cap E = (x-c,x+c)$ contains infinitely many points. Otherwise if $c > c_0$, then $(x-c_0,x+c_0) \subset E$ contains infinitely many points and hence $(x-c_0,x+c_0) \subset (x-c,x+c)\cap E$ implies the superset also contains infinitely many points.

Interior and accumulation points


Como montar um inner join filtrando por um campo com valor minimo?

Question: Queria montar um inner join que trouxesse somente os valores filtrados por um campo de minimo valor
select min(data_vencimento) from pagamento where cod_situacao = 3,
cli.cpf, cli.nome, con.data_inicio, con.data_fim,
sit.situacao, con.valor_mensalidade  from cliente cli
inner join contrato con on con.cpf = cli.cpf
inner join pagamento pag on pag.COD_CONTRATO = con.COD_CONTRATO
inner join situacao sit on sit.cod = pag.cod_situacao;

Comment: Como foi feita suas tabelas? Onde você pega este valor minimo?
Comment: seria uma data_vencimento como varchar e os pagamentos sao gerados automaticamente no sistema c#.
Comment: tem situacao de pagamento: 1 = em aberto, 2 = pago, 3 vencido
Comment: gerei 5 pagamentos, deixei 3 em aberto, 1 vencido, 1 pago. Como exemplo :
   1º   Data_vencimento = 09/07/2017 em aberto
     2° Data_vencimento = 09/08/2017 em aberto                                                                                queria mostrar somento uma linha com o vencimento para  09/07/2017
Comment: @MarcusVinicius , já estudou álgebra relacional? SQL é uma implementação parcial dessa matemática, pode ajudar bastante nas suas consultas entender a parte algébrica de trás de tudo isso
Answer: Você deveria fazer assim:
SELECT MIN(co.data_vencimento), c.cpf
FROM cliente c
INNER JOIN contrato co ON co.cpf = c.cpf
INNER JOIN pagamento p ON p.COD_CONTRATO = co.COD_CONTRATO
INNER JOIN situacao s ON s.cod = p.cod_situacao
WHERE cod_situacao = 3
GROUP BY c.cpf

Levando em consideração que o campo "data_vencimento" existe na tabela "contrato" e que vc queira a menor data de vencimento por cliente.
Caso vc queira isso agrupado por contrato, deveria ser assim:
SELECT MIN(co.data_vencimento), con.cod
FROM cliente c
INNER JOIN contrato co ON co.cpf = c.cpf
INNER JOIN pagamento p ON p.COD_CONTRATO = co.COD_CONTRATO
INNER JOIN situacao s ON s.cod = p.cod_situacao
WHERE cod_situacao = 3
GROUP BY co.cod

O importante aqui é entender que o "group by" junto com a função de agregacão "MIN" é o que vai te dar essa informação.
Abs!
Comment: Um subselect do tipo data_vencimento = (select min(data_vencimento) from ...) não resolve ?
Comment: Pode resolver mas vc está fazendo uma subquery o que traz uma complexidade maior para a sua query .. Fica ai mais uma opção para  escolha, se preferir usa subselect, não vejo problemas.


Attack on first notes on trumpet

Question: I realized that when starting a note on trumpet, It always, especially with lower notes like low C (Bb) to start making the sound it comes a stream of air first.
I wonder how I can do to start the note from the beginning.
I came up with using a lip attack like saying a "P" but I'm not sure if this is correct or I should do it in other way.
Should I use the tongue like TA, TU, TI, KA, KU, etc?
The problem is that when trying to use the tongue I tend to make a b it of spit.
Comment: As always -- get a qualified teacher and take lessons.
Comment: @CarlWitthoft I could not find teachers in nearby....
Answer: You should always tongue each note, unless it's a slur from the previous note. "Tah" is a good syllable to think in general, and especially for low notes. "Tee" may work better for high notes, since leaving the tongue high in the mouth forces the air to go faster.
As for unintentional spit, it's just a matter of managing how moist your mouth is. Do a quick swallow before playing and it shouldn't be an issue.
Comment: Whilst I agree with the suggested consonants, I'd always advise against using different vowel shapes for high and low notes. Should be "Ah" for everything - the reason is that if you arch your tongue you constrict the air flow. Using an Ee shaped tongue is often an exasperated teacher's "quick fix" solution for high notes, and is counter-productive (i.e it has to be unlearned) in the long run.
Answer: Think about the sequence of things that must happen each time you start a note on the trumpet:

Form your embouchure and place the mouthpiece.
Breathe in through the corners of your mouth so your lungs inflate.
Plant the tip of your tongue in the angle between hard palette and top teeth (not between your lips or behind your bottom teeth). This seals your mouth so no air can escape.
Contract your chest, increasing the internal air pressure within your chest and mouth.
Draw your tongue back sharply as though pronouncing the syllable "Tu!". Your tongue should then be flat in the bottom of your mouth. Don't let it get in the way of the air stream.
The note starts immediately with a beautiful crisp attack.
Follow through with your chest contraction so the wind speed stays constant.

The sequence is the important thing here. If you do step 4 without first doing step 3 then there will be no air to produce the note. If you tongue first and only then try to produce a stream of air the production will be unreliable.
Having read this you may already know what the problem is in your note production.
One other thing to do is to practise producing those low notes. Set your metronome going and then play 8th notes on a low C. The goal here is to internalize how it feels to produce those sounds. Good notes feel different to bad notes and you need to repeat often enough that the good happens more often than the bad. Do this for a few minutes a day for a couple of weeks and you'll hear the difference.
Acceptable consonants for starting the note are "Tu!", "Du!" and sometimes "Ku!" (if you're double-tonguing). But don't use "P" or "B" sounds because they disturb your lips.
Answer: As a beginner it is important to use your tongue,  but you can also train to get a sound only by breath (p,pf,f,h). You can explore your instrument and your body experimenting as much as you like, as far as you don't get bad habits.
Here arise the "PS" which tries to bring as lossless as possible to the lips. A very efficient exercise for this is the "Breath Attack". The lip is closed, the sound is only played with the air. Make sure that the use of the "support" and the beginning of the sound are exactly the same. One way as m

Attack on first notes on trumpet


For which $z \in \mathbb{C}$ does $f(z) = |z|^2 +2z$ satisfy Cauchy-Riemann equations?

Question: The task is as follows:
$$
\text{Check, for which } z\in\mathbb{C} \text{ function } f(z) = |z|^2 +2z \text{ satisfies the Cauchy-Riemann equations.}
$$
I figured I need to transform $f(z)$ to $f(x,y) = u(x,y) + i \cdot v(x,y)$.
I started by transforming $f(z)$ to $f(x+iy)$ as such:
$$
f(x+iy) = \sqrt{x^2+y^2} + 2(x + iy) = (\sqrt{x^2+y^2}+2x)+(2y)\cdot i
$$
Therefore:
$$
\begin{cases}
u(x,y)=\sqrt{x^2+y^2} + 2x\\
v(x,y) = 2y
\end{cases}
$$
Unfortunately, when checking I started to check the Cauchy-Riemann equations I got the solution "$f(z)$ does not satisfy the Cauchy-Riemann equations for any $z\in \mathbb{C}$" which is wrong.
Here's how I got this erroneous solution:
$$
\frac{\partial u}{\partial x} = \frac{-x}{\sqrt{x^2+y^2}}+2
\\
\frac{\partial v}{\partial y} = 2
\\
\frac{\partial u}{\partial x}=\frac{\partial v}{\partial y} \Leftrightarrow x=0 \wedge y\neq0
$$
$$$$
$$
\frac{\partial u}{\partial y} = \frac{-y}{\sqrt{x^2+y^2}}
\\
-\frac{\partial v}{\partial x} = 0
\\
\frac{\partial u}{\partial y}=-\frac{\partial v}{\partial x} \Leftrightarrow y=0 \wedge x\neq0
$$
And just like that I got the wrong answer. Where did I go wrong? How do I do this task correctly?
Comment: $|z| = x^2 + y^2$, not $\sqrt{x^2+y^2}$.
Answer: You calculated $|z|^2$ wrong.
It should be $x^2+y^2$.
Since $h(z)=2z$ is analytic, you can focus on $g(z)=|z|^2=x^2+y^2$ where $z=x+iy$.
Now $u(x,y)=x^2+y^2$ and $v(x,y)=0$ for $g=u+iv$. You can go on and check the C-R equations.


Cover times and hitting times of random walks

Question: Consider a random walk on an undirected graph which, at each step, moves to a uniformly random neighbor. Define $T(u,v)$ to be the expected time until such a walk, starting from $u$, arrives at $v$, and let $T = \max_{u,v} T(u,v)$. Define $G(u)$ to be the expected time until such a walk, starting from $u$, visits every vertex and let $G = \max_u G(u)$. Is it true that  $$G \leq cT$$ for some constant $c$ which does not depend on the graph and any of its parameters (e.g., number of nodes)?
Comment: btw, I believe the "standard" notation for $T(u,v)$ is actually $H(u,v)$ (or $H_{uv}$). And $C$ instead of $G$.
Answer: That seems false.
For the complete graph $K_n$, $T = T(u,v) = \mathcal{O}(n)$, but $G = \Theta(n \log n)$.
Comment: This is a bit simpler than my example :-)
Answer: No. Take a graph with one central vertex and $n$ vertices connected only to the central vertex. The expected time to visit every vertex is determined by the coupon collector's problem and goes as $n\log n$, whereas the expected time to visit any vertex from any other vertex only goes as $n$.


Why is it true that $\lim_{n\to\infty} \left(\int_a^b \left|f(x)\right|^ndx\right)^{1/n} = \text{sup}\{\left|f(x)\right| : x \in [a,b]\}$?

Question: Can someone explain the intuition behind this/ what the proof might look for this?
If $f$ is a continuous, real-valued function on $[a,b]$, then
\begin{equation}
\lim_{n\to\infty} \left(\int_a^b \left|f(x)\right|^ndx\right)^{1/n} = \text{sup}\{\left|f(x)\right| : x \in [a,b]\}
\end{equation}
It seems like it's a way of averaging $\left|f(x)\right|$, similar to how the Lyapunov number is an average of all the slopes of an orbit in a dynamical system.
Answer: Let $M = \sup \{|f(x)|: x \in [a,b]\}$, and suppose $M > 0$.  For  $M > \epsilon > 0$, if $\delta > 0$ is small enough there is an interval of length $\le \delta$ on which $|f(x)| > M - \epsilon$.  Therefore
$$ M^n (b-a) \ge \int_a^b |f(x)|^n\; dx \ge \delta (M-\epsilon)^n $$
Take the $1/n$ power, and then limit as $n \to \infty$, and use the Squeeze Theorem.
Comment: Can I get clarification on why that inequality holds? Is $\delta(M-\epsilon)^n$ the maximum of the integral of $|f|^n$ on just the interval of length $\leq \delta$? So we know $\int_a^b |f(x)|^ndx$ is greater because that's just a portion. Then $M^n(b-a)$ is the maximum of the entire integral because $M^n$ is the supremum of $|f|^n$ so that is just the area of a rectangle with height $M^n$ and width $b-a$.
Comment: On an interval of length $\delta$, $|f(x)|^n > |M - \epsilon|^n$, so the integral over that interval is at least $\delta |M-\epsilon|^n$, and since the integrand is nonnegative the integral over $[a,b]$ is at least that.


Using SKScene as a loading screen

Question: In my game I am making, I wanted to make an animation every time the game is opened. I was thinking of using an SKScene as my loading scene to be able to show the animation. Do you think this is a good idea or is there a better way to go about going this?
Comment: Implement it. Does it work? Yes. Good. Don't get held up in analysis paralysis over such a trivial thing. ;)
Answer: SKScenes are the building blocks for Sprite Kit.  You can animate, delay and transition to another scene using the functionality scenes have built in.  Basically, make a sequence that ends with the scene transitioning to the next scene.
<code>// Here is transitioning code which covers a majority of your tasks.

SKTransition *reveal = [SKTransition flipHorizontalWithDuration:0.5];
SKScene * gameOverScene = [[GameOverScene alloc] initWithSize:self.size won:YES];
[self.view presentScene:gameOverScene transition: reveal];
</code>

Using SKScene as a loading screen


Where can I find useful R tutorials with various implementations?

Question: I'm using R and the manuals on the R site are really informative. However, I'd like to see some more examples and implementations with R which can help me develop my knowledge faster. Any suggestions?
Comment: This is really a Stackoverflow question as it has to do with learning the R programming language.  With the current wording the question is only associated with statistics by virtue of R's focus on statistical analysis.
Comment: I wouldn't vote to close it just yet- there could be a good question in there.  Perhaps something like "Where can I find useful tutorials that focus on putting statistical concepts into practice using a tool such as R?" or "Where can I find useful tutorials that teach statistics by example using tools such as R?"
Comment: http://meta.stats.stackexchange.com/questions/35/how-much-programming-here
Answer: Quick R site is basic, but quite nice for start http://www.statmethods.net/index.html .
Answer: R bloggers has been steadily supplying me with a lot of good pragmatic content.
From the author:
R-Bloggers.com is a central hub (e.g: A blog aggregator) of content
collected from bloggers who write about R (in English).
The site will help R bloggers and users to connect and follow
the "R blogosphere".

Answer: Another great resource is the LearnR blog, which went through an extensive study of visualizations with lattice and ggplot2.
Answer: R is designed around ideas such as "reproducible research" and "trustworthy software", as John Chambers says in his excellent book "Software for Data Analysis: Programming with R".
One of the best ways to learn R is to look at the wealth of source code that available on CRAN (with 2461 packages and counting).  Simple install.packages, load a library(), and start browsing the code.
Answer: I found this rather helpful: http://cran.r-project.org/doc/contrib/Verzani-SimpleR.pdf


question regrading double cone

Question: How to prove that double cone is not a topological manifold.I think I have to do something with the meeting point of the two cones.
Comment: You're right. It looks like 2 copies of $\mathbb{R}^2$ glued at a point.
Comment: but what does it imply?
Answer: Hint: By observation, the space around $(0,0)$ is giving us problems. In fact, it looks like 2 copies of $\mathbb{R}^2$ glued at a point.
Using this fact, show that any neighborhood around $(0,0)$ is not homeomorphic to $\mathbb{R}^2$ (and clearly not $\mathbb{R}^n$ for any other $n$), by considering the image of the lower cone (without the apex) and the upper cone (without the apex), which are 2 disjoint open sets.
Hence, it is not a topological manifold.

question regrading double cone