Swift and Salesforce IOS SDK

Question: I am trying to create a connected app with Salesforce IOS SDK and Swift and followed the steps mentioned  in the https://www.youtube.com/watch?v=9Mt02DzsOBo but as try to attach the "Appname-Swift.h"file in the AppDelegate.m file I am getting an error.Please help what can be done next.

1)I have created the native connected app as per Salesforce IOS
  Description
   2)Created the bridge for Swift
  "MySampleApp-Bridging-Header.h"
   3)Added SFRestDelegate to RootVC.Swift
  4)Imported the important header files to
  "mySampleApp-bridging-Header.h" that is

#import <UIKit/UIKit.h>
#import "SFRestAPI.h"

5)As soon I am trying to import #import "MySampleApp-Swift.h" I am getting the error
I am using OSX mavericks with XCode-6(4beta)
Answer: I don't think in the video or in the sample code repository there is a file named MySampleApp-Swift.h
Comment: You can change the app name alright. But did you really create a file 'MySampleApp-Swift.h'? The error is very explicit about missing this file. And based on your question, I thought you were going to create a MySampleApp-Bridging-Header.h
Comment: What I have done is I have changed the name of the app(that I can do I guess) to MySampleApp so the change.
Comment: But as per the tutorial it will be an auto generated header file for swift that will do the job and it should be of order "Appname-Swift.h"(this will be auto generated).

Swift and Salesforce IOS SDK


Pyspark's write stringtype argument doesn't deal with null values

Question: I am trying to write a dataset's data into postgres db using jdbc driver.
my_df.write().format('jdbc').mode('append')\
    .option('driver', 'org.postgresql.Driver')\
    .option('url', 'my_url')\
    .option('dbtable', 'my_dbtable')\
    .option('user', 'my_user').save()

Apparently pyspark tries to insert all textual types (i.e. uuid) as text by default and throws that error:
Caused by: org.postgresql.util.PSQLException: ERROR: column "id" is of type uuid  but expression is of type character varying

Hint: You will need to rewrite or cast the expression.
In order to overcome that issue I had to set a property:
'stringtype':"unspecified"

But that solution does not work on NULL values and throws that error
Caused by: org.postgresql.util.PSQLException: ERROR: column "id" is of type uuid  but expression is of type character

Which basically means that it tries to insert the NULL value as character. Separating the dataset to 2 datasets (as @Karuhanga suggested here Pyspark nullable uuid type uuid but expression is of type character varying) is not possible in my case. Did anyone face that issue and found a solution that does not fix a specific column?
Answer: Instead of putting a Null value in uuid columns, use as uuid by default like this:
uuid='00000000-0000-0000-0000-000000000000'

Comment: This is actually what I did (then i converted them to NULL when the process ended). Also used '01010000000000' for geometry but I think we should come up with a better solution. It's just a workaround.
Comment: @lidorbt did you find a better solution since then?
Comment: unfortunately I didn't find any solution for that - I just used @juanjosegdoj 's suggestion and changed all these values to null when the process ended


Updating Python in my folder on the cluster

Question: I want to run a program on our cluster environment which requires python 2.7. The thing is the version installed on the cluster is 2.6.6. Therefore, I tried to update the python version in my own folder. To do so, first I used module avail python command, but nothing showed up!!! Afterward, I tried which python2.7 on the command line, and I noticed that it exist in /usr/bin/python2.7. Going into the given subfolder, I tried module load python2.7 but I faced the following error:
ModuleCmd_Load.c(208):ERROR:105: Unable to locate a modulefile for 'python2.7'
I would be very thankful if someone could tell me how can I solve my problem.
Answer: The module command you use needs to find a modulefile for the module python2.7 you try to load. If such modulefile is found it usually updates the shell environment to active the software in question.
In the situation you describe, it seems there is no python module available by default currently. Which means you either:

need to find the modulepath to activate with the module use command where those python modulefiles are located
or write a modulefile to enable this python2.7 installation and save it in an existig modulepath directory


$X$ is a subset of $\mathbb{R}$. Prove that $|x-2|<c$ for all $x$ that are elements of $X$.

Question: Suppose that $X\subset\mathbb{R}$ (real numbers) is a bounded set. Prove that there exists a number $c$ that is an element of the real numbers, such that for all $x$ that are elements of $X$, the absolute value of $x-2$ is less than or equal to $c$.
can we assume $X$ is non-empty?
OR
if $X$ is non empty, the $X$ is a subset of $[m,M]$ and every $m\le x \le M$ if $x$ is an element if X, and then let $c=$ max of the absolute value of either $M-2$ or $m-2$.
and then show the absolute value of $x-2$ is between $-c$ and $c$?
Comment: If $X$ is empty, it is vacuously true.  The rest of what you say is correct.
Comment: I am confused on how I finish the proof.
Answer: Suppose $m \le x \le M$.  Then $m-2 \le x - 2 \le M-2$.
If $x-2 \ge 0$, then $x-2 \le M-2$.
If $x-2 \le 0$, then $2-x \le 2-m$.
So either way
$ |x-2| \le \max\{M-2, 2-m\} < \max\{M-2, 2-m\} + 1$.


O que significa o termo "atômico"?

Question: Vejo em algumas resposta/perguntas o termo "atômico".
Em programação, o que ele deve significar de fato?
Ex:
comparison (4) is possible only for atomic and list types
Tem como auto incrementar o id no mongo?
Comment: Foi mal, @Renan. Deu uma confusão entre minhas edições e as tuas.
Comment: @LINQ no problemo.
Answer: Atômico vem do átomo, ou seja, algo que é indivisível. Na computação usamos o termo quando algo é garantidamente feito por inteiro, não pode fazer apenas uma parte, ainda que tenha que descartar o que estava fazendo para garantir isso. Uma operação atômica não pode ser dividida em partes sem que cause algum problema.
Atualizar um valor inteiro é uma operação atômica na maioria das arquiteturas. Você não muda uma parte dele. Mudar um decimal ou long já pode não ser atômico porque ele pode ter mais que uma parte e se não tiver algum mecanismo que garanta a atomicidade, uma parte poderia ser mudada, e acontecer algo em seguida com esse valor e depois outra parte ser atualizada. Isso também é chamado de linearização.
Em banco de dados se usa muito o termo, principalmente em transações. Isso quer dizer que ou a transação faz por completo ou ela faz nada, não pode fazer só uma parte. Se você faz uma compra a operação tem que emitir a nota fiscal, mudar o saldo do estoque, baixar o pedido, gerar o boleto, etc., tudo junto, se algo falhar nada disso pode ser feito, não pode fazer algumas dessas e deixar as outras pra lá.
Isso tem a ver com o estado. A preocupação não é se o algoritmo em si foi executado por completo, mas se o estado foi mudado por completo. O que não altera estado não tem problemas de atomicidade. Então o que um método retorna nada tem a ver com esse conceito, terá se o método altera algum estado dentro dele. Se essa alteração for feita por completo, ou nada for feito, ela será atômica. Se ele deixar mudar só uma parte por alguma razão ela não é atômica.
O fato de fazer a alteração de uma parte deixar essa parte alterada visível por alguma operação concorrente e depois fazer a outra parte, também quebra a atomicidade (embora tenha mais a ver com isolamento), mesmo que a operação se complete. Se tem mais de uma parte é divisível, então não é atômico. Por isso existem mecanismos para controlar que várias partes executem juntas por completo antes de deixar algo acessar aquilo. O travamento é o mecanismo mais óbvio.
Quando não há qualquer forma de concorrência a atomicidade não é importante. O problema é que existe concorrência em vários pontos onde não vemos. E o fato de não haver concorrência não significa que algo não pode ser atômico. Ou algo é atômico ou não é. Se precisava ser é outra questão.
Tem a ver também com condição de corrida. É raro observar esse problema em certas ocasiões e isso faz as pessoas negligenciarem o problema. Ele é pior justamente por ser raro. É difícil de reproduzir e saber o que está acontecendo. Por isso tem que fazer certo mesmo que não parece ser necessário.
Coloquei no GitHub para referência futura.
Comment: Então um método que retorna true ou nada é atomico, e um método que pode retornar true, false ou uma exceção não seria, é isso ?
Comment: Não, nada a ver com isso, dei uma editada para melhorar.
Answer: A palavra átomo vem do grego  atomos. Ela é formada pelas partes:

a: radical que indica negação;
tomos: que significa divisões.

Logo, um átomo é algo que é impossível de se dividir (até surgir o Albert Einstein a Marie Curie e esculhambar com essa parte da física).
Em programação, nós dizemos que uma coisa é atômica se ela não puder ser quebrada em mais partes. Geralmente isso é utilizado em bancos de dados, para uma sequência de operações que devem ser tratadas como uma operação só por motivos de consistência de informações.
Por exemplo, suponha que você queira me transferir dinheiro através de Internet Banking. A sequência de passos no banco de dados seria a seguinte:
1-) seu saldo é subtraído da quantia a transferir;
2-) meu saldo é aumentado pela mesma quantia;
3-) é lançado um registro de saída no log da sua conta;
4-) é lançada um registro de entrada no log da minha conta.
O que acontece se a conexão cair entre o passo 1 e o passo 2? Seu dinheiro some e vai pro limbo, sem jamais chegar à minha conta, e sem o log da saída não tem como recuperar aquela quantia.
Ao tornar essa sequência atômica, o banco garante que ou ela acontece, ou ela não acontece, pois ela é indivisível e todos os passos devem ocorrer como um só. Na prática, isso significa que as operações ficam em memória e só são persistidas todas de uma vez - se uma operação falhar, todas as operações são revertidas.
Answer: Note: É necessário que você saiba o que é uma thread para entender a explicação abaixo.
Todas as instruções que você faz em um computador são divididas em partes, isso acontece pela forma como a arquitetura do computador é construída, por exemplo:
if(x == 3){
    // faz alguma coisa importante aqui e depois zera o x
    x=0;
}else{
    x++
}

para que o computador seja capaz de fazer a verificação de x == 3 ele divide isso em 8 partes.
Sabendo disso, imagine um programa que possui diversas threads, isso causa o que chamamos de situação de concorrência, exemplo: digamos que só existe duas threads, e a primeira chego no if(x==3) e logo em seguida ela irá zerar o valor de x porém essa ação não é atômica(ou seja não é executada de uma vez só.) e a segunda thread também chega no if antes da primeira conseguir zerar o x ou seja ela também ira entrar no if
Então quando trabalhamos com threads queremos que algumas ações sejam "atômicas", que em teoria quer dizer que ela seria executada de uma vez só, porem isso é impossível porque faz parte da arquitetura do computador, mas o sistema operacional consegue "burlar" a arquitetura e faz com que aquele ponto que foi sinalizado como atômico não seja acessado por outra thread até que ele seja liberado. Esse bloqueio e liberação é feito por meio de semáforos ou mutex, em java você tem classes que abstraem essa implementação para você.
Answer: Atomicidade:
Uma transação deve ser uma unidade atômica de trabalho; ou todas as suas modificações de dados são executadas ou nenhuma delas é executada.
fonte: Microsoft Technet

O que significa o termo "atômico"?


No style only Plain text when try to login

Question: SO I have a problem when I try to login to Drupal (drupal.kalianet.to/user)it gives me a plain text with no style. I realized when I inspect the page that it automatically put user after the domain name. Which Im not sure what really the problem.
Answer: Looks like the styles can't be loaded. Have you tried clearing the cache and saving the file-system path? Perhaps the sites/default/files folder isn't writeable.
Comment: Thank you for your reply I check the folder sites/default/files and it on 0755 which I think is writeable right?
Comment: 755 would do the trick. Perhaps it's handy to post a screenshot with some logs (admin/reports/dblog).
Comment: Thank you and sorry for the reply the website is live and you check it @ drupal.kalianet.to if that easy.
Comment: user 10/25/2017 - 22:14 Session opened for admin. admin
cron 10/25/2017 - 21:40 Cron run completed. Anonymous (not verified)
cron 10/25/2017 - 21:40 Execution of update_cron() took 25507.74ms. Anonymous (not verified)
cron 10/25/2017 - 21:39 Starting execution of update_cron(), execution of… Anonymous (not verified)
cron 10/25/2017 - 21:39 Starting execution of system_cron(), execution of… Anonymous (not verified)
cron 10/25/2017 - 21:39 Starting execution of search_cron(), execution


Flutter Dio package how to show onSendProgress data in widget

Question: I am using Dio package for a http api request and it works pretty well. However i have a requirement that I want to show progress while sending data to server. I have following codes
CommonApiProvider.dart
static Future saveUserData(Map params) async {
    try {
      var body = json.encode(params);
      final response = await _dio!.post("${globals.apiUrl}SaveUserData/",
          data: body,
          onSendProgress: (int sent, int total) {
              print("$sent kb of data sent of total $total kb");
      });
      if (response.statusCode == 200) {
        Map<String, String> d = Map<String, String>.from(response.data);
        return d;
      } else {
        return null;
      }
    } catch (exception) {
      return null;
    }
  }

And I am calling this from my GetX controller like this
Future saveUserData() async{
    Map params = {
      ....
    };

    var res = await CommonApiProvider.saveUserData(params);
    .......
}

The above code works and prints progress in debug console. however I want to show this information to user, in a Widget.
Can please someone tell me how to do this?
Answer: One simple way is just to pass the same callback to saveUserData.
static Future saveUserData(Map params, ProgressCallback onSendProgress) async {
...
      final response = await _dio!.post("${globals.apiUrl}SaveUserData/",
          data: body,
          onSendProgress: onSendProgress
      );
...
}


Probability of customers arriving and waiting

Question: Customers arrive at a bank at the mean rate of 20 per hour. the exponential probability distribution describe the time between customer arrivals. (a) What is the probability that a customer arrives within 3 mins of a previous customer? (b) What is the probability that the bank will go 6 mins without any customer?
Comment: (b) Part (b) might depend on how long it takes to serve a customer
Comment: In (b), do you mean "without any customer arriving"? If you mean "without any customer being there", Henry's comment (b) applies. Also, presumably you mean "go without any customer for 6 *particular* minutes"? The probability that the bank will at *some* point go without any customer for 6 minutes is $1$.
Answer: We need to decide between minutes and hours for our unit of time. Say it is minutes. Then the mean time between arrivals is $3$ minutes. Or else, depending on the way the exponential distribution has been introduced to you, the rate is $1/3$.
Recall that an exponential distribution with parameter $\lambda$ has mean $\frac{1}{\lambda}$.  So $\frac{1}{\lambda}=3$ and therefore $\lambda=\frac{1}{3}$.
A customer has just arrived. Let $X$ be the waiting time until the next customer arrives. Then $X$ has exponential distribution with parameter $\lambda=\frac{1}{3}$. For any positive $x$,
$$\Pr(X\le x)=\int_0^x \frac{1}{3}e^{-t/3}\,dt=1-e^{-x/3}.\tag{$1$}$$
Now we can answer the questions. Interpretation is needed, since there are some ambiguities in the questions.
(a) Interpret the question as saying: "Customer Alicia has just arrived. What is the probability that there will be a customer who arrives later than Alicia, but no more than $3$ minutes later." Then we want $\Pr(X\le 3)$. By $(1)$, this is $1-e^{-3/3}$.
(b) Interpret the question as saying that Alicia has just arrived, and we want the probability that there will be a gap of at least $6$ minutes until the next customer arrives. Then we want $\Pr(X\gt 6$. By $(1)$, this is $1-\Pr(X\le 6)$, which is $1-(1-e^{-6/3})$.
Remark: The exponential distribution is at best a crude model of the situation. For one thing, banks do close. For another, there is always a long line when one is in a hurry.


Why doesn't this coffescript code work?

Question: I am trying to make a function that lists all properties of an object
showProps = (obj) ->
 result = ""
 result+= String(i+ ' = ' + obj[i] + '\n') for i in obj when obj.hasOwnProperty(i)
 return result
O = {A:1}
alert showProps O

Why does the function return nothing?
Answer: CoffeeScript's for...in loops are for looping over arrays.  To iterate over an object, you want for...of (which compiles to Javascript's for...in).
If you use
result+= String(i+ ' = ' + obj[i] + '\n') for i of obj when obj.hasOwnProperty(i)

then you will get the result you're looking for.
As @muistooshort pointed out, you can get the hasOwnProperty part for free in CoffeeScript with own, which makes the code a bit simpler:
result+= String(i+ ' = ' + obj[i] + '\n') for own i of obj

Comment: Why not `for own i of obj` instead of `when obj.hasOwnProperty(i)`?
Comment: I made the smallest change that showed what was wrong and how to fix it.  That is probably worth mentioning, though.
Answer: You want an for [own] of-loop to iterate over properties:
showProps = (obj) ->
 result = ""
 result+= String(i+ ' = ' + v + '\n') for own i, v of obj
 return result
O = {A:1}
alert showProps O

Btw, you don't need the explicit String call since you're concatenating strings anyway, and your whole function could be defined more easily as an array comprehension:
showProps = (obj) ->
  (i+' = '+v  for own i, v of obj).join('\n')

Answer: It doesn't work because you used wrong operator. in is meant to be used for iterating through collections, like an array for example. You would like to use of operator.
Besides I changed your example a bit to make it more CoffeeScript way:
showProps = (obj) ->
  result = ""
  result += "#{i} = #{v} \n" for i, v of obj when obj.hasOwnProperty(i)
  result
anObject = A:1
alert showProps anObject

Why doesn't this coffescript code work?


Proving that the function $f(x)=\sum_n\frac{1}{10^n}\{10^nx\}$ is everywhere continuous but nowhere differentiable.

Question: Theorem: The function $f(x)=\sum_{n=1}^{\infty}\frac{1}{10^n}\{10^nx\}$ is everywhere continuous but nowhere differentiable, where $\{.\} $ represents distance from nearest integer.
This theorem has been taken from chapter $23$ of Spivak's Calculus book.
By Weirstrauss M test, $f$ is uniformly continuous.
In the book, the theorem is proven by showing that the limit $L=\lim_{m\to \infty}\frac{f(a+h_m)-f(a)}{h_m}=\lim_{m\to \infty}\sum_{n=1}^{\infty}\frac{\{10^n(a+h_m)\}-\{10^na\}}{10^nh_m}$ does not exist when $h_m\to 0$, where $a\in (0,1]$. Let $a=0.a_1a_2\cdots$
Let $h_m=10^{-m}$ if $a_m\ne 4,9$ and $h_m=-10^{-m}$ if $a_m=4,9$.$\tag{1}$
No. of terms in summation in the above limit $L$ is finite as if $n\ge m, 10^nh_m$ is integer and hence numerator of the summations becomes zero. So for $n\lt m$, $\{10^na\}=\text{integer}+0.a_{n+1}a_{n+2}\cdots a_m\cdots $ and
$10^n \{a+h_m\}=\text{integer}+0.a_{n+1}a_{n+2}\cdots (a_m\pm1)\cdots$ and this representation into decimals is correct as $h_m=-10^{-m}$ if $m=9$.
**

Then, Spivak makes a statement that if $0.a_{n+1}a_{n+2}\cdots
 a_m\cdots \le 0.5$, then we also have $0.a_{n+1}a_{n+2}\cdots (a_m\pm
 1)\cdots \le 0.5$ as $h_m=-10^{-m}$ if $a_m=4$.

**
And I think that this is not true at all because in the special case $m=n+1$, if $a_m=5$ then clearly $0.a_m\le 0.5$ but $0.(a_m\pm 1)\le 0.5$ is not true! and hence condition on $h_m$ should be $h_m=-10^{-m}$ when $a_m=5,9$ and $h_m=10^{-m}$ when $a_m\ne 5,9$. Is my understanding correct?
Another doubt that I have is:
Is the following alternative way correct?
Let's choose  $h_m=10^{-m}$ if $a_m\ne 9$ and $h_m=-10^{-m}$ if $a_m=9$. Then it's clear by writing decimal representation that, $\{10^n(a+h_m)\}-\{10^na\}=\pm 10^{n-m}$ and then $L=\lim_{m\to \infty}\frac{f(a+h_m)-f(a)}{h_m}=\lim_{m\to \infty}\sum_{n=1}^{\infty}\frac{\{10^n(a+h_m)\}-\{10^na\}}{10^nh_m}=\lim_{m\to \infty}\sum_{n=1}^{m-1}\frac{\{10^n(a+h_m)\}-\{10^na\}}{10^nh_m}\lim_{m\to \infty}\sum_{n=1}^{m-1}\pm 1=\lim_{m\to \infty}\pm (m-1)$,
which doesn't exist. Hence proved.
Please help. Thanks.
Comment: @OliverDiaz: Even in the book in your link, it's not made clear why $h_m=-10^{-m}$ when $a_m=4$, which I think should have been $a_m=5$. And why do we have to distinguish cases $\lt 1/2$ , $\gt 1/2$?
Comment: Do you agree that with $h_m=-10^{m}$ for $a_m=4,9$ and $h_m=10^{-m}$ things work? All you need is a particular sequence $h_m\rightarrow0$ for which the sum does not converge.  notice that there is a choice to make for the decimal expansion of $x$ when $x$ has a a possible finite decimal expansion.
Comment: @OliverDiaz: I disagree with $h_m=-10^{-m}$ when $a_m=4$ as it will create problems for $a_m=5$.
Comment: The choice $h_m=-10^{-m}$ for $a_m\in\{4,9\}$ and $h_m=10^{-m}$ otherwise does not cause any problem.
Comment: The confusion I gather is a typo in the text: the correct statement should be: $0.a_{n+1}a_{n+2}\cdots
 a_m\cdots < 0.5$, then we also have $0.a_{n+1}a_{n+2}\cdots (a_m\pm
 1)\cdots < 0.5$  (replace $\leq$ with $<$. The rest follows though).
Comment: The function was originally given by van der Warden and is discussed in the first chapter of *Functional Analysis* by F. Riesz and B. Nagy.
Answer: The idea of the construction is to keep fractional parts on the same side of $\frac{1}{2}$, that is if $10^na-\lfloor 10^na\rfloor <\frac{1}{2}$, then choose $h_m$ so that $10^n(a+h_m)-\lfloor 10^na\rfloor<\frac12$ and if $10^na-\lfloor 10^na\rfloor\geq\frac{1}{2}$, then choose $h_m$ so that $10^n(a+h_m)-\lfloor 10^na\rfloor\geq\frac12$
Notion:

$\lfloor x\rfloor$ is the integer part function: $\lfloor x\rfloor =\max\{n\in\mathbb{Z}: n\leq x\}$.
By definition $\{x\}=\min\big(x-\lfloor x\rfloor, \lfloor x\rfloor +1 -x\big)$.
For $a\in [0,1)$, write $a$ in decimal expansion $a=0.a_1a_2\ldots=\sum^\infty_{k=1}\frac{a_k}{10^k}$, where $a_m\in\{0,1,\ldots, 9\}$ and, for those $a$ with two different decimal expansions, choose the one with infinite number of $0$'s. For example $a=1/2=0.49999...=0.5$, we choose the expansion $a=0.5$.

Try to convince yourself that

If $a_m\notin\{4,9\}$ and $n=1,\ldots,m-1$, then
$$10^n(a+10^{-m})=a_1\ldots a_n.a_{n+1}\ldots (a_m+1)a_{m+1}\ldots$$
and so,
$$\{10^n(a+10^{-m})\}-\{10^na\}=\left\{\begin{array}{lcr}
10^{n-m} &\text{if}& a_{n+1}<5,\, a_m\neq4\\
-10^{n-m} &\text{if} & a_{n+1}\geq 5,\, a_m\neq9
\end{array}\right.$$

If $a_m\notin\{4,9\}$ and $n\geq m$, then
$$\{10^n(a+10^{-m})\}=\{0.a_{m+1}a_{m+2}\ldots\}=\{10^na\}$$
and so,
$$\{10^n(a+10^{-m})\}-\{10^na\}=0$$

Hence,  if $a_m\notin\{4,9\}$,
$$\Delta_m:=\frac{1}{10^{-m}}\sum^\infty_{n=1}\frac{\{10^n(a+10^{-m})\}-\{10^na\}}{10^n}\equiv m\mod 2$$

If $a_m\in\{4,9\}$ and  $1\leq n < m$, then
$$10^n(a-h_m)=a_1\ldots a_n.a_{n+1}\ldots(a_m-1)\,a_{m+1}\ldots$$
and so,
$$\{10^n(a-10^{-m})\}-\{10^na\}=\left\{\begin{array}{lcr}
-10^{n-m} & \text{if}& a_{n+1}<5,\, a_m=4\\
10^{n-m} & \text{if} & a_{n+1}\geq5,\, a_m=9
\end{array}
\right.$$

If $a_m\in\{4,9\}$ and  $n\geq m$, then
$$\{10^n(a-10^{-m})\}=\{0.a_{m+1}a_{m+2}\ldots\}=\{10^na\}$$
and so
$$\{10^n(a+10^{-m})\}-\{10^na\}=0$$

Hence, if $a_m\in\{4,9\}$
$$\Delta_m:=-\frac{1}{10^{-m}}\sum^\infty_{n=1}\frac{\{10^n(a-10^{-m})\}-\{10^na\}}{10^n}\equiv m\mod 2$$

If you were to modify the construction and set $h_m=-10^{-m}$ if $a_m\in\{5,9\}$ and $h_m=10^{-m}$ otherwise then, for $a$ with $a_m=4$ you get
$$ \{10^{m-1}(a+10^{m})\}-\{10^{m-1}a\}=1-10^{-m} -2(0.4a_{m+1}\ldots)
$$
and so
$$\frac{1}{10^m}\sum^\infty_{n=1}\frac{\{10^n(a+10^{-m})\}-\{10^na\}}{10^n}\notin\mathbb{Z}$$
The genius of the construction is to keep all differential increments $\Delta_m$ as integers that vary on the parity of $m$.
Comment: In "that is if $10^na-[10^na]<\frac{1}{2}$, then $10^n(a+h_m)-[10^na]<\frac12$", did you mean $10^n(a+h_m)-[10^n(a+h_m)]<\frac12$? I suppose $[.]$ is greatest integer function.
Comment: No, I wrote what I meant. The construction maintains which side of of 1/2 the fractional part is.
Comment: @Koro: In the construction, the only crucial setp is when $a_m=4$ and $n=m-1$. then $\{10^{m-1}(0.a_1\ldots a_{m-1}(4-1)a_{m+1}\ldots\}-\{10^{m-1}(0.a_1\ldots a_{m-1}4a_{m+1}\ldots\}=-0.1$
Comment: @Mittens - this is way above my head but would you be able to take a look at my answer and confirm whether or not there's an error in Spivak's text?
Comment: @Peter4075: I just lighten the compact notation (which used indicator functions) and expanded it for more clarity. Like I said in my posting, the distinction between  $a_m\in\{4,9\}$ and $a_m\notin\{4,9\}$ in order to keep the values of the differential increments (with $h_m=\pm 10^{-m}$ ) as integers is correct.
Comment: @Mittens - Fantastic answer, and much clearer to me now that you've expanded and tidied it up. I've attached to my answer the relevant pages from Spivak. You can see (where I've underlined) where he uses $\le0.5$ instead of $<0.5$.
Answer: I've been trying to make sense of this proof for days now. I believe there's an error in the text and that $$0.a_{n+1}a_{n+2}a_{n+3}\ldots a_{m}\ldots\le0.5$$ should read $$0.a_{n+1}a_{n+2}a_{n+3}\ldots a_{m}\ldots<0.5.$$As far as I can see it then also follows that$$0.a_{n+1}a_{n+2}a_{n+3}\ldots\left(a_{m}\pm1\right)\ldots<0.5.$$
For example, let $a=0.049, m=2, n=1.$ Therefore, $a_{m}=4\Rightarrow h_{m}=-10^{-m}=-10^{-2}.$ Which gives$$10^{m-n}\left(\left\{ 10^{n}\left(a+h_{m}\right)\right\} -\left\{ 10^{n}a\right\} \right)$$ $$=10\left(\left\{ 10\left(0.049-0.01\right)\right\} -\left\{ 10*0.049\right\} \right)$$ $$=10\left(\left\{ 0.48\right\} -\left\{ 0.49\right\} \right)=-1,$$
as predicted.
If you don't make the $"a_{m}=4"$ correction and instead use $h_{m}=+10^{-m}=10^{-2}$ you end up with $$10\left(\left\{ 10\left(0.049+0.01\right)\right\} -\left\{ 10*0.049\right\} \right)$$ $$=10\left(\left\{ 0.59\right\} -\left\{ 0.49\right\} \right)=-0.8,$$which $\neq\pm1.$
Here are the relevant pages from Spivak with the errors (?) underlined in red.
Comment: Yes, the error is in $\leq1/2$ which should be $<1/2$, and the case $>1/2$ you'd be $\geq1/2$. At the end of the day, the differences $\{10^na+10^{-m}\}-\{10^na\}=\pm1$ for $1\leq n<m$ and $0$ otherwise are correct.


Form API focus on first input

Question: When my form load I would like to set the focus on the first field in the form. I know I can use jquery to do this by doing $('inout id').focus();. Where would I put this code so that it only runs on a certain form?
Is there a simpler way?
Updated
Using a mixture of smile's answer and clive's comment the code that got it working in the end was:
$form['#attached']['js'] = array('(function ($){$(document).ready(function() { $(".form-item-field-name input").focus()});})(jQuery);' => array( 'type' => 'inline'));

Answer: You can attach js only to your form. Use hook_form_alter()
function your_module_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'my_form'){
  // Add JavaScript file
  $form['#attached']['js'] = array(drupal_get_path('module', 'your_module') . '/your_file.js');

  // Or for inline JavaScript
  $form['#attached']['js'] = array('/* some javascript here */' => array( 'type' => 'inline'));
  }
}

Comment: Tried `$form['#attached']['js'] = array('$(".form-item-field_name input").focus()' => array( 'type' => 'inline'));` but no joy
Comment: @user13134 Assuming you're using Drupal 7 you need to qualify the `$` var: (`(function($) { // code using $ })(jQuery);`), see [Managing JavaScript in Drupal 7](http://drupal.org/node/756722)
Answer: To add the HTML5 autofocus attribute from a module in D7, use this example for the user-login form. However, still not supported on iOS Safari as of this posting date.
function HOOK_form_user_login_alter(&$form, &$form_state, $form_id) {
    //should also add JS focus code for iOS Safari
    $form['name']['#attributes'] = array('autofocus' => '');
}

Form API focus on first input


Slur and tie confusion

Question: Not sure how to play this. It's in the bass clef. My understanding is that the first curved line (green) is called a "slur," which means "move smoothly from note 1 to note 2." And the lower line is a "tie" which increases the count of the joined notes to the combined count of both.
But how do I move from the A in the first bar to the G in the second bar (slur) if I've already played the G in the first bar (now "tied" to the G in the second bar)?
Answer:
how do I move from the A in the first bar to the G in the second bar

You don't.  There is only 1 G note.  Simply slur from A to G, and then hold the G for 3 beats.
Why are there 2 G note heads?  Because notes can't go over a barline, so the composer had to notate it with 2 note heads connected by a tie.  This is just a convention to enhance readability.
Why is the slur over both G's?  This is also just a convention of notation, though I'm not entirely sure why.  If you think of both note heads as being 1 note, then it makes some sense, no?
While they can look very similar, slurs are for articulation while ties are primarily for readability, so they operate on different planes, so to speak.
Answer: Play the A then smoothly start playing the G note, which, as you say, ties across the bar. Which means it doesn't get played again, purely held over for another two beats. The slur (or phrase mark) could have gone to the 1st G, but it's easier to understand the bigger picture if it expands to the end of the longer note, where the next slur (or phrase) starts.
Answer: The convention is that slurs start from the first of tied notes and end on the last of tied notes. Thus the slur covers both the endpoints. This convention makes it easier to quickly see the difference between ties (between time adjacent) notes and any pair of notes played legato.

Slur and tie confusion


Stoll, Set Theory and Logic (pg 165): Logic for P->Q and P<->Q

Question: Conditional P->Q: If P is True, then Q is also True.
Truth table
P Q P->Q
T T T
T F F
F T T
F F T

BiConditional P<->Q: If P is True, then Q is also True; If Q is True,
then P is also True.
P Q P<->Q
T T T
T F F
F T F
F F T

The motivation for the truth-value assignments made for the
  con-ditional is the fact that, as intuitively understood, P->Q is
  true if Q is deducible from P in some sort of way.
So, if P is true and Q is false, we want P->Q to be false, which accounts for the second line of the table.

My understanding of this is as follows: We are asserting that
IF P is TRUE then Q also is TRUE; therefore if Q happens to be False for a True P, then our assertion is FALSE. But remember here that we are giving/inserting real values to P and Q and then determining/evaluating the validity of P->Q (our assertion).

Next, suppose that Q is true. Then, independently of P and its truth
  value, it is plausible to assert that P->Q is true. This reasoning sug-
  gests the assignments made in the first and third lines of the table.

Wo! How?? What reasoning!!! He hasn't reasoned anything! The weasel! He just made a supposition and then a bloody assertion!

To justify the fourth line, consider the statement (P A Q) -> P. We expect
  this to be true regardless of the choice of P and Q. But, if P and Q are
  both false, then P A Q is false, and we are led to the conclusion that
  if both antecedent and consequent are false, a conditional is true.

What? He's saying: IF (P AND Q is TRUE) then P is also true. How the heck can that statement be independent of the values assigned to P and Q?? Still he says "We expect this to be true.." I don't expect it!! What's going on!!

I tried thinking of this another way:
P->Q implies: IF P is TRUE then Q also is TRUE
P<->Q implies: IF P is TRUE then Q also is TRUE; AND
               IF Q is TRUE then P also is TRUE

Let's say we make an assertion P->Q = [IF P is TRUE then Q also is TRUE]
If we insert values:
 T T then our assertion P->Q is T
 T F then our assertion P->Q is False
 F T Not Applicable since we can't derive a Q value from a False P!
 F F Not Applicable since we can't derive a Q value from a False P!

For the Biconditional (making our assertion in both directions)
T T T
T F F
F T F
F F Not Applicable since we can't determine if both values are False

Why is Stoll right?????
Comment: He's right because that is in fact how the conditional $\to$ is defined in propositional logic. You may feel that he hasn't given you an adequate explanation of why we define it that way, but that's a separate issue. (And I can assure you that Bob would not have taken kindly to being called a weasel!) In fact I agree that he could have done a better job of giving an intuitive justification of the third line, but his justification of the fourth line is quite reasonable.
Comment: hopefully he's not in the land of the living and can't strangle me - seriously, look at what he says here (pg 163): " We agree that <-> is the strongest connective (that is, it is to encompass most), and then follows ->. Next in order are V and A, which are assigned equal
strength, and then follows -| (me: NOT symbol) the weakest connective." But the Wikipedia says something seemingly different: https://en.wikipedia.org/wiki/Logical_connective#Order_of_precedence AND and OR don't have equal precedence and NOT the weakest connective has the highest precedence!
Comment: It's a good book but there are these patches that startle me (like sudden gunfire)! Plus I'm not calling him a weasel - that's silly, just parts of his logic in the book :)
Comment: He does say: "These five tables are to be understood as definitions; they arc the customary definitions adopted for mathematics. We have made merely a feeble attempt to make them seem plausible on the basis of meaning." which is why i like the book - though I wish he had placed that at the beginning and not the end.,
Comment: Bob died a little over 20 years ago, so I expect that you're safe. :-)
Answer: You would agree, surely, from your experience with arithmetic that the following is true?

If $x=1$, then $x+1 = 2$

But wait, you don't actually know that $x=1$. Maybe $x$ is 2, or seventeen!
The way I like to justify the truth table is by looking at how we can use truth values to make inferences. Here are some exercises to try given Stoll's values for the truth table, and again for any other definition you choose.

1. Suppose you know that $A \to B$ is true.

Can $A$ be false?
Can $B$ be false?

If your answer to both of these questions is "no", then what you have in mind is "A and B", not "if A then B".
2. Suppose you know that $A \to B$ is true. Suppose you also know that $B$ is true. Can $A$ be false?
If your answer to this question is "no", then you have the conditional backwards: you have in mind "if B then A", or equivalently "A if B".
3. Suppose you know that $A \to B$ is true. Suppose you also know that $A$ is true. Can $B$ be false?

The answers "yes and yes, yes, no" collectively determine that the truth table must be of the form Stoll describes.
Comment: umm.. there's no maybe x = 2 because the equality won't be satisfied - so I don't follow that. If A->B is true then A and B CANNOT be false and I can't even begin to grasp what you are implying about "A and B".. sorry..
Comment: @paleywiener: It's okay if $x=1$ isn't satisfied; a lot of the time $x$ really is not one! But those times when $x$ is one, we know that $x+1$ will be $2$: that's what the conditional expresses.
Answer: As a comment ( don't have enough points yet), maybe this would help:
http://en.wikipedia.org/wiki/Material_conditional
Answer: A common assumption goes that we can determine the truth value of a compound statement from atomic components.  In other words, if we input truth values for its components, then we will get a truth value for the compound statement.  For example, if we have some binary connective X and we input truth values for "p" and "q" in (pXq), we will get some truth value for (pXq).  Additionally, the other common assumption goes that we have a constant, fixed truth set for both atomic statements and compound statements.  Since we assume that we only have two truth values, this means all compound statements will take on some truth value in {true, false}.  Without these assumptions, you end up studying something different than what Stoll is talking about.
Now, given the above assumptions what are "<->" and "->".  Well, if "(p<->q)" holds true, then "p" and "q" have the same truth value, and if "p" and "q" have the same truth value, then (p<->q) holds true.  Consequently, if p holds true, and so does q, then (p<->q) holds true.  If p is false, and q is true, then (p<->q) is false.  If p is true, and q is false, then (p<->q) is false.  If p is false, and q is false, then (p<->q) is true.  Thus, what Stoll has <-> makes sense.
Now, you've agreed that if p is true, and q is true, then (p->q) is true.  Also, you've agreed that if p is true, and q is false, then (p->q) is false.  Consequently, we have four possibilities for ->.
1:
 A  f  t
 f  f  f
 t  f  t

2:
 B  f  t
 f  f  t
 t  f  t

3:
 C  f  t
 f  t  f
 t  f  t

4:
 D  f  t
 f  t  t
 t  f  t

Now 3 is <->.  So, it can't be ->, since we already think these distinct.  1 is logical conjunction.  So, similarly we can reason that it can't be ->.  Could -> be 2?  Well, if it did work out that way, then (p->p) would NOT be a tautology.  So, if you want (p->p) as a tautology, then -> cannot be 2.  This leaves us with -> as 4 or operation D.
Comment: Your para-1 is in essence saying that my remark about things being "Not Applicable" is wrong: it's a "composite sentence" built from an "atomic/prime-sentence" and it can have only True or False values and must take a value. I agree!
Comment: Now, considering the truth-table for (IFF) <-> , given that I have to insert a True or False value in place of "Not Applicable" what should it be - True or False. Should it be F F F or F F T. I dunno.. flip a coin? Perhaps that's what he did and then adjusted "Conditional" to match! I don't understand your para-2.. "Well, if "(p<->q)" holds true, then "p" and "q" have the same truth value" -- why should they have the same truth value - don't see how your para-1 results in this conclusion.
Comment: @paleywiener Stoll didn't just flip a coin.  Every single logician agrees with the truth table for these two connectives if we have only 2 truth values.  Iff p, thenn q, means that "if p, then q" holds true and "if q, then p" also holds true.  Suppose p true.  By modus ponens (or detachment) and "if p, then q" as true, q holds true also.  Suppose p not true.  Then p qualifies as false.  But, since "if q, then p" holds true, by modus tollens q is also not true, and thus false.  So, q always has the same truth value as p if we have "iff p, thenn q".
Comment: ah! thank you! https://en.wikipedia.org/wiki/Modus_ponens


In regression, which distribution will have the largest standard deviation?

Question:
the predicted scores on the outcome variable, Ŷ
the residuals
the observed scores on the outcome variable, Y
the standardized regression coefficients

My understanding is that the question wants to see which of these regression distributions has the greatest spread.
My first approach was to try and order these options on a spectrum of lowest to highest standard deviation. I think observed scores would have greater standard deviation versus predicted scores, as regression tries to minimize the residuals. I have no idea how to compare the other two distributions though. (It may have to do with the formulas for these, but I find them very confusing!)
What do you think?
Comment: You are right to be concerned: the question is unanswerable because the standardized regression coefficients are unitless and therefore (in general) it makes no sense to compare them to the outcome variable. Consequently trying to compare their variances is equally nonsensical.
Answer: Without more information, I don't believe you can actually order these four.  Fortunately, the question only asks you which is largest; which is, e.g., second largest is not required.  Let's see if some hints will help you determine which must be largest, and why:

Consider that if $X$ and $Y$ are perfectly uncorrelated, not only in the population, but also in your sample, then the SD of the residuals will be identical to the SD of $Y$.  I suppose the question is assuming that $X$ and $Y$ are not perfectly uncorrelated in your sample (which would be incredibly unlikely), even if they are in the population.  In that case what would be the ordinal relationship between them?
Next, how are the observed scores, $y_i$, related to the predicted scores, $\hat y_i$, and the residuals, $\hat e_i$?  (This can be inferred from the full regression equation, or from the equation that lets you calculate the residuals given the fitted model, for example.)  Given the way these three are related, which must have the largest SD?
The SD of the standardized regression coefficient is a little trickier.  How is the standard error of the estimated coefficient related to the standard deviation of the residuals?  Given what you had figured out in #1 & 2, what does this imply?


How can a page in IE render differently between Cassini and IIS7?

Question: I am completely confused - I have a website that renders perfectly in IE8 when run through Cassini (in Visual Studio) but has several messed up elements (style/look) when deployed to localhost and viewed through the same browser (IE8).
I have run Beyond Compare 3 on the html and CSS files and they are exactly the same. Are there any circumstances where IIS7 could be somehow sending extra/different information to the browser? Has anyone run across something like this before?
Note that Chrome and Firefox both render the same webpage just fine through Cassini and IIS7.
(Update)
What Browser Mode and Document Mode does IE8 Developer Tools think you are in if you press F12?
When running from Cassini (http://localhost:22120), IE8 stays in IE8 mode (with the option for turning on IE7 compatibility view) and everything looks great.
When running from IIS7 (http://{machine name}), IE8 automatically goes into in IE8 Compat View, IE7 standards and things look horrible.
Comment: Have you Beyond Compared the results of a "File | Save As..." MHT file to see what is actually different?
Comment: Also, what Browser Mode and Document Mode does IE8 Developer Tools think you are in if you press F12?
Comment: Best question in Stack Overflow. Ever. =)
Answer: My assumption (as mentioned in my comment earlier) was that IE is working in a different rendering mode, depending on whether you are using IIS or Cassini, and this is causing the layout differences.  It actually appears to be IE that is causing this, based on the settings found in Tools | Compatibility View Settings.  There are two check boxes:
Display intranet sites in Compatibility View - this is checked by default.
Display all websites in Compatibility View - this is not.
Either way, you should use the standard meta tag to force the mode you wish to be rendered in.
<meta http-equiv="X-UA-Compatible" content="IE=8" />

Hope this helps.
Comment: This is the answer.  "http://localhost" is special-cased to be treated like Internet-zone content, while (by default) http://machinename is treated like Intranet-zone content.
Comment: A little bit of extra info which I found was required to fix my problem: when run in intranet mode, if not specified otherwise, IE defaults to "IE=EumulateIE7" mode. Whereas the default for the internet zone is "IE=8" mode. Since my site was working fine on the intranet, I had to use "IE=7". (IE=EmulateIE7 would have also worked, but under some circumstances this can wind up rendering in IE5 mode, which is not exactly desirable)
Comment: 3.5 years later, this helped me out as well!
Answer: I think the best solution I have found is not far from Paul's one but it tells the browser to use your Internet Explorer version which solved other problems I have with content="IE=8".
Here it is:
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

Comment: This seems to be the same for IE8 and IE.  I tried your suggestion and it fixed it for both I8 and IE9.  Thanks.
Answer: Actually I had the same issue. IE8 has a compatability settings dialog under tools menu. There is a check box which indicates "Display intranet sites in compatability mode".
And not that IE7 compatability mode is not the same as using ie7, there are some differences.
Answer: One side note to this issue:
if the same page renders differently on different servers but in the same IE8 browser, check your url - IE8 automatically displays in compatibility mode if the domain is not fully qualified.
Answer: If the page content is the same then compare the headers that the servers are sending with the page.
After kicking this around a bit I though about compatibility mode. Try manually forcing IE8 to render the page in compatibility mod. If the render doesn't change then you know that the issue is because IE is rendering that page in compatibility mode when reading it from that web server.
If the latter is the case look into http://msdn.microsoft.com/en-us/library/dd567845%28VS.85%29.aspx
Comment: This pretty much nails it, because *something* has to be different.  It's got to be the content or the header.


How can I 'clean' up my bass fretting?

Question: I find if I'm playing faster riffs - say Hysteria by Muse - I sometimes find that I hear a clunking, metallic sound as I fret. That is, the string hitting the fret. So if I fret at the 7th and then play open repeatedly, I hear the sound of the string hitting the metal bar of the fret.
It's not that I'm fretting on the actual fret, but more the speed of the changes means that I get the metallic sound on string-on-fret.
How can I avoid this, bar learning to play fretless? (Which I really want to do, if I could afford another bass)
Comment: Not a complete answer since I haven't verified this, but you might try using some EQ to fix this. It might be possible to notch out the fret noises at least somewhat by reducing the frequencies where the fret noises are happening. It would likely change your sound a bit, though, particularly if you like a lot of high-end in your bass tone.
Answer: When you fret a note make sure that your finger is as close to the edge of the fret as possible; literally right next to it; this will instantly give you a cleaner sound; the closer to the metal you get the purer the note, this applies to all fretted instruments and all styles of playing.  (the edge towards the bridge, not the nut)
Do this consciously until you do it automatically; slow down your playing if need be until you have it.
You might want to pay attention to how hard your hitting the notes; only you know how hard you currently hit them though, so I cannot really comment.  Concentrating on the above technique  will definitely help make you a clearer and more accurate player.
Action has been covered so the the other possible thing you could do, is turn up your amp ;)
Answer: Play slower.
If you are clanging and banging around it means you are playing something too fast.
Gotta practice it slower until it gets clean and quiet, THEN get it up to speed.
There might be some gear related issues, but if those are taken into account and you are still clanking away, slow down until you can play it without it.
Answer: From my experience of playing faster bass, I have found changing the action to be the best option. What you want is a high action, so that when you fret the string does not come down and hit the fret as hard, reducing 'clunk.' Remember that you will need to check your intonation when you have changed the action, so that the bass stays in tune with itself.
If others disagree, then I'm cool with that, but I personally found this helped my playing quite a bit. Hope this helps :)
Comment: The rule of thumb I've always gone by is that lower action => fast, higher action => more precision.
Comment: Wouldn't a higher action necessitate faster motions with your fretting hand, increasing the sound?

How can I 'clean' up my bass fretting?


How to create independent sections, which consits of menu and more pages automatically

Question: I have little problem with creating independent sections on the web.
I have content type named project. It is basically landing page, which has own menu and this menu can link multiple simple pages. These projects have simillar structure, on every on them is page like timeline, news & events... Now when I want to create new project, I need to create new project, than create multiple simple pages, create menu, add menu to this project and so on. It is really complicated. Is there any way how can this be automatized?
Example: I will create new project, and menu and simple pages will be created automatically.
Answer: Try with field collection module and divide groups of fields in sections as explained in field collection module documentation. You will get what you want!


Change height of CKEditor (per profile) without using WYSIWYG Module

Question: Problem
How can I change the height of the CKEditor window without using the solution outlined here which requires the WYSIWYG module. I can't spot where the height is defined in the CK module.
Ideally I'd like to be able to set it per profile and I'd prefer not to add an extra module if possible.
Has anyone dealt with this before?
Comment: Do you want a different height per profile (so each user has a different height) or per role?
Comment: @FelixEve Either per user role, or just per CKEditor profile type (So full is a different height from filtered). At the moment I've just been switching it with firebug, but it's not really an option for everyone else.
Comment: How you installed CKEditor in the first place? Custom code, some module other than WYSIWYG module? Or maybe some hack at the theme level (I know, sounds weird, but seen that once)?
Answer: UPDATE:
The patch in this thread on DO fixes this issue.

Looking at the ckeditor demo on this page it is possible to change the height of the editor with css alone.
The div .cke_contents has an element style setting the height to 300px, however a rule in the stylesheet marked as important would overrule this.
So, if you can add the roles of the user as a classes of say the body, then you could include:
<code>.role1 .cke_contents {
    height: 400px !important;
}
.role2 .cke_contents {
    height: 100px !important;
}
</code>
Alternatively there may be a class added by the CKEditor profile type that you could use.


how to use Peer-To-Peer networking to minimize internet bandwidth?

Question: I am trying to build a networking solution to the following problem:
I have several stores running PCs which need to be frequently updated with new content (primarily video files ~40Mb).  I want to put the new content on a central server and have the PCs pull down the files.  I can write services to run on the PCs that will take care of contacting the server and downloading the content.  But, I have to find a way to minimize the total bandwidth used.  The PCs are connected to the internet but not on a domain, they are mostly Windows 7 Home/Premium editions.
If each PC connected only to the central server I would not be taking advantage of the fact that the neighboring PC (within the same store, on the same router) may already have the new files.  Ideally, that PC would be able to discover this and rather than getting the files from the central server it would get them from its neighbor.  The files are not secure and speed is only a minor concern.
At first though a Peer-To-Peer service would be at the heart of this solution.  But, I don't know anything about Peer-To-Peer application development or where to start.
If you have any ideas of where to start with such a solution or any thoughts on how I could solve this problem I'd love to hear it!
Thank You, Jesse D.
Answer: Don't try to develop your own thing, just set up a (private) bittorrent tracker on your central server and point all the PCs to it to download the update.
You may even be able to use Murder, developed by Twitter for the very purpose of distributing updates to numerous machines.
Comment: would to solve the root problem which is to minimize internet bandwidth used?  In other words, would the PC connect to its neighbor within the LAN or would it go out and back in?  Thanks.


Getting Illegal invocation error while using Jquery

Question: I am getting the below error while trying to use ajax call in Jquery. I am explaining my code below.
Error: Uncaught TypeError: Illegal invocation
    at e (http://oditek.in/fyndspace/js/jquery.js:4:23990)
    at Vc (http://oditek.in/fyndspace/js/jquery.js:4:23875)
    at Vc (http://oditek.in/fyndspace/js/jquery.js:4:23898)
    at Function.m.param (http://oditek.in/fyndspace/js/jquery.js:4:24236)
    at Function.ajax (http://oditek.in/fyndspace/js/jquery.js:4:20195)
    at Function.m.(anonymous function) [as post] (http://oditek.in/fyndspace/js/jquery.js:4:22297)
    at saveAllManageSpaceData (http://oditek.in/fyndspace/listyourspace:1418:6)
    at HTMLButtonElement.onclick (http://oditek.in/fyndspace/listyourspace:693:102)

My working code is given below
<button class="btn nextbtnbgdiv open6" type="button" onclick="saveAllManageSpaceData();">Save & Continue </button>

var data={"city":city,"area":area,"list_name":list_name,"file_data":file_data,"stDate":stDate,"endDate":endDate,"address":address,"latitude":latitude,"longitude":longitude,"description":description,"tag_google_map":tag_google_map,"space_area":space_area,"space_status":space_status,"price":price,"sPrice":sPrice,"price_type":price_type,"booth_size":booth_size,"height":height,"width":width,"spaceAccess":spaceAccess,"rules":rules,"Overview":Overview,"depositeForLoss":depositeForLoss,"dkeyAccess":dkeyAccess};
console.log('hello',data);
var url="common.php?action=saveManageSpace";
$.post(url,data,function(data){
    console.log('res',data);
});

Here I am getting the above  error while using ajax call. Please help me to resolve this issue.
Comment: Show the click event handler and the element you clicked
Comment: @mplungjan : Please check my post again.
Answer: your data is an object - you might want to try as array
 var data=[{"city":city,"area":area,"list_name":list_name,"file_data":file_data,"stDate":stDate,"endDate":endDate,"address":address,"latitude":latitude,"longitude":longitude,"description":description,"tag_google_map":tag_google_map,"space_area":space_area,"space_status":space_status,"price":price,"sPrice":sPrice,"price_type":price_type,"booth_size":booth_size,"height":height,"width":width,"spaceAccess":spaceAccess,"rules":rules,"Overview":Overview,"depositeForLoss":depositeForLoss,"dkeyAccess":dkeyAccess}];


How do I apply weights to a Cox Regression Model in R?

Question: I am trying to answer the question of whether service in a certain organization has an effect on age of first marriage, and am interested in using the Cox model
to understand the difference in the hazard rates.
Because I have observational data, I'm using a pre-processing technique to achieve covariate balance between the two groups (to account for selection bias), and then trying to estimate the treatment effect of service. Using the WeightIt package, each observation is given a weight, and I would now like to add these to the observations when conducting the Cox regression.
I was introduced to the coxphw package, but am unsure if I am putting the weights in the correct place. Currently, I am putting them in caseweights, where W1 is the object from the WeightIt package.
<code>fit1 <- coxphw(Surv(time1mar, censor) ~ milserve,
               data = com,
               template = "ARE",
               caseweights=get.w(W1))
</code>
Thanks for the help!
Answer: Well, folks, I e-mailed the writer of the program, and he confirmed that any weights generated should be specified under the caseweights option.
Cheers!
Comment: Thank you for following up! And I'm glad you're finding WeightIt useful!
Comment: @MohamedRahouma W1 is generated from the WeightIt package.
Comment: @Ryan Thanks for sharing your experience. Upvoted. Would it be possible how you got `W1. Appreciate your input.
Comment: @Ryan Thx for your answer. Upvoted.


Who Bowled the Fastest Ball in Cricket till now?

Question: Who bowled the fastest ball in cricket? I got to know that Shoaib Akhtar is not the right answer there is someone else who bowled a faster ball than him.
Answer: Guinness World Records lists Akhtar as the bowler of the fastest ball of all time:

The highest electronically measured speed for a ball bowled by any bowler is 161.3 km/h (100.23 mph) by Shoaib Akhtar (Pakistan) against England on 22 February 2003 in a World Cup match at Newlands, Cape Town, South Africa.

The rest of the quote from that page is very significant though:

Quote from World Cup communications director: "ICC has always said there is not enough uniformity in the various speed guns around the world for any one performance to be designated official". However many believe this to have been the fastest ball bowled.

i.e. you cannot compare measurements from different matches against one another, due to systematic differences between the equipment used. There are claims that Mohammad Sami bowled balls at both 164 km/h and 162.3 km/h; the 164 km/h ball was ruled out due to "faulty speed measurements on the speed meter", but there is no clear explanation available as to why the 162.3 km/h ball was ruled out.
TL;DR: nobody actually knows because there isn't an accurate means of measuring.
Answer: There is no perfect,actual or true equipment which can measure the speed of ball correct or accurately in all environment.
While the fastest speed ball bowl by PAKISTANI cricketer player "Shoaib Akhter" with the speed of 161.3km/h.
During the World Cup  group A match between "Pakistan " and "England" at "Newlands stadium, Cape Town, South Africa", 22 feb 2003 .
Second fastest ball was bowl by AUSTRALIAN cricketer "Shaun Tait", during the 5th ODI at "Lord's" cricket ground , "London",3 jul 2010 with the speed of 161.1km/h.
so there is slightly speed difference but still Shoaib Akhter is fastest bowler in cricket history.


MVC tracking fields such as Author and Editor (Created By and Modified By)

Question: I'm looking for the best way to track the Author and Editor fields for all the entities in my database.
I started by creating a base model which all my models inherit from:
public class DatabaseEntity
{
    [Key]
    public int Id { get; set; }

    [Display(Name = "Last Modified By")]
    public ApplicationUser Editor { get; set; }

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
    [Display(Name = "Last Modified")]
    public DateTime LastModified { get; set; }

    [Display(Name = "Created By")]
    public ApplicationUser Creator { get; set; }

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime Created { get; set; }
}

This works good, but I have to set these fields in every action in my controllers. How can I set these fields every time an item in my database is updated or edited? I am aware that I could override Add in my DbContext, but I have no idea how to get the ApplicationUser from the HttpContext.Current.User.Identity in my DbContext. I have tried:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> {
    private readonly UserManager<ApplicationUser> userManager;
    private readonly HttpContext httpContext;

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, UserManager<ApplicationUser> userManager, IHttpContextAccessor contextAccessor)
    : base(options)
    {
        this.contextAccessor = contextAccessor;
        this.httpContext = contextAccessor.HttpContext;
        this.userManager = userManager;
    }

    public override EntityEntry<TEntity> Add<TEntity>(TEntity entity)
    {
        DatabaseEntity dbEntity = (entity as DatabaseEntity);
        if (dbEntity != null)
        {
            dbEntity.Created = DateTime.Now;
            dbEntity.Creator = await userManager.GetUserAsync(httpContext.User);
        }

        return base.Add(entity);
    }
}

but this gives error because userManager.GetUserAsync(httpContext.User); requires an await and public override EntityEntry<TEntity> Add<TEntity>(TEntity entity) is not async.
Answer: For getting current user, you should not use UserManager<ApplicationUser>. With commenting dbEntity.Creator = await userManager.GetUserAsync(httpContext.User);, you will get error A circular dependency was detected for the service of type 'CoreDb.Data.ApplicationDbContext'. due to that you accessing UserManager<ApplicationUser> in ApplicationDbContext.
I suggest you try get the current user by querying DbSet<ApplicationUser> with current user name.
Here is a simple code:
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    private readonly HttpContext httpContext;

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor contextAccessor)
        : base(options)
    {
        this.httpContext = contextAccessor.HttpContext;
    }
    public DbSet<ApplicationUser> ApplicationUser { get; set; }
    public override EntityEntry<TEntity> Add<TEntity>(TEntity entity)
    {
        DatabaseEntity dbEntity = (entity as DatabaseEntity);
        var userName = httpContext.User.Identity.Name;
        if (dbEntity != null)
        {
            dbEntity.Created = DateTime.Now;
            dbEntity.Creator = userName == null ? null : ApplicationUser.Where(user => user.UserName == userName).FirstOrDefault();
        }
        return base.Add(entity);
    }
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }
}

Comment: As soon as I get home today I will give this a try. It looks like it should work.


Understanding on concept of IAM role on EC2

Question: I'm just getting in touch with EC2 and came across the IAM Role concept. This question is to clear my doubt about the concept on restriction level.
Lets say I have an EC2 instance with attached IAM Role Role A which posses one policy AmazonS3ReadOnlyAccess, correct me if i'm wrong but it means this particular instance only allow to perform S3 Read only operation.
Now says I created a User with Programmatic access and AmazonS3FullAccess policy.
If this user SSH into the EC2 instance, can he write file to s3 ?
I still unable to try it out by myself as I don't have a linux machine and still figuring on how to connect to Ec2 using putty
Comment: If you want to connect to EC2 linux machine http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/putty.html
Answer:
Lets say I have an EC2 instance with attached IAM Role Role A which
  posses one policy AmazonS3ReadOnlyAccess, correct me if i'm wrong but
  it means this particular instance only allow to perform S3 Read only
  operation.

Yes

Now says I created a User with Programmatic access and
  AmazonS3FullAccess policy. If this user SSH into the EC2 instance, can
  he write file to s3 ?

IAM users cannot SSH to EC2 instances using IAM user credentials. After provisioning a EC2 instance, you need to use regular Operating System User constructs, to SSH to the Server (Default user keys created by AWS).
In addition if a user SSH to EC2 instance and use a Programatic Access Credentials of a EC2 User through AWS CLI, REST API or SDKs (Doesn't have to be a EC2 instance, it also can be your on-premise server) then if the IAM User has a S3 write policy, the CLI commands or API calls or the code using SDK is able to write files to S3.
So in a summary

Use IAM roles if you are running a EC2 instance, for your CLI commands, Code with SDK, or REST API calls to access AWS Resources.
If you are using a server on-premise or outside AWS, use IAM User's Programatic Access keys to do the same.

Insight on how IAM roles work internally with EC2

When you attach a IAM role to a EC2 instance, AWS periodically updates the EC2 instance with temporal Access Credentials to that EC2 instance (Which is a good security practice).
These credentials are accessible through the Metadata URLs for the CLI, REST API and Code using SDKs inside EC2 instance.

Note: When using Roles, its much secure since it uses Temporal access credentials vs IAM Users Programatic Access uses Long lived access credentials.
Comment: so is it means that after this user accessed `EC2` via `AWS CLI`, `AWS` will   value the policy of the user more despite the fact that this user is on this particular EC2 instance that only has a read access
Comment: When you say "This user accessed" means OS user in EC2 or IAM user? Note: Only OS user SSH to the EC2 instance. When the OS user SSH to the EC2 instance, if there is a Role attached to the EC2 instance, all the CLI commands uses that role to access resources such as S3. So for this operation IAM User is not required (Only IAM role is sufficient). Check the answer summary at the end.
Comment: My scenario is, I will first using OS user SSH to EC2 instance and configure a user profile for the user I've created.
Comment: Is the answer clear @Mr.SuicideSheep? I just updated the answer with insights for more clarifications.
Comment: According to your answer **then if the IAM User has a S3 write policy, the CLI commands or API calls or the code using SDK is able to write files to S3.** which means will ignore the role policy that attached to this EC2 instance?
Comment: Yes, if you configure your EC2 instance to use a IAM user's credentials for CLI, SDK or REST API (Don't do it, use a Role which is better, as mentioned in the answer) then it will use its policy. Use a Role policy instead.


Character guessing gaming in C language using 1D array and for loop

Question: I intend to skip a particular character using "continue statement" if an iteration("i==[index]"). I want to skip the character at index 5.
Please below is the code. Am a newbie though.
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char guess[10]="Programmer";
    char choice;
    printf("Welcome to my guessing game\n");
    printf("===============================\n");
    int i;
    for(i=0;i<10;i++)
    {
         printf("%c", guess[i]);
          if(i==guess[5])
            continue;
    }

    printf("\n\n");
    printf("Guess which letter is missing\n");
    scanf(" %c",&choice);

    if(choice==guess[5])
    {
        printf("Excellent! Good point");
    }else
    {
       printf("Ooops! Wrong answer\n");
    }

    return 0;
}

Comment: Remove the `continue` which at the end of the code block does nothing. Change to `if(i != 5) printf("%c", guess[i]);`
Comment: `char guess[10]="Programmer";` ==> `char guess[]="Programmer";` Just saying. `Programmer` is an *eleven* octet sequence when you include the terminator. I'm not really sure what you think `i==guess[5]` is supposed to be doing. Comparing your enumeration variable `i` against the *content* in `guess[5]` doesn't really sound right, does it? Even if that were addressed, the `continue` seems wrong anyway. You're about to loop anyway, so.. continue to *what* ? I think this needs self-explanation, because that test+continue should be *before* the print.
Comment: You should just say `if (i == 5)` if you want to skip that index. But you need to do it *before* you print.
Comment: @WhozCraig Since he never uses `guess` as a string, the terminator is not needed.
Comment: @WhozCraig in this case it is not a string, but an array of 10 characters. There's no fault there.
Comment: @WeatherVane I agree.  Putting a continue in this block doesn't make much sense.  It is so simple the   i != 5 is the best solution.
Comment: @WeatherVane nowhere in my comment did I claim there was a fault. I claimed that initializing an array of 10 from an array of 11 is going miss something (the terminator). That's all, and that can be rectified by letting the compiler do the sizing for you.
Comment: @WhozCraig but you are: *that can be **rectified**.* There is nothing to rectify, as Barmar commented too.
Answer: Here is the fix:
Also updated the array size as stated above (It isn't treated as string anywhere, but better safe than sorry).
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char guess[12]="Programmer";
    char choice;
    printf("Welcome to my guessing game\n");
    printf("===============================\n");
    int i;
    for(i=0;i<10;i++)
    {
        if( i != 5 )
        {
            printf("%c", guess[i]);
        }
    }

    printf("\n\n");
    printf("Guess which letter is missing\n");
    scanf(" %c",&choice);

    if(choice==guess[5])
    {
        printf("Excellent! Good point");
    }else
    {
       printf("Ooops! Wrong answer\n");
    }

    return 0;
}

Here is the output:
Answer: first of all you need to write continue statement before instruction that you want to skip. Do you want to skip every character which is the same in guess[5] or do you want to skip index 5?
If you to skip all letters which is the same to the letter at index 5:
for(i=0;i<10;i++)
{
    if(guess[i]==guess[5]) continue;
    printf("%c", guess[i]);
}

If you want to skip only letter at index 5 try:
for(i=0;i<10;i++)
{
    if(i==5) continue;
    printf("%c", guess[i]);
}

Answer: You shouldn't be comparing with an element of the array, just compare with the index you want to skip.
And you need to put the continue before the statements you want to skip. Otherwise the letter has already been printed and continue does nothing useful.
    for(i=0;i<10;i++)
    {
        if(i==5) {
            continue;
        }
        printf("%c", guess[i]);
    }


Database ETL Design Question

Question: A dataset I receive for routine refresh purposes contains a date field that's actually VARCHAR.
As this will be an indexed/searched field, I'm left with...
1) Converting the field to DATETIME and validating and normalizing the data values when refreshing
or...
2) Leaving the data as-is and forming my queries to accommodate various valid date formats, i.e.,
WHERE DateField = 'CCYYMMDD' OR DateField = 'MM/DD/CCYY' OR ....
The refresh would be on a monthly basis; "cleaning" the data would add about 35% time to the ETL cycle. My queries on the date field would all be equalities; I do not need to range search.
Also, I'm a one man shop, so the more hands-off the overall solution the better.
So which scenario am I better off doing? All opinions appreciated.
Answer: I think this is a great question.  Here's my opinion:
I'm a big believer in the idea that in the long run you'll save more time and have fewer headaches by using data types for the purpose for which they were intended.  That means dates in date fields, characters in character fields, etc.  If you go with option 2 you'll need to remember to code for all the various possible date formats every time you query the table.  If you set this down and come back a year from now, are you going to remember?
By contrast, if you use a date field and do the upfront work in the ETL process of dealing with the dates properly, you will always know just how to interact with the field.  And I'm not even going into performance implications.
And in this case, I'm not sure you'll even see a short-term benefit.  If there are, for example 5 different possible date formats in the source data, you'll need to account for those one way or another; either in the ETL or in the output queries.  The code to transform those 5 formats in ETL is not materially more complicated than the code to manage those 5 formats in the output queries.
And if the data could literally arrive in an infinite number of formats, you have big problems either way.  Either your ETL will break or your queries will break.  It is, to a certain extent, an irreducible complexity.
I would suggest that you take the time to code the proper transforms into your ETL.  But do yourself a favor and code a preprocessing step that identifies dates in formats that won't properly transform and alerts you to them.  If you see patterns; i.e., if any format shows up more than once, code a transform for it.  Over time you'll be left manually cleaning fewer and fewer of those nasty dates.  With luck, your 35% will drop to 5% or less.
Good luck!
Answer: You are better off cleaning the data. First dates which are not good dates are meaningless so it's pointless to store them. Second, it is harder to fix a bad datatype choice later than it is to never make it. Querying will not only be easier but it will be faster than if you use a varchar. And things like ordering will work correctly as well as date functions. Third, I can't imagine that cleaning this would add that much to your import, I clean data all the time without it being a problem. But if it does, then clean the data in a staging table that no other process is using (so you aren't affecting users on prod) and then do the load to the prod tables from nice clean data.
Answer: Clean the data up front and store the dates as dates.
I work with systems that store dates as strings and there appear to be an unlimited number of ways to store the dates. This makes it very difficult to create a query to will work against a future new date format.
If you store dates as strings then you should apply constraints to make sure the data is stored in the proper format. Or, just convert the date strings to dates and let the database apply the valid date constraint itself. It is usually best to let the database do the work for you.
Answer: Definitely better off cleaning the data and loading into date column as this will ensure the integrity.

Database ETL Design Question


Problema na renderização da imagem

Question: A imagem tá toda "pixelada" não fica como deveria, o que pode ser?
A imagem original tem ótima resolução e o tamanho dela tá 1200x1200, diminuir o tamanho dela também não mudou o resultado
No CSS estou usando
width: 40px; height: 40px;

E no HTML

A imagem fica assim nos navegadores
Comment: Está dando esse problemas em todos os Browsers? Já considerou transformar o .png em .svg?
Comment: Não era pra acontecer isso não. Talvez seja o formato ou a codificação da imagem. Se puder disponibilizar a imagem original para download para ser analisada seria bom.
Answer: Ao comprimir a imagem, ela irá perder qualidade, mesmo que seja boa, isso acontece em todos os formatos que usam pixels, exemplo bmp, jpeg, png...
Pois esse tipo de construção só trabalha bem em determinadas distancias e tamanhos, dependendo da compressão, o browser não irá conseguir calcular as curvas e os pixels irão ficar expostos, exemplo...

A solução perfeita é usar vetores, pois eles são interpretados pelos browsers como elementos visuais matemáticos, então sempre irão se manter intactos nas bordas.
É possível criar vetores a partir de programas avançados como CoreDraw e Illustrator, mas o que uso e recomendo é a criação/edição de vetores com Vectr, pois além de ser grátis e online é fácil de usar...
Comment: Passei pra svg, e resolveu no chrome mas no IE tá o mesmo problema
Comment: Como assim o mesmo problema? ele exibe pixelado? já tentou setar as dimensões do svg no css/html? vale lembrar que é suportado até a versão 9 do IE https://caniuse.com/#feat=svg
Answer: Isso acontece ao redimensionar a imagem.
Sugiro editar sua imagem e salvar já na resolução que irá usá-la.
Se de todo modo ainda não ficar da forma ideal, o melhor a se fazer é desenhá-la novamente já nesse tamanho que irá utilizar, assim não perderá nenhuma informação.
Answer: Imagens circulares costumam ter esse problema quando comprimidas, Principalmente pelo fato de não existir "meio pixel". Observe as imagens abaixo.

Imagens em painéis de alta densidade de pixel, como o painel Retina da Apple

Os Browser não renderizam imagens tão bem quanto o Photoshop por exemplo. Então as vezes no Photoshop fica bom, mas o algorítimo do Browser pode não ter o mesmo resultado comprimindo imagens.
Muito provavelmente se sua imagem fosse um quadrado com linhas restas você não teria esse problema de forma tão acentuada.
O ideal seria tratar a imagem em algum software feito para isso. Ou transformar em .SVG. Tratar esse tipo de coisa no browser para mim é gambiarra. Apesar disso você pode tenar usar a classe image-rendering: crisp-edges; na imagem.
img {
  image-rendering: crisp-edges;
}

Aqui tem documentação sobre a classe: https://developer.mozilla.org/pt-BR/docs/Web/CSS/image-rendering
Apesar disso veja como mesmo com ela a image-rendering: pixelated; renderização nos Browser é diferente.

Chrome:

Safari:

FireFox Quantum:

Você também pode tratar a imagem com JavaScript dentro de um canvas, como nesse exemplo:
Para testar onde estiver False coloque True no script

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var textarea = document.getElementById('code');
var reset = document.getElementById('reset');
var edit = document.getElementById('edit');
var code = textarea.value;

function drawCanvas() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  eval(textarea.value);
}

reset.addEventListener('click', function() {
  textarea.value = code;
  drawCanvas();
});

edit.addEventListener('click', function() {
  textarea.focus();
})

textarea.addEventListener('input', drawCanvas);
window.addEventListener('load', drawCanvas);
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>

  <input id="edit" type="button" value="Edit" />
  <input id="reset" type="button" value="Reset" />

<textarea id="code" class="playable-code" style="height:140px;">
var img = new Image();
img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png';
img.onload = function() {
 ctx.mozImageSmoothingEnabled = false;
 ctx.webkitImageSmoothingEnabled = false;
 ctx.msImageSmoothingEnabled = false;
 ctx.imageSmoothingEnabled = false;
 ctx.drawImage(img, 0, 0, 400, 200);
};</textarea>

Fonte: https://developer.mozilla.org/pt-BR/docs/Web/API/CanvasRenderingContext2D/imageSmoothingEnabled

Problema na renderização da imagem


Bass trumpet vs. valve trombone

Question: Apart from the obvious external form difference, how do a bass trumpet and a valve trombone differ?
Comment: Hi, you could make your question more appealing by inserting a couple photos  and links to description pages. Or better yet, sound samples.
Answer: There are a number of instruments in the pitch class of a trombone and each of them have interesting and unique features.
The Valve trombone bears the most resemblance to a slide trombone because in many cases, the valve section is interchangeable with the slide section to the extent that many of these models are sold with the valve section as an option.  This includes :

Yamaha 354 vs. Yamaha 354V
Bach 16 vs the Bach 16V
King 2B vs. King 2166

The sound of the instrument is actually quite similar, mostly differing in the articulation.  There is actually another instrument that combines both the slide and the valves called a "Superbone".  For a long time, Holton was the only manufacturer but Wessex and Shagerl now have a model in current production.  The demonstration video done by James Morrison is quite excellent. That link in particular will take you to a spot in the video where he demonstrates the advantages of one over the other by playing two licks: one that works well on the valves and one that works well on the slide utilizing both of the mechanisms in isolation and then in tandem.
Bass trumpet, in contrast, has a much more strident sound because they are often made to be the same bore size as a trumpet and share a similar profile.  With a slide/valve trombone, half of the instrument is cylindrical, meaning there is virtually no taper from the leadpipe (the part immediately after the mouthpiece receiver) through the slide tenon (the part that connects the slide/valve section to the bell).  With a bass trumpet, the leadpipe is directly attached to the valve section so there can be more overall conical tubing and the taper of it can be over a greater expanse.  Additionally, the bells are much smaller than on trombones.  The smallest of contemporary valve trombones has a bore size of around .485 and usually have a 7.5" - 9" bell flare.  Compared to models of bass trumpet:

Wessex's bass trumpet is .46" bore with a 6" bell
Bach B166 has a .485" valve bore with 7" bell
Joseph Lidl has a .460" valve bore and a "small" bell
Kanstul 1088 has a .485" valve bore and 7" bell
The Alexander 19 has a .492" valve bore and a 6.2" bell
The Thein "New York" bass trumpet has a valve bore of .512" and a 6" bell

Note however, that not all of these bass trumpets are equal.  Some have 3 valves, others have 4. Some are pitched in C and others are pitched in Bb. The C trumpets with 4 valves are more often used for orchestral work and the Bb ones sound more like the typical tenor trombone.  The Kanstul goes even further and is very similar to a valve trombone because it has much more length of conical tubing before the valve section, leaving the portion after the valves similar to the bell section on a tenor trombone.
Finally, a hybrid between the valve trombone and the bass trumpet is often used by marching bands and can be called a "Flugabone" or a "Marching Trombone" depending on the manufacturer. (The terms can be used interchangeably.) Wessex and Kanstul currently have offerings in this category. They are similar in appearance to the now defunct Olds and Blessing "Marching Trombones". Unfortunately, King no longer sells their Flugabone and I can't find a picture of one that isn't from eBay.  These are much more close to valve trombones than are bass trumpets because the valve bore are often the same or larger (the above models all have a .500 or .522 valve section) as well as a larger bell section (the above models all have an 8.5" bell).
Additionally, the amount of tapered tubing is much more similar to a trombone than to the bass trumpet due to the additional length of tubing that occurs between the leadpipe and the valves.  E.g. a flugabone has a smaller distance between the valves and the end of the bell than a bass trumpet. It also has to go from .500 to 8.5". This means the taper is more rapid in the flugabone than it is a bass trumpet, which has a longer distance to get from .485 to 6".
Answer: According to Wikipedia

The bass trumpet is a type of low trumpet which was first developed
  during the 1820s in Germany. It is usually pitched in 8' C or 9' B♭
  today, but is sometimes built in E♭ and is treated as a transposing
  instrument sounding either an octave, a sixth or a ninth lower than
  written, depending on the pitch of the instrument. Having valves and
  the same tubing length, the bass trumpet is quite similar to the valve
  trombone, although the bass trumpet has a harder, more metallic tone.
  Certain modern manufacturers offering 'valve trombones' and 'bass
  trumpets' use the same tubing, valves, and bell, in different
  configurations - in these cases the bass trumpet is virtually
  identical to the valve trombone.

Personally I find that disappointing, as I'd have hoped that "bass" trumpets kept the bore profile of the regular trumpet series, thus differing from the bore profile of trombones.  That's life.
Comment: I don't know which source you got this from, but "Certain modern manufacturers" almost invariably refers to Bach who is notorious for utilizing the same parts across a bevy of instruments. (Such as their slide crooks for small bores, which are literally the same part from the 39, which is an alto trombone, through the 16M).
Comment: @mkingsbu    "WIYF" : wikipedia is your friend

Bass trumpet vs. valve trombone


How to block permissions tab for certain users?

Question: Is there a way to block users who are allowed to edit users roles from seeing the "permissions" tab?
Can this be done without code?
Comment: Would the RoleAssign module do what you're after ? Have a look https://www.drupal.org/project/roleassign and see...
Comment: RoleAssign module was the best answer!  can you put this as an answer please ?
Comment: Well, glad that helped. ;-)
Answer: This cannot be done without code.  If you take a look at user_menu() you'll see that access to both of those pages is determined by the administer permissions permission.
To block access to one but not the other will require you to implement hook_menu_alter() and change which permission is checked for one of those pages.
Answer: Option 1
Use the RoleAssign module for this. Some details from its project page:

RoleAssign specifically allows site administrators to further delegate the task of managing user's roles while withholding the Administer permissions permission.
RoleAssign introduces a new permission called Assign roles. Users with this permission are able to assign selected roles to still other users. Only users with the Administer permissions permission may select which roles are available for assignment through this module.
RoleAssign is ideal for smaller sites with a system administrator and one assistant administrator role that should be reasonably restricted in what it allows. For larger sites with multiple levels of administrators or whenever you need finer-grained control over which role can assign which other role, check out Role Delegation. See #961682: Does the role delegation module supersede this module? for a short discussion of the relative merits of the two modules.

Option 2
Use the Role Delegation for this. Some details from its project page:

This module allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.
For each role, Role Delegation provides a new assign ROLE role permission to allow the assignment of that role.
The module also adds an assign all roles permission. Enabling this permission for a role is a convenient way to allow the assignment of any other role without having to check all the assign ROLE role permissions in the Permissions page.
If an administrator has the administer users permission, a role assignment widget gets displayed in the account creation or editing form, and bulk add/remove role operations become available on the user administration page. Otherwise, if s/he has at least the access user profiles permission, the module adds its own Roles tab to the user profile so that roles can be assigned.

Option 3
Use the Administer Users by Role module for this (only an RC version for D7). Some details from its project page:

This module allows site builders to set up fine-grained permissions for allowing "sub-admin" users to edit and delete other users — more specific than Drupal Core's all-or-nothing 'administer users' permission. It also provides and enforces a 'create users' permission.
Comment: I used Role Assign
Comment: Makes sense in your case. But as so often in Drupal, there are multiple options to GTD, no?
Answer: this code works
function mymodule_menu_alter(&$items){
     $items['admin/people/permissions']['type'] = MENU_CALLBACK;
}
Comment: Perhaps this is what you want, but to be clear, this won't prevent a user from accessing the permissions page, they just won't see the tab.
Comment: you are right, the best answer was the Role Assign module


Attempting to Distribute an Access Application with SQL Server Backend

Question: I am attempting to use a Packaged Solution for my Access 2010 application that has its backend linked to SQL Server. At the moment, I'm using the .accdb file as the frontend, and I would like to distribute my application to some other Windows computers, but the Packaged Solution does not work. I had the package include Access Runtime, so their version of the frontend is running on Runtime and not full Access. However, once the application makes a request to the backend, the application does nothing, as I am not even prompted for the SQL Password as per usual with the full version. I've read on about including a .dsn file in the package can secure the SQL connection (see here), but going through steps of other tutorials to create .dsn files hasn't led to any results. Would anyone know how to correctly generate the .dsn file or if I've done something else wrong at this point?
(And yes, I understanding using Access 2010 in the year 2019 is almost a joke at this point, but I'm doing this for testing purposes. I plan to completely remake the frontend in Angular in the future.)
One other unrelated note... would it be a better idea to have the frontend hosted as a .html file like through the "Publish to Access Services" process? I did read that Access Services was discontinued last year, so would that not be possible?
Edit: This is not a duplicate of "DSN Less Connection (MS Access to SQL2016)" because A) I want to utilize a DSN Connection, not DSN-less and B) I am not using connection strings in my code to hook up with SQL.
Comment: A word of advice, from someone who's been there: don't go to the trouble of using the Access Runtime to distribute an Access app unless you intend it to become the *actual application.*
Comment: Possible duplicate of [DSN Less Connection (MS Access to SQL2016)](https://stackoverflow.com/questions/44729231/dsn-less-connection-ms-access-to-sql2016)
Comment: If you're just doing this for testing, wouldn't it be better to use a full-fledged version of Access?
Comment: Also, it's unclear to me what, if anything, you might learn from this exercise once you start writing an Angular frontend.
Comment: Perhaps it would be more useful in full Access, but I thought it'd be quicker just to include an installer for Access Runtime instead of having the computer download full Access. And for the second comment, I'm testing to see how the backend data requests will work with the SQL Server. Prototyping in Access is quicker and easier to do than in Angular.
Comment: Kinda depends on what your goals are.  If you're distributing this, it's not really "for testing purposes," is it?
Comment: My best guess is you want to make a DSNless connection. Tip: if you don't want to mess with connection strings, using a file DSN also creates a DSNless connection.
Answer: You should be able to just create FILE dsn, link your tables, and then distribute the compiled accDE to each desktop.
However, what SQL odbc source provider did you use? If you use the SQL server ODBC provider, then that is by default installed on each computer.
However, if you linked using Native 11 (or later), then that driver is NOT installed on each workstation by default. So, I HIGH recommend you create a FILE dsn (not a user or system DSN), and link the table using that. (Access will create DSN-less links for you)
And you should NOT be seeing a logon prompt with your application. This suggests you forgot or missed the save password option.
So, I would re-link your tables, creating a new FILE DSN. And if you using the linked table manager, then make sure you check the prompt for new location to force creating of a NEW DSN. If you just re-fresh, then you DO NOT get a chance to click on the save password option during the linking process.
So, what odbc driver are you using? The native 11 or later are better, but they are not installed by default on each workstation. However, CAUTION is required here, since the older sql driver does NOT support the newer datetime2 formats. If you used these newer sql column types, they will be returned as string data types in Access and create a mess of issues.
So, first, I would re-link using a FILE dsn.
Make sure you check the save password during the re-link.
You then compile your accDB into an accDE, and then distribute that. You don't really need to use the package wizard, since once each workstation has the runtime installed, then a simple copy of the accDE to each person's computer will thus work fine. There is NO special connection between your accDE and the package wizard. Once the runtime is installed, then any and all mdb, accDB, and your accDE can simply be clicked on to launch + run. So for testing, you can skip the package wizard, and just copy the accDE to the target machine, click on it, and see if it works.
Edit
The prompt and check box during this process is this:

So you have to check that box to save the password. Note that you ONLY get this dialog WHEN you create a new FILE dsn.
Comment: You NEVER in any circumstances will want to fix code or modify your application due to a datetime2 issue. The steps to fix this in general are you change the datetime2 to a datetime in the sql designer, and then re-link the tables on the access side. If you have to do anything more, or modify code or go on a code witch hunt in your forms then you busting up good code and forms, but are fixing something that will now break when you doo this correctly! That code should work100%. Make sure in access when you flip the linked table into design mode shows a date/time column data type.
Comment: I linked to SQL Server through the "SQL Server Migration Assistant for Access". I see a logon prompt for my full access version, but I don't remember a "save password" option in the migration process. I'm using a Native 10 ODBC driver. Perhaps the migrant assistant is what's got me messed up. I'll try re-linking with a file DSN and I'll report back on that.
Comment: Well, you already have all your linked tables, so that is good and fine. What you have to do is re-link again using the linked table manager in Access. If you [x] (check) the box prompt for new location, then you are able to create a new FILE DSN. The problem you have is you used the native 10, and that is not installed on each machine. And worse, by using native 10, then SSMA will have used the newer data types. So, I would likely consider re-migration, but use the legacy SQL driver, or you be forced to install native 10 on each workstation.
Comment: Well, I do have a Native 10 driver, but I don't remember specifying during the migration to use it. I just went through all the migration steps again, and there was no point where I chose what driver to use.
Comment: Albert, I tried creating a new DSN file through the Linked Table Manager, but the process fails to work. I was able to create a DSN file, but when I hit the "OK" button I am prompted to put my SQL username and password in again. Once I do that, the Select Data Source dialogue box reappears, as if nothing happened. I'm not sure what to do next, but I now understand that part about selecting the SQL driver.
Comment: see my edit and picture in my answer as to where that check box is to save you password. You must select this box.
Comment: The sql migration assistant for Access will choose the newer native drivers based on the sql server version you select, but you BETTER change the field mappings for date time from datetime2 to datetime before you migrate, else you be forced to use the native 11 drivers (the datetime2 columns will appear as text, and that is a HUGE mess to deal with, or you install native 11 drivers on each workstation) You MUST set the mappings in SSMA to datetime if you going to use sql driver as opposed to native 11 drivers. SSMA does not prompt to save passwords, you need to re-link to save passwords.
Comment: Thanks for the help so far. I've re-linked the tables and saved the passwords (it seems the migration process did not have a "save password" option) and saved the document as a .accde file. On the secondary computer, I got a "--ODBC call failed SQL Native 10 driver" error... I'm going to take another look at this on Monday and I'll report back here.
Comment: Did you install the native 10 odbc driver on that other workstation? As I stated, you either link using the standard sql server driver, or if you choose native 10, 11 etc, but then you have to manually install those drivers on each work station. However, as I also pointed out, if you use SSMA, and you ALSO want to use non native drivers, then you have to change the field mapping in SSMA, else it will use datetime2 type columns which are NOT supported with sql driver (but is with native 10, 11 etc.). You also can use SQL table designer to change the column types if you don't want to re-migrate
Comment: And no, SSMA does not change or create accDE file. You can only create those if you are using the package wizard, but that is another issue RATHER far down the road and VERY separate from doing a migration of data tables to SQL server.
Comment: I used the standard SQL driver and it worked this time. Thanks for all the help, Albert! The final process turned out to be 1) use SSMA to migrate and create the tables in SQL, 2) delete all linked tables within Access, 3) relink tables using a created .dsn file with generic SQL driver to the previously created tables, 4) save the file as a .accde and distribute it with Access Runtime.
Comment: You  can also re-link and check the prompt for new location, and that will thus eliminate the need for deleting the tables. Also, beucuase you used SSMA, then you MUST look at and determine that you don't have any datetime2 data types on sql server, since those columns will appear as text columns in access and not datetime in Access. So things will seem to work, but you find tons of date/tme code and fields on forms will not work unless you correct this issue. Anyway, it sounds like  you are up and running.
Comment: Yup, I'm currently working on a solution to the datetime2 problem SSMA created. Thankfully there's only a handful of dates used in my forms to fix.


regex js with multiple conditions. first condition for text not surrounded with html tag(span) and second condition surrounded with curly braces

Question: i am having issue with implement regex on text.
i need to find all matches of text surrounded by curly braces {{ text }} but not surrounded with span tag.
i tried (?<!)(\{(.*?)\})(?!<\/span>) without success.
example:
mr {{name}}

 deliver to {{address}}

from the text above i want to extract only address text.
thanks,
Comment: thanks its working. i need to do it contenteditable input changes. is html parser will be more efficient ? can you give code example.
Comment: its not working in js. i am getting error.
core.js:5845 ERROR SyntaxError: Invalid regular expression: /(?s).*?<\/span>(*SKIP)(*F)|{{(.*?)}}/: Invalid group
    at new RegExp ()
Comment: Perhaps use a dom parser and get the value of the ``. Then use `{{(.+?)}}` and the value will be in the first capturing group https://regex101.com/r/uEzKcV/1
Answer: you can try this regex
(?<!)(?<!{)(\{(.*?)\})}(?!<\/span>)

Comment: i tried your code ant its not working.
1.  deliver to {{address}} - works only if i type enter for new line
2.   deliver to a {{address}} a - not working.
3. deliver to  {{address}}  - not working.
Comment: can you explain more I think you want to extract the only {{address}} ?