tns not resolving correctly through webservice

Question: I realise there are some similar questions on here already but I couldn't see one that matched my problem so I'm afraid I had to ask a new question.
I have a webservice running on a server, which is throwing a ORA-12154: TNS:could not resolve the connect identifier specified" error. However when I log onto the said server i am able to tnsping the entry successfully, and connect to it via sqlplus, but not through the webservice.
If anyone has any suggestions as to things to look for then I would greatly appreciate it.
Cheers
Answer: The webservice can't find tnsnames.ora which usually means that you didn't set up Oracle's environment properly when starting the process. This usually means you didn't source oraenv.sh in the shell script which starts it.
Answer: So your interactive login works - what is different between your interactive login and the user that runs your web service?
Are they the same user? If not then you will need to update some of your configs in order to make the Oracle client files available to the webservice.
Details like Operating System, Oracle Version, etc are always a help.
Answer: Some other things to look at include:

If you're using a service name instead of SID, are you specifying the entire service name?
If you're using the ORACLE_SID environmental variable, check the case (mydb vs MYDB)
Check for a sqlnet.log file
If you're using a username/password@SID connect string, you may need to quote your password if it contains special characters (like an @ symbol).


Use of collation in mongodb $regex

Question: Since v3.4 collations are available for find operations, especially as matches for diacritic characters are concerned. While a find query with a definite value ($eq opeartor or corresponding construct) will match letters and correspondent diacritics, the same is not true if a $regex is used in order to achieve a match on a partial search string (a 'LIKE').
Is there a to make the $regex query use the collation the same way than the $eq query?
consider example collection testcoll:
{ "_id" : ObjectId("586b7a0163aff45945462bea"), "city" : "Antwerpen" },
{ "_id" : ObjectId("586b7a0663aff45945462beb"), "city" : "Antwërpen" }

this query will find both records
db.testcoll.find({city: 'antwerpen'}).collation({"locale" : "en_US", "strength" : 1});

the same query using a regex will not (finds the record with 'Antwerpen' only)
db.testcoll.find({city: /antwe/i}).collation({"locale" : "en_US", "strength" : 1});

Comment: This not supported at the moment https://stackoverflow.com/questions/39160072/mongodb-case-insensitive-index-starts-with-performance-problems
Answer: I face this same issue today and I searched the Internet like crazy trying to find a solution. Didn't find any. So I came up with my on solution, a little frankenstein that worked for me.
I created a function which removes all the special characters from a string and then replaces all the characters that could be special to the equivalent regexp that could be special. In the end I just add a "i" option to cover the capitalize strings in my DB.
export const convertStringToRegexp = (text: string) => {
  let regexp = '';
  const textNormalized = text
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '') // remove all accents
    .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') // remove all regexp reserved char
    .toLowerCase();

  regexp = textNormalized
    .replace(/a/g, '[a,á,à,ä,â,ã]')
    .replace(/e/g, '[e,é,ë,è,ê]')
    .replace(/i/g, '[i,í,ï,ì,î]')
    .replace(/o/g, '[o,ó,ö,ò,õ,ô]')
    .replace(/u/g, '[u,ü,ú,ù,û]')
    .replace(/c/g, '[c,ç]')
    .replace(/n/g, '[n,ñ]')
    .replace(/[ªº°]/g, '[ªº°]');
  return new RegExp(regexp, 'i'); // "i" -> ignore case
};

And in my find() method, I just use this function with $regex option, like this:
db.testcoll.find({city: {$regex: convertStringToRegexp('twerp')} })

/*
Output:
[
  { "_id" : ObjectId("586b7a0163aff45945462bea"), "city" : "Antwerpen" },
  { "_id" : ObjectId("586b7a0663aff45945462beb"), "city" : "Antwërpen" }
]
*/

I also create a .spec.ts file (using Chai) to test this function. Of course you could adapt to Jest.

describe('ConvertStringToRegexp', () => {
  it('should convert all "a" to regexp', () => {
    expect(convertStringToRegexp('TAÁdaáh!')).to.deep.equal(
      /t[a,á,à,ä,â,ã][a,á,à,ä,â,ã]d[a,á,à,ä,â,ã][a,á,à,ä,â,ã]h!/i
    );
  });
  it('should convert all "e" to regexp', () => {
    expect(convertStringToRegexp('MEÉeéh!')).to.deep.equal(
      /m[e,é,ë,è,ê][e,é,ë,è,ê][e,é,ë,è,ê][e,é,ë,è,ê]h!/i
    );
  });
  it('should convert all "i" to regexp', () => {
    expect(convertStringToRegexp('VÍIiishí!')).to.deep.equal(
      /v[i,í,ï,ì,î][i,í,ï,ì,î][i,í,ï,ì,î][i,í,ï,ì,î]sh[i,í,ï,ì,î]!/i
    );
  });
  it('should convert all "o" to regexp', () => {
    expect(convertStringToRegexp('ÓOoóhhhh!!!!')).to.deep.equal(
      /[o,ó,ö,ò,õ,ô][o,ó,ö,ò,õ,ô][o,ó,ö,ò,õ,ô][o,ó,ö,ò,õ,ô]hhhh!!!!/i
    );
  });
  it('should convert all "u" to regexp', () => {
    expect(convertStringToRegexp('ÚUhuuúll!')).to.deep.equal(
      /[u,ü,ú,ù,û][u,ü,ú,ù,û]h[u,ü,ú,ù,û][u,ü,ú,ù,û][u,ü,ú,ù,û]ll!/i
    );
  });
  it('should convert all "c" to regexp', () => {
    expect(convertStringToRegexp('Cacacacaca')).to.deep.equal(
      /[c,ç][a,á,à,ä,â,ã][c,ç][a,á,à,ä,â,ã][c,ç][a,á,à,ä,â,ã][c,ç][a,á,à,ä,â,ã][c,ç][a,á,à,ä,â,ã]/i
    );
  });
  it('should remove all special characters', () => {
    expect(
      convertStringToRegexp('hello 123 °º¶§∞¢£™·ª•*!@#$%^WORLD?.')
    ).to.deep.equal(
      /h[e,é,ë,è,ê]ll[o,ó,ö,ò,õ,ô] 123 [ªº°][ªº°]¶§∞¢£™·[ªº°]•\*!@#\$%\^w[o,ó,ö,ò,õ,ô]rld\?\./i
    );
  });
  it('should accept all regexp reserved characters', () => {
    expect(
      convertStringToRegexp('Olá [-[]{}()*+?.,\\o/^$|#s] Mundo! ')
    ).to.deep.equal(
      /* eslint-disable @typescript-eslint/no-explicit-any */
      /[o,ó,ö,ò,õ,ô]l[a,á,à,ä,â,ã] \[-\[\]\{\}\(\)\*\+\?\.,\\[o,ó,ö,ò,õ,ô]\/\^\$\|#s\] m[u,ü,ú,ù,û][n,ñ]d[o,ó,ö,ò,õ,ô]! /i
    );
  });
});

Comment: You might want to add some tests with commas in them ;) The RegExp character sets will match any character from that set, including the comma. You don't separate the characters in the character set – those are just lists of characters (and character ranges). So yes, your first test RegExp matches `'ÓOoóhhhh!!!!'`, but it would also match `',,,,hhhh!!!!'`.
Answer: Documentation
Case insensitive regular expression queries generally cannot use indexes effectively. The $regex implementation is not collation-aware and is unable to utilize case-insensitive indexes.
Comment: Thx for pointing that out. The problem is therefore yet UNSOLVED :(
Answer: There is no need to use collation on top of regex. You can functionally implement this behaviour using the correct regex.
Considering to the Antwerpen example the following regex gives you all the matches in the database:
/antw[eë]rpen/i
To generate the above regex you have to regex-replace your search string first using the following replace formula:
str.replace(/e/ig, '[eë]')
And of course you have to do it with all diactric character. Also you can simply use the following library:  diacritic-regex.

Use of collation in mongodb $regex


Sql nao retorna nome de coluna

Question: Tenho duas tabelas uma TEAM outra MATCH_DETAILS. A tabela TEAM tem a coluna id e é chave primaria. Fiz duas relaçoes da tabela TEAM para MATCH_DETAILS. Na MATCH_DETAILS assumiu como chave estrangeira team_id e team_id1.
Com a seguinte query:
SELECT
  team_name, team_id1, Umpire_name,
  playermatch_name, score_id
FROM
  Match_details m, Team t,
  Umpire u, player_match p, Score s
WHERE m.TEAM_TEAM_ID = t.TEAM_ID
  and m.TEAM_TEAM_ID1 =  m.TEAM_TEAM_ID1
  and m.UMPIRE_UMPIRE_ID = u.UMPIRE_ID
  and p.Match_details_MATCH_ID = m.match_id
  and s.Match_details_MATCH_ID = m.match_id;

Retorna o seguinte:

A euipa Chelsea tem como id numero 1  o id numero 2 na coluna team_id1 corresponde a euipa liverpool. aquilo que pretendo é aparecer Liverpool e não o id que corresponde.
Answer: Em primeiro lugar, eu sugeria utilizar junções explícitas ao invés de junções implícitas (ANSI-92). Apesar de não haver diferenças de performance, a "nova" sintaxe é bastante mais legível quando existem muitas tabelas envolvidas (como é o seu caso).
Dito isto, a sua query pode ser re-escrita da seguinte forma.
SELECT  T1.TEAM_NAME,
        T2.TEAM_NAME,
        U.Umpire_name,
        playermatch_name,
        score_id
  FROM Match_details m_d,
 INNER JOIN Team T1  -- Detalhes da primeira equipa
    ON T1.TEAM_ID = m_d.TEAM_ID
 INNER JOIN Team T2  -- Detalhes da segunda equipa
    ON T2.TEAM_ID = m_d.TEAM_ID1
 INNER JOIN Umpire U
    ON U.UMPIRE_ID = m_d.UMPIRE_UMPIRE_ID
 INNER JOIN player_match P
    ON P.Match_details_MATCH_ID = m_d.match_id
 INNER JOIN Score S
    ON S.Match_details_MATCH_ID = m_d.match_id

Note a dupla junção na tabela TEAM: Uma para a primeira equipa (no seu exemplo Chelsea) e outra para a segunda equipa (Liverpool). Para mostrar o nome da segunda equipa no resultado, basta selecionar o nome da tabela respective (T2) ao invés do ID.
Comment: experimentei sua sugerencia e nao funcionou apresenta o seguinte erro:ORA-00933: comando SQL não foi terminado correctamente
00933. 00000 -  "SQL command not properly ended"
Comment: @DianaMadeira, editei a resposta. Faltava incluir "JOIN" em duas das junções

Sql nao retorna nome de coluna


Python - Convert scientific notation string to float retaining decimal places

Question: I am using python to read some float values from a file. The values read are input to an 'Ada'(Programming Language) program.
The values being read are in different formats (scientific, decimal) and I would like to retain the format.
Everything works well with simple float() operation except when converting '1.0e-5' to float.
>>float('1.0e-5')
#returns 1e-5

1e-5 when used in Ada program gives
error:negative exponent not allowed for integer literal

1.0e-35 works with ada program.
I know if I use format I can get 1.0e-5
>>>"{:.1E}".format(float('1.0e-5'))
#returns '1.0E-5'

But this changes format for other read values also as my reading/manipulation function is common.
How should I approach this problem?
and if
float('1.0')
#returns 1.0

why same behavior is not followed when converting a scientific notation string to float?
(My reading/manipulation function is common. Using formatter string will change the formatting of other read values also)
Answer: You could use a custom float to string conversion function which checks if the number will be accepted by Ada using a regular expression (which tests if there are only non-dots before the exponent character, and in which case only convert with format):
import re

def ada_compliant_float_as_string(f):
    return "{:.1e}".format(f) if re.match("^-?[^\.]e",str(f)) else str(f)

for f in [-1e-5,1e-5,1.4e-5,-12e4,1,1.0]:
    print(ada_compliant_float_as_string(f))

prints:
-1.0e-05
1.0e-05
1.4e-05
-120000.0
1
1.0

only the first value is corrected, other values are just the string representation of a float, unchanged.
Comment: because `1.0` tells you that this is a float. With `1e-35` you _know_ this is a float because of the exponent. No need to add the `.0` part.
Comment: Thanks. But why does it remove '.0' in the first place?
Comment: what do you mean?
Comment: Like when we convert '1.0' string to float, it retains '.0' but not for '1.0e-5'..
Comment: Ok. Thanks. Is there any downside if python retained `.0` part?
Comment: Haha.. Thanks for your help..:)


Vim Starts on Insert Mode and Inserts Special Characters

Question: So vim just suddenly started flaking out on me today and I can't pinpont the problem. Haven't touch the configuration file and the last thing I worked on before I noticed the problem was updating my sshd_config and sshd_config.pacnew files.
What I noticed is that upon opening the sshd_config file is vim starting out in insert mode and automatically inserted a series special characters wherever the curser was at the moment. So it overwrites information in configuration files. I guess that can become somewhat problematic =)
So if I start a new file touch test_vim && vim test_vim this is what I see:
:bfff/00fe/00fe/13fe[>85;95;0c
I have a feeling this is going to be one of those things that's really stupid and I completely overlooked. Does anyone have any idea what's going on?
" An example for a vimrc file.
"
" Maintainer:   Bram Moolenaar <firstname.lastname@example.com>
" Last change:  2014 Feb 05
"
" To use it, copy it to
"     for Unix and OS/2:  ~/.vimrc
"         for Amiga:  s:.vimrc
"  for MS-DOS and Win32:  $VIM\_vimrc
"       for OpenVMS:  sys$login:.vimrc

" When started as "evim", evim.vim will already have done these settings.
if v:progname =~? "evim"
  finish
endif

" Use Vim settings, rather than Vi settings (much better!).
" This must be first, because it changes other options as a side effect.
set nocompatible

" allow backspacing over everything in insert mode
set backspace=indent,eol,start

if has("vms")
  set nobackup      " do not keep a backup file, use versions instead
else
  set backup        " keep a backup file (restore to previous version)
  set undofile      " keep an undo file (undo changes after closing)
endif
set history=50      " keep 50 lines of command line history
set ruler       " show the cursor position all the time
set showcmd     " display incomplete commands
set incsearch       " do incremental searching

" For Win32 GUI: remove 't' flag from 'guioptions': no tearoff menu entries
" let &guioptions = substitute(&guioptions, "t", "", "g")

" Don't use Ex mode, use Q for formatting
map Q gq

" CTRL-U in insert mode deletes a lot.  Use CTRL-G u to first break undo,
" so that you can undo CTRL-U after inserting a line break.
inoremap <C-U> <C-G>u<C-U>

" In many terminal emulators the mouse works just fine, thus enable it.
if has('mouse')
  set mouse=a
endif

" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if &t_Co > 2 || has("gui_running")
  syntax on
  set hlsearch
endif

" Only do this part when compiled with support for autocommands.
if has("autocmd")

  " Enable file type detection.
  " Use the default filetype settings, so that mail gets 'tw' set to 72,
  " 'cindent' is on in C files, etc.
  " Also load indent files, to automatically do language-dependent indenting.
  filetype plugin indent on

  " Put these in an autocmd group, so that we can delete them easily.
  augroup vimrcEx
  au!

  " For all text files set 'textwidth' to 78 characters.
  autocmd FileType text setlocal textwidth=78

  " When editing a file, always jump to the last known cursor position.
  " Don't do it when the position is invalid or when inside an event handler
  " (happens when dropping a file on gvim).
  " Also don't do it when the mark is in the first line, that is the default
  " position when opening a file.
  autocmd BufReadPost *
    \ if line("'\"") > 1 && line("'\"") <= line("$") |
    \   exe "normal! g`\"" |
    \ endif

  augroup END

else

  set autoindent        " always set autoindenting on

endif " has("autocmd")

" Convenient command to see the difference between the current buffer and the
" file it was loaded from, thus the changes you made.
" Only define it when not defined already.
if !exists(":DiffOrig")
  command DiffOrig vert new | set bt=nofile | r ++edit # | 0d_ | diffthis
          \ | wincmd p | diffthis
endif

Comment: Are you sure that file `test_vim` doesn't exist before you did a `touch` on it ?
Comment: I'm sure. I created several test files to confirm. Or I can open any existing file and vim will just add those special characters to that file.
Comment: so, what happens if you don't source your .vimrc?
Comment: the problem goes away if I don't source my vimrc.. I haven't touched my vimrc file since setting up vim. Any idea what's going on here? Just a thought, but I can try using the vimrc file from my other notebook to see if that does anything they use the same configuration.
Comment: Post your vimrc. Do you have any mappings to escape (``) in it?
Comment: I don't have any mappings to escape. Alright, posted .vimrc
Comment: Okay, so searching online I stumbled onto vim registers, something which I knew nothing about. .viminfo stores these registers, so I looked in the file and sure enough the second register in the list contains those special characters. Don't know how they got in there. I must have accidentally hit the wrong series of keys at some point. I also noticed my email address and some shell commands in other registers, apparently you can have more than one. They just store information for later use. I must be inadvertently adding them in. Could this be the problem? Still doesn't explain insert mode.
Comment: What exactly happens when you run `vim`, try `alias | grep vim`.
Comment: Same thing happens. Someone mentioned it being a bug, but it doesn't seem to affect my other computer.
Answer: This is a recent Vim bug. You should probably roll back to an earlier release while a proper fix is worked on.
Comment: Hmm... that's odd because it's not affecting my other computer which uses the same version of vim. Thanks for the heads up, guess it's back to nano for now
Comment: The bug seems to affect urxvt termianls and may be realted to transparency. Works find when using other terminals.
Answer: You can have a look about changing the vim configuration files on this post
this is the official vim wiki page
Vim wiki
Comment: I haven't laid a hand on the configuration file so I think it's some other issue.
Answer: So the bug seems to affect urxvt terminals running with transparency. Using a different terminal, or in my case disabling transparency via /.Xresources will temporarily solve the issue until they release a patch.


Lebesgue measure and characterisation of function $\Phi$ [Rudin-Real&Complex]

Question: Let $m$ be Lebesgue measure on $[0,1]$ and define $||f||_p$ with respect to $m$ as usual. What are all functions $\Phi$ on $[0, \infty)$ such that the relation
$$ \Phi( \lim_{p\to\ 0}||f||_p)= \int_{0}^{1}(\Phi\circ f)dm$$
holds for every bounded, measurable, positive $f$ ?
A hint is provided:

Show first that
  $$c \Phi(x)+(1-c) \Phi(1)= \Phi(x^c) \ \ (x>0, 0 \le c \le 1) \ \tag 1 $$

I was thinking of using this $$ \lim_{p\to\ 0}||f||_p = \exp\left \{ \int_0^1 \log |f| dm\right \}$$ From here we get that $\log $ satisfies the condition.
Then I tried to show that any $\Phi$ which meets the conditions of $(1)$  must satisfy the relation, $\Phi(xy)= \Phi(x)+ \Phi(y)$ from which I want to conclude that $log$ is the only such function.
Is my line of thinking correct? If not, then how should I proceed?
Comment: It is not hard to see that any constant function will satisfy your assumptions. Since both sides are linear in $\Phi$, this also means that linear combinations of log and constants also satisfy your equation.
Comment: are you sure that $p\to 0$?
Comment: Yes. I know that it is not a norm for $p<1$.
Comment: Its easy to see that $\Phi=\log$ is one solution, using that $\lim_{p\to 0}||f||_p=\exp$...
Comment: Yes. That is sort of obvious. Also scalar multiples of $log$ satisfy it. But I need to find all such functions.
Comment: Is that obvious? You have said that $\Phi$ is defined at 0 too.
Comment: This was the printed question. I think it should be $(0, \infty)$
Answer: First, it's not clear from your post and the comments whether you've seen why $\Phi$ must satisfy (1). Let $f=x\chi_{(0,c)}+\chi_{(c,1)}$. Then $$\int_0^1\Phi(f)=c\Phi(x)+(1-c)\Phi(1),$$while $$||f||_p=\left(cx^p+1-c\right)^{1/p}.$$
So $$\log(||f||_p)=\frac1p\log(1+c(x^p-1))\sim\frac cp\left(e^{p\log(x)}-1\right)\sim c\log(x).$$So (1) holds.
Now if you let $\Psi(s)=\Phi(e^s)-\Phi(1)$ then (1) gives $$c\Psi(t)=\Psi(ct)\quad(0\le c\le 1,\,t\in\Bbb R).$$Setting $t=1$ shows that $$\Psi(c)=c\Psi(1)\quad(0\le c\le 1).$$And $t=2$ shows $\Psi(2c)=2\Psi(c)$. Hence $$\Psi(c)=c\Psi(1)\quad(c\ge0).$$
Unravelling things now shows that $\Phi(t)$ is a linear combination of $1$ and $\log(t)$.

Conversely, any linear combination of $1$ and $\log$ works. This is well known, or at least better known to me than what's above. Proofs exist in various places, for example On the space $L^0$ and $\lim_{p \to 0} \|f\|_p$  . (Ok, all you actually find there is a proof that $\Phi=\log$ works. But it's obvious that $\Phi=1$ works, and that the set of $\Phi$s that work is closed under linear combinations.)
Comment: Why did you take this specific $f$? Could you explain it? It does not look like a general proof.
Comment: @VaibhavJena We are _given_ that $\Phi(\lim||f||_p)=\int\Phi\circ f$ for _every_ $f$. In particular that holds for the $f$ that I chose. It holds for any $f$. The reason I chose that particular $f$ is that it shows how what we are given implies (1). It is true that I didn't show that in fact if $\Phi$ is a linear combination of $1$ and $\log$ then  $\Phi(\lim||f||_p)=\int\Phi\circ f$ holds for every $f$. That's not part of what the problem asked us to prove. (There are various posts around here, including one by me, that do show that any linear combination of $1$ and $\log$ works.)
Comment: But can we say that there does not exist any other function apart from linear, $\log$ and their combinations ?
Comment: @VaibhavJena Yes, we can say there are no other such functions. That's exactly what I proved. Come to think of it I should retract my previous comment, though: Looking back at the question, it said "find all $\Phi$ such that...". I showed that if $\Phi$ works then $\Phi$ is a linear combination of $1$ and $\log$, but yes the question _does_ require that we also show that any linear combination of $1$ and $\log$ works.
Comment: @VaibhavJena I just edited this post to include it. Thanks for pointing out the gap...


Three level tab on user profile page

Question: I am trying to show a 3 level tab on the user profile page, but I cannot find a way of doing it.  I've managed to get a second level working, on my custom module on drupal 7.
<code><?php
/**
 *patners page with all the tabs
 */

$items['user/%user/patners'] = array(
    'title' => t('My deals'),
    'description' => t('this is to show patners ther items'),
    'page callback' => 'patners_page',
    'page arguments' => array(1),
    'access arguments' => TRUE,
    'type' =>MENU_LOCAL_TASK,
    'weight'=>-18,
);
$items['user/%user/patners/coupon'] = array(
    'title' =>'??????',
    'page callback' => 'patners_page',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_DEFAULT_LOCAL_TASK,
);
$items['user/%user/patners/statistics'] = array(
    'title' => '?????????',
    'page callback' => 'partners_statistics',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
);
$items['user/%user/patners/coupon/all'] = array(
    'title' =>'??? ??????',
    'page callback' => 'patners_page',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_DEFAULT_LOCAL_TASK,
);
$items['user/%user/patners/coupon/used'] = array(
    'title' =>'????????????',
    'page callback' => 'patners_coupon_used',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
);
$items['user/%user/patners/coupon/pending'] = array(
    'title' =>'??????',
    'page callback' => 'patners_pending_coupons',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
);
return $items;
?>
</code>
Comment: You're going to have to be more specific.  Drupal version?  Any contrib modules?  Could you post any custom code so we can see if there are any errors in it?  the more information you provide the more likely you are to get a constructive answer.
Comment: @Chapabu I have edited the Question,i have included my code. I am using drupal 7.
Answer: Drupal doesn't provide third level local tasks by own. You have to implement it, something like this:
<code>/**
 *  @see: menu_local_tabs()
 */
function my_module_menu_local_tabs() {
  return array(
    '#theme' => 'menu_local_tasks',
    '#primary' => menu_primary_local_tasks(),
    '#secondary' => menu_secondary_local_tasks(),
    '#tertiary' => my_module_tertiary_local_tasks(),
  );
}

/**
 * @see: menu_secondary_local_tasks()
 */
function my_module_tertiary_local_tasks() {
  // The index of local task starts from 0, so you need the 2 level of local tasks.
  $links = menu_local_tasks(2);
  // Do not display single tabs.
  return ($links['tabs']['count'] > 1 ? $links['tabs']['output'] : '');
}

function my_module_preprocess_page(&$vars) {
  $variables['tabs'] = my_module_menu_local_tabs();
}
</code>
All of this code based on core's localtask generation function, it's normally alterable, translation-ready, access checked:
menu_local_tabs()
menu_secondary_local_tasks()

Three level tab on user profile page


Requisição Get em Python encerra o programa quando não há conexão

Question: Estou desenvolvendo uma aplicação em Python para verificar o IP externo e salvar em uma base de dados, o problema é a seguinte função:
def pega_ip(): ip = get('https://api.ipify.org').text return ip

Pelo fato de ela usar o método get para receber o conteúdo diretamente em uma variável, quando não há conexão com a internet, o erro ocorre:

File "/usr/local/lib/python3.5/dist-packages/requests/adapters.py",
  line 508, in send raise ConnectionError(e, request=request)
  requests.exceptions.ConnectionError:
  HTTPSConnectionPool(host='api.ipify.org', port=443): Max retries
  exceeded with url: / (Caused by NewConnectionError(': Failed to
  establish a new connection: [Errno -3] Temporary failure in name
  resolution',))

Preciso tratar este problema pois o programa é finalizado quando este erro ocorre, preciso que caso a conexao caia ele continue executando e tentando acessar esta url para assim conseguir o IP externo.
Answer: Você só tem que botar num while e pegar a exceção quando ocorrer:
def pega_ip():
    while True:
        try:
            ip = get('https://api.ipify.org').text
            return ip
        except ConnectionError:
            pass

Assim, se houver uma exceção, ele vai imediatamente tentar novamente. Se não houver, ele chega no return e a função é encerrada.
Comment: Valeu amigo pela ajuda!


What statistical measures are recommended for mixing of population samples?

Question: I want to know what statistics should be used to measure the mixing of languages in cities in a country/state. I have samples from individuals and know the language they speak and the city they live in. The cities are not all the same size and there are 3 different language groups.
The samples are taken uniformly from the total population so that larger cities have a proportionally larger number of samples in the data set.
I want to avoid naive approaches such as; taking the value from A/B since 100/50 is the same as 2/1 and have equal contributions.
Comment: Your reply indicates your data are richer than just counts of individuals: how otherwise can you discern evidence of segregation within mere counts? Are you perhaps suggesting you want to study how your counts vary geographically?  If so, exactly how would such variation be interpreted in terms of "segregation" or lack thereof? To be concrete, suppose the counts are (50K, 10K, 5K) in one city and (0K, 5K, 5K) in another (smaller) city. How do these cities compare in terms of "segregation"? Would your answer change if the third component were a small minority within the state?
Comment: Building on @whuber, and just to check on what you mean by "segregation" - do you actually mean just varying proportions?  For example, there is a higher proportion of Spanish speakers in Los Angeles than there is Vancouver, but I don't know that this would mean "segregation" in the common English usage.  But this seems to be what you are looking for.  Perhaps a better expression would be "varying proportions" of the language groups.
Comment: What is the purpose of your study?  What would you be using these statistics or measures for?
Comment: @whuber, the purpose is to see if there is segregation or not. If the populations are mixed uniformly or cluster together.
Comment: @whuber the answer would not change if the third component was a minority within the state although in this example it is. In your example with those numbers the first city is less uniform than the others maybe in terms the distribution of the languages from something merely random.
Comment: @PeterEllis yes, `varying proportions` appears to be a much better expression. I imagine that saying that given the total population counts of each category the ratios in each city are not random.
Answer: A humble Chi sqare test is probably all you need to test the null hypothesis that there is no relationship between mother tongue and city ie that the proportion of speakers is the same in each city (note that this is not the same as all proportions are a third).
As per my comments, I'm not sure this is that useful a question, depending on the context.  After all, you would expect different cities to have different proportions of languages wouldn't you, on historical, geographical and cultural grounds?  So you will almost certainly reject a null hypothesis of equal proportions.
But the test would be something like the below.  The numbers in the table represent the number from a sample reporting that language as their mother tongue (made-up data).
<code>> x <- data.frame(
+ row.names=c("London", "New York", "Hanover"),
+ english=c(100,100,10),
+ german=c(5,8,60),
+ french=c(7,4,12))
> x
         english german french
London       100      5      7
New York     100      8      4
Hanover       10     60     12
>
> # inbuilt chi square test:
> chisq.test(x)

        Pearson's Chi-squared test

data:  x
X-squared = 174.4, df = 4, p-value < 2.2e-16

>
> # or, by hand:
> # First, what are the "expected" values if there
> # is no relationship between city and language
> e <- apply(x,1,sum) %o% apply(x,2,sum)/sum(x)
> e
         english german french
London     76.86  26.72  8.418
New York   76.86  26.72  8.418
Hanover    56.27  19.56  6.163
> sum((x-e)^2/e)
[1] 174.4
>
</code>
Answer: If you are only looking for a score you can take inspiration from the question
How does one measure the non-uniformity of a distribution?.
If you have a perfect mixing, the distribution of your languages should be uniform in every city (i.e. 1/3 each language group). If mixing is imperfect, it will not be uniform.
The answer to this post suggests using the $\chi^2$ metric, the entropy or the Kullback-Leibler divergence. I would actually use the last one, which easily allows you to normalize for unequal language distribution in the whole population.
Comment: I doubt there is any state or country in the world whose population is exactly equally distributed among three languages (or any other three categories, for that matter)! This highlights the importance of looking at the metric *in context* and of using it *to make comparisons* rather than on some absolute scale. Of greater concern is the potential for some abstract theoretical answer (no matter how rigorously supported) to be misinterpreted or misused for such a socially important application as assessment of segregation.
Comment: Thanks for the feedback @whuber. If I understand your point, since populations are far from uniform it makes no sense to compare their distance to that ideal situation (+1). Still, as far as I am aware, you can compare the entropies together, without reference to the "absolutely perfect situation".
Comment: This is what I had in mind when writing the answer. Following the comment of @whuber I admit that comparing your groups to ideal distributions ($Q$ in your case) does not necessarily make sense. Still, you can try, maybe it works just fine. Otherwise you can compute the entropy of the distribution in each city and directly compare those scores.
Comment: @gui11aume I am thinking of using the KL divergence http://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence#Definition , and using the Beta/Dirichlet distributions for `P` and `Q`, and the parameters for `P` to be the population groups in a region and for `Q` to be the population group values overall. How does that sound?
Comment: @gui11aume , I also thought of using absolute differences or some squared deviation, from the average global ratio, what would you think of this? whuber 's comment is correct, but without much more information I cannot take into account all of the necessary contexts to be more accurate.


lighttpd does not start at boot after enabling ipv6

Question: A few days ago I configured lighttpd to listen on my VPS IPv6 address as well. It runs on a Debian 7 Xen VPS (Linode) with a 3.15.4-x86_64-linode45 kernel. The version of lighttpd is 1.4.31-4+deb7u3.
My lighttpd.conf used this configuration to listen to IPv4:
server.bind                 = "10.0.0.1"
server.port                 = 80

I added the following to enable IPv6 as per http://redmine.lighttpd.net/projects/lighttpd/wiki/IPv6-Config
$SERVER["socket"] == "[2001:DB8::1]:80" {  }

Now, when I restarted lighttpd, everything was alright - it ended up listening to both as planned.
The problem appeared after I had to reboot my VPS. Turns out at boot time, starting lighttpd fails with the following message to the console:
[....] Starting web server: lighttpd2014-10-20 21:00:19: (network.c.405)
       can't bind to port: 2001:DB8::1 80 Cannot assign requested address

If I login and run service lighttpd start it starts without a problem, listening on both IPv4 and IPv6.
I thought that maybe it didn't have the IPv6 address at boot time, so I made it output ifconfig to a file before attempting to start (in the init script) and it has both IPs assigned to the interface.
Any ideas what might be the problem or how to troubleshoot this further?
Comment: Why not just bind to any address?
Comment: I need to be specific as there are other alias interfaces configured and it shouldn't bind to those.
Answer: When IPv6 addresses are configured they aren't available immediately. The system first performs DAD (Duplicate Address Detection) to make sure that its new address doesn't conflict with an existing address on another system. Applications cannot bind (at least not with default settings) to addresses that are still tentative.
Recent versions of the Debian ifupdown package contains a script called settle-dad.sh that will pause until the interface has left the tentative state. You might want to add such a script to your boot process between configuring the network interface and starting your servers.
It's not that big/complex:
#!/bin/sh

# 6 seconds maximum wait time
attempts=${IF_DAD_ATTEMPTS:-60}
delay=${IF_DAD_INTERVAL:-0.1}

[ $attempts -eq 0 ] && exit 0

echo -n "Waiting for DAD... "
for attempt in $(seq 1 $attempts); do
    tentative=$(ip -o -6 address list dev "$IFACE" to "${IF_ADDRESS}/${IF_NETMASK}" tentative | wc -l)
    if [ $tentative -eq 0 ]; then
        attempt=0 # This might have been our last attempt, but succesful
        break
    fi
    sleep $delay
done

if [ $attempt -eq $attempts ]; then
    echo "Timed out"
    exit 1
fi

dadfailed=$(ip -o -6 address list dev "$IFACE" to "${IF_ADDRESS}/${IF_NETMASK}" dadfailed | wc -l)

if [ $dadfailed -ge 1 ]; then
    echo "Failed"
    exit 1
fi

echo Done

It is distributed under the GPLv2 license.
Comment: Alternatively one could change the `accept_dad` setting to disable DAD. On a server with a static IP address, DAD isn't very useful after all.
Comment: It makes sense, thanks. I'll try integrating it tonight as a dependency. Seeing as it's in sid I might spin it up in a VM to see how it's called.
@kasperd Completely agree with you, but in this case the IP is assigned via DHCPv6.
Comment: If you get the address via dhcpv6 binding to "[::]:80" sounds like the better solution :)
Comment: Yeah, getting an address through a dynamic protocol and then putting it statically in some other configuration files sounds like a unnecessary complication. I would personally do everything statically in such a case.
Comment: I agree that logically it doesn't make sense. But that DHCP binding is static (it's just an IP that can't be allocated via SLAAC) and its use is mandated by the whole VPS setup (ties in with DNS and their tools).
Comment: Integrating settle_dad.sh into existing scripts is more trouble than I have time for. Your answer is right though (thanks!), it is DAD that's preventing lighttpd from binding. I've solved it in a dirtier fashion by making the lighttpd start-up script wait until DAD is done.


Como verificar se uma sessão ($_SESSION) existe ou está ativa em PHP?

Question: existe algum função nativa do PHP que possa utilizar para verificar se uma sessão de determinado usuário está aberta?
Por exemplo, tenho uma $_SESSION['usuario'] = "400379d4eaa6ec24826dd44cd5cf65a3" e quero consultar se ela está ativa no servidor PHP que está com a sessão ativa.
Isso, através de outra página, externa, por exemplo, se alguém chamar: http://meuenderecom.com.br/getSession.php?idUsuario=400379d4eaa6ec24826dd44cd5cf65a3 quero que retorne 'S' se a sessão estiver ativa, ou 'N' se a sessão estiver fechada.
Answer: Pelo que entendi, você quer saber se uma outra sessão, que não a do usuário em questão, existe, certo? Se sim:
O PHP guarda os dados das sessões em uma pasta temporária no servidor, que você pode descobrir qual é, ou até mesmo definir, usando session_save_path().
Para cada sessão, o PHP cria um arquivo sess_{SESSION_ID} nessa pasta. Você pode pegar a lista de arquivos (sessões) usando:
<?php
print_r(scandir(session_save_path()));
?>

Se você quiser saber se uma sessão específica existe, caso você tenha o SESSION_ID, você pode fazer o seguinte:
<?php
session_start();
// $SESSION_ID = id da sessão que você quer saber se existe
echo (file_exists(session_save_path().'/sess_'.$SESSION_ID) ? "Existe!" : "Não existe!");
?>

Como parece que você quer buscar pelo 'usuario', você teria que fazer o parse desses arquivos e verificar pela informação que você precisa lá. Caso não queira fazer o parse, você pode pegar o ID de todas as sessões, que está no nome do arquivo e fazer um loop inicializando via session_start($SESSION_ID) e buscando pelo dado que você precisa conferir, nesse caso o usuário.
Vale lembrar que de nenhuma maneira isso é uma recomendação. Ainda há uma opção, que seria manipular as sessões você mesmo, setando um novo handler. Dessa forma você poderia guardar os dados num banco ou de outra maneira que preferir, mas você precisa ter certeza que sabe o que está fazendo!
Por fim, parece que você só quer saber se um usuário está online. Existem outras técnicas muito mais seguras e eficientes para se fazer isso, mas fica para uma próxima pergunta (ou até mesmo já deve ter uma sobre isso).
Answer: pra fazer isso basta usar o comando isset(), no seu caso ficaria assim, usando um if ternário:
$valor = isset($_SESSION['usuario']) ? 'S' : 'N';

Comment: Mas em que lugar vou informar o `id` da sessão que quero verificar?  Eu atribuí a $_SESSION['usuario'] o código "400379d4eaa6ec24826dd44cd5cf65a3".
Comment: sua pergunta não está muito clara, por favor, edite-a pra que eu possa ajudar melhor
Comment: O que não entendeu? Veja: tenho uma sessão, em que atribuí a ela vários identificadores criptografados, e quero através de um desses identificadores saber se a sessão está ativa ou não, pelo ID e não pela sessão em si!
Answer: Com essa pergunta na verdade acaba expressando talvez outras dúvidas, ideal estudar um pouco.
Se quiser pegar o id de sessão pode usar o session_id() porém existem outras variáveis acerca disto, por exemplo:
- Pode-se ter havido o encerramento da sessão do usuario(session['usuario'], mas a session_id() ainda poderá ser a mesma se não foi feito um regenerate... recomendo que pesquise um pouco sobre como funcionam sessões para todos podermos ajudá-lo melhor.


Mongoid query with OR and WHERE

Question: I am building a rails3 web app. Is there a query like this in mongoid
<code> db.collection.where((:status => "abc" OR :status2=>"abc") , :license=>"Active")
</code>
I don't know what fields are present in my collection, one between status and status2 field could exists in my collection or both may exists.
Update
I found that I could use any_of for OR but it is not working. The query is runny find but there is no result.
<code> db.collection.any_of(:status=>"abc",:status2=>"abc").where(:license=>"Active")
</code>
Comment: Did you try reading the docs?
Comment: ya. I found that i could use any_of but it is not working. my query db.collection.any_of(:status=>"abc",:status2=>"abc").where(:license=>"Active")
Comment: your query is wrong. Read the docs again.
Comment: thank you, found the answer its - db.collection.any_of({:status=>"abc"},{:status2=>"abc"}).where(:license=>"Active"). May be I posted this question a bit early.
Answer: Posted this question without enough search. The answer is
<code> db.collection.any_of({:status=>"abc"},{:status2=>"abc"}).where(:license=>"Active")
</code>

Mongoid query with OR and WHERE


How to give more depth to vocals when mixing?

Question: I'm recording vocals with a SM58 mic through a USB audio interface and getting clean audio with no ambient noise. At this point it sounds pretty flat (no reverb or echo from the room). So in my DAW I've been experimenting with different effects to make it sound more full and natural, like you hear on professional recordings. I've tried adding reverb which helps a little. I've run it through a compressor. I'm using an EQ which works well, but I can't find the optimal settings. After a while of playing around it starts to sound weird and unnatural.
So my question is, which frequencies should I boost to make the best sound? What other things can I do to give my audio recordings more depth, make them stand out and sound great in the mix.
Comment: Not a full answer but have you tried doubling? Record the vocals two or three times and mix them together.
Comment: "more depth, make them stand out and sound great in the mix" - could you explain what you mean by 'more depth' ? I understand it's hard to put into words bit there are lots of answers already listed, it might help to know a bit more about how the sound is lacking. Ta
Answer: Before trying any effects at all, I should change that mic if I were you. The SM58 is an amazing live mic – not just because it's dead sturdy, but also because it has a very focused, direct, "shallow" sound. Great to make vocals come out in a live mix and to avoid feedback and other common trouble – but none of these benefits have any relevance for a studio recording! If you want a full, deep, clear sound, no dynamic mic can hope to match even cheap large-diaphragm condensers you can get today. One of those1, perhaps through a tube preamp, should give you a much better signal to start with, without the dangers of "fixing it in the mix" with compressors and EQs. Of course you may still want to employ some of those, but with a good signal you can do it much more subtle and to the point.

1You may need a pop screen for a large-diaphragm mic. Also, be sure to record in a room with decent acoustics... parallel-walls-clatter-resoncances are deadly to any recording.
Comment: @Almo: yes and no. Yes, tube amps in stereo systems have questionable value, because there's not really a good reason to saturate the signal at that point (the mastering engineer will already have done that as much as sensible). However (unlike $100 power chords etc.), there's no doubt that tubes do alter the sound, and in a way that is quite benefitial in particular as a first stage for vocals (adding smooth even harmonics, and boosting RMS for given peak gain without really committing compression). Sure you can also simulate that later in digital, but that incurs aliasing etc. problems.
Comment: Annie Lennox never did badly with a 58 - several big international hits, in fact ;) I've heard Bono sometimes records on one, too
Comment: @Tetsujin yes. But then, Annie Lennox has a voice that wouldn't sound flat even through a walkie-talkie. Not every singer provides such an advantageous starting point.
Comment: For sure - I'm just not a fan of the 'you cannot possibly do it with a 58' club, because you clearly can. It's not something I do a lot, I've a lovely U87 that's my prime vox mic, but I did this a few years ago, where it *had* to be live to camera, for a movie audition [you can even see & hear my clap at the start, for sync to the video]. Lousy video & I look like lightly boiled sh*t, full of cold, but all there is on this is a multiband comp & a bit of rev. I really don't think the mic is the weak point. https://www.youtube.com/watch?v=jt5grnzXuWg
Answer: Try employing parallel compression. Here is a good article about it. Basically, you make a copy of your vocal track. Leave one copy alone and compress the other. That gives you the original loud transients plus a compressed version where the rest of the material is also louder. Sometimes, you'll see this described where the original has very fast or very subtle compression (or even expansion). Hence "parallel".
Comment: Parallel compression is a useful technique in a number of situations. But so are a hundred of other particular FX tricks. I don't think it's very helpful to list all those! And FWIW, most transients are actually preserved quite well in regular a non-limiting compressor with attack > 3 ms. Such a rather slow compressor is a much better point to start learning dynamics processing, instead of going parallel right away. But before even doing the most basic EQ, _get the mic right_!
Comment: As your own answer says, @leftaroundabout, a large diaphragm condenser mic and a decent preamp is certainly the ideal setup and it's what I use, too. And I agree that it's not useful to list every FX trick. But for the original poster's situation, *this technique* is apropos, particularly if running out to buy more equipment isn't an option. There's hardly any recording problem you can't solve with enough money, but many of them are also solvable with a bit of ingenuity.
Comment: I very much agree on that last sentence. It's just that such ingenuity comes only through long experience, experimentation with all kinds of effects – and, IMO, to start you should get a proper understanding of the basics, so you can even appreciate how such and such effect behaves in a more complex setup like parallel-comp. These days, a lot of people think they know all about mixing because they have read so much about a bunch of "miracle effects". Well, to me the records such guys produce usually sound less than ingenious!
Comment: Or, to turn your argument around: _there's hardly any recording problem you can't solve with enough FX-foo, but many of them wouldn't even have surfaced if you had used a better mic-setup in a room with great acoustics_!
Answer: One technique that works like magic is by splitting the vocals channel into multiple channels, panning each channel differently, and then applying a different equalizer to each channel. This creates a very subtle difference between what you're hearing in your left and right ear, which is what depth is all about. The difference can be made even more pronounced by offsetting the timing of the tracks in relation to each other by a very small amount.
Comment: I did a preliminary test of this and it sounds promising. I'm doing something similar when recording acoustic guitar. I record both plugged in and through a mic at the same time and pan them to opposite channels.
Comment: Although there are a lot of great ideas discussed here, I decided to choose this one as the solution because I think it answers the original intent of the question. Sure, using a different mic might give a better input, but there's still the issue of mixing the vocals into the song and making it stand out. I think that's what this solution accomplishes. However, I suggest that you read all of the solutions offered here because there are a lot of good ideas for making your vocals sound better.
Comment: This is a terrible idea. [I only just found this in the sidebar from another question, hence being a decade late] This is a great way to create weird phase-cancellation holes in your spectrum & poor mono summation. Avoid.
Comment: I have never thought of that but it sounds like an awesome idea! What's your approach to equalize a track two times?
Answer: The only answer possible is "it depends". It depends on what sound you're trying to achieve, it depends on the recording itself. In my experience, I drop everything below 600 Hz and above 5KHz. You may need to give a little boost at 2 KHz, which is the frequency of speech.
Compression helps smooth the sound out in terms of volume but shouldn't affect the tone. Reverb adds depth; there are different types of reverb - the depth of the reverb (how many millisecs, obviously), but also how long before the reverb kicks in.
Answer: For lead vocals it is very standard practice for the singer to sing the song twice onto two parallel tracks. That alone adds significant richness the the vocal.
Another thing I'll do requires a real-time compressor: set the threshold relatively low and the ratio fairly low. If you feed that to the vocalist monitor, he will have to put more power out to hear it "correctly". This forces both better tone, and can cover a little for bad mic technique.
Answer: I like to use an analog pre-amp which adds harmonic distortion to an otherwise "cold" sounding digital recording. It adds body but could also sound muddy. You could eq out some of the tones giving it a muddy sound. Run an out into the pre and run it back into your recording setup. You could use 2 audio tracks - clean one and pre-amped one - and adjust the volume/eq of each until you get a sound you like.
Answer: The SM-58 is a more-than-capable microphone which has been used on countless studio recordings.  The key issues preventing you from getting a lively sound are probably as follows:
You are using a USB audio interface - these range GREATLY in quality. Most A/D converters in them are relatively poor from an audiophile standpoint.  If you get a higher end one with good reviews (do your research) you should get much better results (it also makes multitracking easier if you get a device with low latency - look for a newer usb 3.0 implementation or even go back to Firewire... I did and it's the best decision I could have made at the time).  It seems like this would be a minor issue, but it honestly makes all the difference in the world.
You may be recording too close to the mic.  As the SM-58 documentation so prominently indicates, the 'proximity effect' occurring from being within about 6-10 inches away from the mic will start increasing bass frequencies immensely, vastly altering the timbre.  Usually you want to be 1-2 feet away, and use your preamp gain to boost the signal to an acceptable level.
Finally, find a good compressor and learn how to use it.  In software there are several free options, one from fxpansion called DCAM which I recommend if you can find where to get a copy (I think you just have to sign up at their website). Another good one (Evaluation version only without paying) is Bombardier Bus Compressor.
EDIT: One more thing I forgot helps a ton, especially when you add the vocals to a mix, but it is the most expensive and difficult part of the whole process.  Getting a low pass and ideally also a high pass or even bandpass filter (or two, or three...) and using them to tweak the frequency response can give you any sound you want.  EDIT 2: Especially if you dynamically modulate the control paramters, i.e. with a triggered envelope.
Answer: Former sound-guy here. Here's how it was done ca. 20 years ago:

Quality condenser mic in neutral / near dead room. Neuman preferred
Quality mic pre-amp
Parametric EQ. add splash of treble, cut down bass, control clarity with mid-tones
Aphex Multiband compressor with de-ess engaged to boost dynamics
BSS 822 or similar sonic maximiser, make it 'deeper'
Lexington reverb, make it 'wider'
Eventide Ultra Harmoniser for delay / effects

Today, outboard gear is obsolete but you get the idea what is needed to achieve really 'rich' and 'crispy' vocals. it's easy to add similar plug-inns to todays DAWs
or

you could just hire a really good singer :)
Comment: Yes, deeper and wider, those are what I'm looking for. And I wish I had a really good singer. I like to write music but unfortunately I don't have anyone to sing it but myself. I'm not too bad but I'm no professional. If I was I'd be in a real studio right now letting someone else worry about the mixing :)
Answer: This article about the "Exciting Compressor" explains a technique that really pumps up any vocal part.  If you use a SM57 or SM58 specifically, here is a little non-invasive modification you can do to your mic that supposedly does miracles.  You could also achieve the effect the variable impedence on a PreSonus Eureka preamp.
Answer: A little bit of chorus or double-tracking the vocals (singing the same line two or more times and then mixing the takes) can do wonders for a vocal track.
Answer: Pro old school engineer here! Still recording many hit artists
Some nice comments. SM58 is a great mic, did you know almost ALL the vocals on all of SHED 7's albums was an SM58! It is how it is mixed. I would favour a high pass filter and lift the bottom end until it sits in the mix. And as suggested! the better the reverb the better the spacing and image. Obviously it does not help with a USB interface as vocals (as with any other instrument) is really all about dynamics, I tend to make my EQ by the type of mic used! Old school, but there are so many hits done that way. Lets face it, EQ like anything else in the chain ads noise and colour. Great, but it also can be a hinderance!


Solving integral that contain exponential function and lower incomplete gamma function

Question: I have the following integral;
$$y=\int_0^\infty\frac{e^{-xf}}{m+x}\gamma(a,hx)~dx$$
where $f,m,h\in\mathbb{R}^+$ , $a\in\mathbb{N}$ , $\gamma\left(a,h x\right)$ is the lower incomplete gamma function
Can anyone help me how to solve it?
Thank you very much
Comment: @OlivierOloa Yes, $f>0$.

I think I found the clue, if we represent the lower incomplete gamma function by infinite sum as the following (by using http://dlmf.nist.gov/8.7.E3 ):

$$\gamma(a,h x) =  \sum_{n=0}^\infty \frac{(-1)^n (h x)^{n+a}}{n! (n+a)}
$$

the above equation is true for the case of $a \ne 0, -1, -2, \ldots $ which is valid for my equation.

I think after this the integral can be solved, what do you think?
Comment: You have, as $x \rightarrow +\infty$, $$\gamma(a,hx) = \Gamma(a,0)-x^{a-1}e^{-hx}+\mathcal{O}\left(x^{a-2}e^{-hx}\right). $$
Since $\Gamma(a,0) \neq 0$, you get
$$
\frac{e^{x f}}{m+x}\gamma(a,hx) \sim \Gamma(a,0)\frac{e^{f x}}{x}
$$
as $x \rightarrow +\infty$, giving a **divergent** integral due to $f>0$.
Comment: This integral doesn't seem convergent. Are you sure that $f>0$?
Comment: @OlivierOloa I am so sorry, I made a mistake, I forgot to write (-) in front of the (x f).
Comment: @OlivierOloa Do you think my representation is correct?
Comment: Yes, I think it is a good start.
Answer: Finding a closed form for this integral seems difficult.
Let us try to obtain an analytic expression.
We may start to write
$$
\begin{align}
y & =\int_{0}^{m}\frac{e^{- x f}}{m+x}\gamma\left(a,h x\right) dx +\int_{m}^{+\infty}\frac{e^{- x f}}{m+x}\gamma\left(a,h x\right) dx
\\\\ & =\sum_{k=0}^{\infty} (-1)^k\left(\frac{1}{m^k}\!\!\int_{0}^{m}\!\!x^ke^{-f x}\gamma\left(a,h x\right) dx +m^k\!\!\int_{m}^{+\infty}\!\!x^{-k}e^{-f x}\gamma\left(a,h x\right) dx\right)
\end{align}
$$ and then inserting the series expansion you gave in your comment for $\gamma\left(a,h x\right)$.
We will end up with a double series.
Answer: Hint:
$\int_0^\infty\dfrac{e^{-xf}}{m+x}\gamma(a,hx)~dx$
$=\int_0^\infty\dfrac{e^{-fx}}{x+m}\sum\limits_{n=0}^\infty\dfrac{(-1)^nh^{n+a}x^{n+a}}{n!(n+a)}dx$
$=\int_0^\infty\sum\limits_{n=0}^\infty\dfrac{(-1)^nh^{n+a}x^{n+a}e^{-fx}}{n!(n+a)(x+m)}dx$
$=\int_m^\infty\sum\limits_{n=0}^\infty\dfrac{(-1)^nh^{n+a}(x-m)^{n+a}e^{-f(x-m)}}{n!(n+a)x}d(x-m)$
$=\int_m^\infty\sum\limits_{n=0}^\infty\dfrac{(-1)^nh^{n+a}e^{fm}(x-m)^{n+a}e^{-fx}}{n!(n+a)x}dx$
$=\int_m^\infty\sum\limits_{n=0}^\infty\sum\limits_{p=0}^{n+a}\dfrac{(-1)^nh^{n+a}e^{fm}C_p^{n+a}(-1)^{n+a-p}m^{n+a-p}x^pe^{-fx}}{n!(n+a)x}dx$
$=\int_m^\infty\sum\limits_{n=0}^\infty\sum\limits_{p=0}^{n+a}\dfrac{(-1)^{p+a}(n+a-1)!h^{n+a}m^{n+a-p}e^{fm}x^{p-1}e^{-fx}}{n!p!(n+a-p)!}dx$


unable to configure vsftpd using ssl

Question: i am trying to setup vsftpd over ssl . followings are configuration under vsftpd.conf
anonymous_enable=NO
local_enable=YES
write_enable=YES
local_umask=022
#anon_upload_enable=YES
#anon_mkdir_write_enable=YES
dirmessage_enable=YES
xferlog_enable=YES
connect_from_port_20=YES
#chown_uploads=YES
#chown_username=whoever
#xferlog_file=/var/log/xferlog
xferlog_std_format=YES
#idle_session_timeout=600
#data_connection_timeout=120
#nopriv_user=ftpsecure
#async_abor_enable=YES
#ascii_upload_enable=YES
#ascii_download_enable=YES
#ftpd_banner=Welcome to blah FTP service.
#deny_email_enable=YES
#banned_email_file=/etc/vsftpd/banned_emails
#chroot_local_user=YES
#chroot_list_enable=YES
# (default follows)
#chroot_list_file=/etc/vsftpd/chroot_list
#ls_recurse_enable=YES
listen=YES
#listen_ipv6=YES
pam_service_name=vsftpd
userlist_enable=YES
tcp_wrappers=YES
rsa_cert_file=/etc/ssl/private/vsftpd.pem
rsa_private_key_file=/etc/ssl/private/vsftpd.pem
ssl_enable=YES
allow_anon_ssl=NO
force_local_data_ssl=YES
force_local_logins_ssl=YES
ssl_tlsv1=YES
ssl_sslv2=NO
ssl_sslv3=NO

after setting up service is running properly but when i try to connect using filezilla i got some errors. iptables is stop working locally.
error -
Error:  GnuTLS error -50 in gnutls_priority_set_direct: The request is invalid.
Error:  Failed to initialize TLS.
Error:  Could not connect to server

my moto is to do so to avoid plain text authentication
i dont know where i am wrong please help me here.
Answer: Use another client. This is a bug in the Filezilla client.
Comment: i used ftp client with linux console & gftp then also getting regarding ssl

unable to configure vsftpd using ssl


Help with modulations identification: where they occur, and writing Roman numerals

Question: I'm currently a full-time music education major and need a lot of help on a project. The project is over Mozart's Fantasia in c minor, KV 475. We are to answer 20 questions along with writing all of the modulations and Roman numerals. I'm really struggling to find the correct modulations, and this causes problems with writing the Roman numerals. It's really hard to tell if the accidentals are embellishments or if they are actually a part of the modulation. If anyone can help, that would be great!
I am not able to post images, but the score can be found on IMSLP.
Comment: check cadencings, (ii-V7 progressions, vii dim7 and analyse pivot chords.
Comment: So on page 73 measure 36-44 I know it modulates but are measures 36-44 in the key of a minor? I wasn't sure because I'm struggling to write the Roman numerals.
Comment: If so what Roman numerals would you use measures 36-44? Then in measure 45 it modulates once again. Does it go to Bflat major?? Cause there's an f# consistently in measures 45-55.
Answer: Duration is a key to deciding whether something is a modulation  or not.
For example, in m. 2 the accidental-carrying chords -- and the chords they lead to -- suggest we could be looking at G major. But since the following measures clearly aren't G major, there's not enough to call this a modulation.
By contrast, in mm. 21-25, we see lots of F#s, A#s, and C#s, which comprise an F# major chord. Plus there are plenty of E#s, which is the leading-tone of F# major. Not only that, but there's a clear F# major cadence in m. 25. This better suggests a modulation, especially since the next four bars (at least), seem to continue in the same vein.
Comment: @Tim - The key signature of an excerpt does not necessarily reflect its true key. For example, the edition of the first movement of Beethoven's Appassionata Sonata I'm familiar with strips the key signature in the development, even though the development modulates to E Major and D Flat Major, among others.
Comment: Wonder if OP means, for instance, many bars in key G, thus G=I, then a modulation to, say, A, for say, 8 bars. Do the RNs call A= II, or call it A=I, since at that time the piece is effectively *in* key A?
Comment: Might be good to mention "tonicization" here as a concept vs modulation.
Comment: @tim - to answer your question you'd need to focus on how it *sounds*. Does it sound like a II, or does it sound like a I? RN job (like all theory) is to show how the music functions, not stuff it into arbitrary boxes. Tonicizations (and any functional harmony) are easily shown with RNA.
Comment: @jjmusicnotes - I guess if the key sig. stays as original, it would have to be called II.
Comment: @Tim - Irrespective of key signature, does it *sound* like a II?


The solution to the integral of $1/(x\ln x-C)$

Question: Solution to the integral of $$\int \frac{\Bbb dx}{x\ln x-C}$$ where $C>0$ is a constant.
I struggled to solve it but failed. I even doubt whether there is an analytical solution for this question.
The failed attempts are listed below:

Assuming $C=0$, it seems quite easy because
$$\int \frac{\Bbb dx}{x\ln x}=\int \frac{\Bbb d(\ln x)}{\ln x}=\ln(\ln x)$$
But $C>0$ makes this method less useful because
$$\int \frac{\Bbb dx}{x\ln x-C}=\int \frac{\Bbb d(\ln x)}{\ln x- \frac{C}{x}}$$
I don't know how to continue, so I stopped here.

Let $y(x)=x\ln x$ and $x(y)=y^{-1} (x)$, the integral becomes
$$\int \frac{\Bbb dx}{x\ln x-C}=\int \frac{\Bbb d(x(y))}{y-C}$$
but I guess there is no analytical formula for $x(y)$, so I can't solve $d(x(y))$ so I stopped again.

I noticed that
$$\int \frac{\Bbb dx}{x\ln x-C}=\frac{1}{1-C} \{ \int \frac{\Bbb d(x\ln x-C)}{x\ln x-C} - \int \frac{\Bbb \ln x dx}{x\ln x-C} \} =\frac{1}{1-C} \{ \ln (x\ln x-C) - \int \frac{\Bbb \ln x dx}{x\ln x-C} \}$$
Again I found that  $\int \frac{\Bbb \ln x dx}{x\ln x-C} $ seems hardly solvable when $C≠0$, so I stopped again.

Sorry for my poor mathematical capability, but I will be grateful if any math expert is willing to provide the solution and solving process.
Comment: Please remember to include your work. Can you explain your failed attempt?
Comment: I do not think there exists a analytical solution to this as per [wolfram](https://www.wolframalpha.com/input?i2d=true&i=Integrate%5BDivide%5B1%2CxLog%5Bx%5D-+C%5D%2Cx%5D). Did you check on it or some other mathematical site? It is showing me [this](https://i.stack.imgur.com/XqnwL.png).
Comment: $$\int \frac{1}{x \log (x)-c} \, dx=\sum _{m=0}^{\infty } -c^{-1-m} (1+m)^{-1-m} \cos (m \pi ) \Gamma (1+m,-((1+m) \log (x)))+C$$ for: $0\leq x\leq 1$
Comment: I agree with @HamLemon ... it is likely that this integral is not an elementary function.
Comment: Thanks to the advice from @ElectricShadow , and I add my works on it.
Comment: Thanks to @HamLemon , the solution from wolfram seems daunting! I checked a few other sites but none of them can solve this.
Comment: Thanks to @MariuszIwaniuk . It would be better if the solution can have a simpler form, but at this stage your answer seems the best.
Comment: Thanks to @GEdgar . It indeed seems uneasy to solve it.
Answer: Writing
$$\frac{1}{x \log (x)-c}=\sum_{n=0}^\infty \frac{c^n}{x^{n+1} \log^{n+1} (x)}$$
$$x=e^t \implies I_n=\int \frac{dx}{x^{n+1} \log^{n+1} (x)}=\int e^{-(n-1)t}\,t^{-n}\,dt$$
$$I_n= -t^{-(n-1)} \,E_n((n-1) t)$$ where appear the exponential integral function.
Comment: Thank you so much! It seems an ingenious and neat solution. At this stage I could only comment that the integral seems unsolvable unless we use sum of series.


Packer won't correctly use private key for SSH auth in provisioning step

Question: I use Packer to build VirtualBox images, with the Ansible provisioner to set up the images. The builder step creates a temporary user (ssh_username and ssh_password). The Ansible provisioner runs using this temporary user. I, of course, want to get rid of this user after it's set up our more secure public key-only user. So I added a second Ansible provisioning step that connects as the secure user and removes the insecure user. Or at least that was the plan. However, Ansible via packer is unable to actually connect to the VM using this method.
Here is the relevant portion of the packer.json file:
"provisioners": [
    {
        "type": "ansible",
        "playbook_file": "playbooks/image/image.yml",
        "groups": [
            "{{user `ansible_group`}}"
        ],
        "user": "vagrant",
        "extra_arguments": [
            "--vault-password-file", "scripts/get-vault-password.sh",
            "-e", "global_configuration_user={{user `configuration_user`}}",
            "-e", "global_deployment_user={{user `deployment_user`}}",
            "-e", "ansible_ssh_pass=vagrant",
            "-vvvvv"
        ]
    },
    {
        "type": "ansible",
        "playbook_file": "playbooks/image/removeVagrant.yml",
        "groups": [
            "{{user `ansible_group`}}"
        ],
        "user": "{{user `configuration_user`}}",
        "extra_arguments": [
            "--vault-password-file", "scripts/get-vault-password.sh",
            "-e", "global_configuration_user={{user `configuration_user`}}",
            "-e", "global_deployment_user={{user `deployment_user`}}",
            "-e", "ansible_ssh_private_key_file=~/.ssh/id_{{user `configuration_user`}}_rsa",
            "-vvvvv"
        ]
    }
],

The first provisioning step works without issue. It's the second one that fails with permission denied. Ansible is trying to execute the following SSH command:
ssh -vvv -C -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=no -o Port=37947 -o 'IdentityFile="/home/redacted/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=redacted -o ConnectTimeout=10 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ControlPath=/home/redacted/.ansible/cp/ansible-ssh-%h-%p-%r 127.0.0.1 '/bin/sh -c '"'"'( umask 77 && mkdir -p "` echo ~/.ansible/tmp/ansible-tmp-1491233126.24-276699777493633 `" && echo ansible-tmp-1491233126.24-276699777493633="` echo ~/.ansible/tmp/ansible-tmp-1491233126.24-276699777493633 `" ) && sleep 0'"'"''

The relevant part of the SSH debug output is:
debug1: SSH2_MSG_NEWKEYS received
debug2: key: /home/redacted/.ssh/id_rsa, explicit, agent
debug2: key: redacted
debug2: key: redacted
debug2: key: redacted
debug2: key: redacted
debug2: key: redacted
debug2: key: redacted
debug2: key: redacted
debug3: send packet: type 5
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug3: start over, passed a different list publickey
debug3: preferred gssapi-with-mic,gssapi-keyex,hostbased,publickey
debug3: authmethod_lookup publickey
debug3: remaining preferred: ,gssapi-keyex,hostbased,publickey
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/redacted/.ssh/id_rsa
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug1: Offering RSA public key: key2
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51

It then continues to try the remaining keys I have in my .ssh directory, which all fail, of course. The first one, the one that was requested, has already failed.
I ran Packer with -on-error=abort so that it would leave the VM up. I tried SSHing in with the same command, and I get a connection refused error. The reason for this, I discovered, is that it's trying to connect to an SSH proxy port that Packer sets up. So I use the actual forwarded port that is set up on the Virtualbox VM, and SSH connection succeeds. Thus, it appears that the problem lies with the SSH proxy. However, I'm not sure how to make it behave.
I also tried using the ssh_authorized_key_file option (https://www.packer.io/docs/provisioners/ansible.html) in my Packer configuration for the Ansible provisioner. In this case, I got a Packer error saying that it failed to parse the authorized key (source code is here: https://github.com/bhcleek/packer-provisioner-ansible/blob/master/provisioner/ansible/provisioner.go). It didn't tell me what the problem is. The Go documentation for the SSH library said that it's the standard SSH keyfile format. Or that's my best interpretation of it (https://godoc.org/golang.org/x/crypto/ssh#ParseAuthorizedKey).
Answer: I had this problem and was unable to get the Packer SSH-Proxy to behave successfully.
In order for packer to not create the temporary key, you need to either bake the "provisioning key" into the AMI or have it exist on AWS ahead of time.
If you follow option 1 - you need to provide both the ssh_private_key_file option to the builder config, as well as setting ssh_agent_auth to true - like so:
   "ssh_username": "ubuntu",
   "ssh_private_key_file": "../provision",
   "ssh_agent_auth": true,

If you follow option 2 - provide the ssh_keypair_name option to the builder.
In both cases, you'll need provide the user to the Ansible provisioner, but specified key pair should be used instead of the temporary one packer generates.
NB:  When I removed the user from the box using the Ansible provisioner it caused ansible to fail.  I suspect that this is because it's not possible to make ansible connect to the target machine without going through the proxy, and it's not possible to specify the proxy user in a provisioner.  I needed to perform the "Remove user and shutdown the machine" in a single async call.


Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

Question: I'm trying to return a table with the depth of a node in a hierarchy represented using the nested set model, I'm following this tutorial but the query used in the section 'Finding the depth of Nodes' doesn't work for me: http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
SELECT node.GroupName, (COUNT(parent.GroupName) - 1) AS depth
FROM CompanyGroup AS node,
        CompanyGroup AS parent
WHERE node.LeftID BETWEEN parent.LeftID AND parent.RightID
GROUP BY node.GroupName
ORDER BY node.LeftID;

Running this query I get the error "Column 'CompanyGroup.GroupName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."
Can anyone explain why please?
Edit: wrong column in the error message, my apologies the error is: "Column "CompanyGroup.LeftID" is invalid..."
Comment: Have you searched this error?
Comment: Is this the exact query you are running?
Answer: Try this one -
SELECT
      node.GroupName
    , depth = COUNT(parent.GroupName) - 1
FROM CompanyGroup node
JOIN CompanyGroup parent ON node.LeftID BETWEEN parent.LeftID AND parent.RightID
GROUP BY node.GroupName
ORDER BY MIN(node.LeftID) --<--

Or try this -
SELECT
      node.GroupName
    , depth = COUNT(parent.GroupName) - 1
FROM CompanyGroup node
JOIN CompanyGroup parent ON node.LeftID BETWEEN parent.LeftID AND parent.RightID
GROUP BY node.GroupName, node.LeftID
ORDER BY node.LeftID

Comment: @Jim Barton, when you use group by, each column in the select/order clause must be either defined via an aggregate function (like MAX, MIN, AVG, ...) or must be included in the group by clause.
Comment: That works, thanks. Out of interest could you explain the problem?
Comment: of course, I couldn't get the solutions in the posts I found to work for me so I opened a new question
Answer: Are you running a different query?  You should not be receiving that particular error, but rather something like "Column "CompanyGroup.LeftID" is invalid in the ORDER BY..."
This query should work:
SELECT node.GroupName, (COUNT(parent.GroupName) - 1) AS depth
FROM CompanyGroup AS node,
        CompanyGroup AS parent
WHERE node.LeftID BETWEEN parent.LeftID AND parent.RightID
GROUP BY node.GroupName
;

SQL Fiddle Demo
Answer: I don't think that this is the error you're receiving from the query you posted - are you sure you didn't mess it up?
Anyway, there's something else wrong here: you're using node.LeftID to order the results, but you can't od this. You should be receiving this message:
Column "node.LeftID" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.

Try removing ORDER BY and run it again.


Add to  tag of a cakePHP app

Question: I have an app where I need to call some JS in the onLoad event of the BODY tag of two forms.  However, I can't find how to modify the tag for just them.  Does anyone know?
Frank
Comment: Do you have app/views/layouts/default.ctp defined? If not, Cake uses the one in cake/ instead. You can add your own layout, and append your onload there if you like. Here's a link: http://www.geekdaily.net/2007/07/27/javascript-windowonload-is-bad-mkay/.
Answer: inkedmn certainly has provided the right answer for this case, but in general, you can "hand information up" like this:
(in views/controller/view.ctp)
$this->set('bodyAttr', 'onload="something"');

(in views/layouts/default.ctp)
<?php
    if (isset($bodyAttr)) {
        $bodyAttr = " $bodyAttr";
    } else {
        $bodyAttr = null;
    }
?>
<body<?php echo $bodyAttr; ?>>

I often use it like this to add extra classes to a "top level element":
<?php
    if (!isset($docClass)) {
        $docClass = null;
    }
?>
<div id="doc" class="<?php echo $docClass; ?>">

Comment: I do prefer setting values in the controller.
Comment: For something like classes I don't, as they're purely view-layer related.
Answer: You don't need to modify the body tag to have Javascript execute when the page loads. You could just include something like this in your layout where appropriate:
(jQuery)
$("body").load(
    function(){
        // do stuff when the body element is loaded.
    }
);

Or, if you want to have the code execute when the document.ready event fires:
$(function(){
        // do stuff when the document is ready
    }
);

Or, if you don't want to use jQuery, you could do something like this:
function doStuff(){
    // whatever you want to happen when the load completes
}

window.onload = dostuff;

Good luck - and please clarify your question if this answer isn't satisfactory.
Answer: I do the following:
We apply $ bodyLoad in my body
<body <? = (isset ($ bodyLoad)? 'onload = \''. $ bodyLoad.' \'',''); ?> >

Already in my [action]. Ctp, I do the following:
<? php $ this-> set ('bodyLoad', 'field.focus ();');?>

If you want you can also put this code in the controller.
Good luck

Add to  tag of a cakePHP app


Find $\int_{0}^{\frac{\pi}{2}} \frac{1}{1+\tan(x)^{\sqrt{2}}}dx$.

Question:
Find $\displaystyle \int_{0}^{\dfrac{\pi}{2}} \dfrac{1}{1+\tan(x)^{\sqrt{2}}}dx$.

I am told I should solve this by switching the limits, but I am unsure of the substitution I should use.
Comment: http://math.stackexchange.com/questions/605673/integrate-int-0-pi-2-frac11-tan-alphax-mathrmdx/605713#605713
Comment: This is very similar to [this question](http://math.stackexchange.com/questions/82489/how-to-compute-int-0-pi-2-frac-sin3-t-sin3-t-cos3-tdt). The same technique applies here.
Answer: You may observe that, by the change of variable $x \to \pi/2-x$, you get
$$I=\int_{0}^{\dfrac{\pi}{2}} \dfrac{1}{1+\tan(x)^{\sqrt{2}}}dx=\int_{0}^{\dfrac{\pi}{2}} \dfrac{1}{1+\frac1{\tan(x)^{\sqrt{2}}}}dx=\int_{0}^{\dfrac{\pi}{2}} \dfrac{\tan(x)^{\sqrt{2}}}{1+\tan(x)^{\sqrt{2}}}dx
$$ giving
$$
2I=I+I=\int_{0}^{\dfrac{\pi}{2}} \dfrac{1}{1+\tan(x)^{\sqrt{2}}}dx+\int_{0}^{\dfrac{\pi}{2}} \dfrac{\tan(x)^{\sqrt{2}}}{1+\tan(x)^{\sqrt{2}}}dx=\int_{0}^{\dfrac{\pi}{2}} dx=\frac{\pi}{2}
$$
 or
$$
I=\color{blue}{\frac{\pi}4}.
$$
Comment: Substitutions are typically taught using variable other than that being integrated with respect to. Thus this answer would be easier to understand if it said let $u = \frac{\pi}{2} - x$
Comment: @TannerCarawan Then $u$ is a new "dummy" variable, which we can change back to $x$.  So, we save ourselves a step by enforcing the substitution $x\mapsto \pi/2 - x$.
Comment: Olivier.   First, Happy New Year.  Now, I am just curious.  I posted my answer to this question nearly one month ago.  And today, my answer received two down votes?  Did you experience something similar?  - Mark
Comment: @Dr.MV Thanks. Happy New Year to you. "Did you experience something similar?": yes. Please have a look at my reputation points.
Comment: If both you and I received multiple down votes today, then it makes me wonder if there is a system error.
Comment: It's not only us. I thought it was someone with some malicious intent...
Answer: Let $I(\alpha)$ be given by
$$I(\alpha)=\int_0^{\pi/2}\frac{1}{1+\tan^{\alpha}x}\,dx \tag 1$$
Then, let $x \mapsto \pi/2-x$ so that $\tan (\pi/2 -x)\mapsto \cot x$, $dx \mapsto  -dx$, and the limits of integration go from $\pi/2$ to $0$.  Then we have
$$I(\alpha) = \int_0^{\pi/2}\frac{\tan^{\alpha }x}{1+\tan^{\alpha }x}\,dx \tag 2$$
Adding $(1)$ and $(2)$ and dividing by two reveals that
$$I(\alpha)=\frac12\int_0^{\pi/2} \frac{1+\tan^{\alpha}x}{1+\tan^{\alpha}x}\,dx=\frac{\pi}{4}$$
which is independent of $\alpha$!
Comment: Why did this receive two down votes after nearly one month after I posted it???  - Mark
Comment: Shall I delete my answer then? - Mark


Debugging .NET 2.0 Winforms application using Debugging Tools for Windows

Question: I support a .NET 2.0 Winforms application that is fairly widely deployed. On rare occasion we get a support call from a customer in which the application returns a .NET runtime exception AS SOON as you attempt to launch the application.
In the past we have helped the customer re-install the .net framework and very often that works...but occasionally not.
In such a situation could the Windows Debugging Tools be used to determine the cause of the problem.  If so would you HAVE to download debugging symbols to the target computer (want to avoid since that can be several hundred MBs of stuff to download to the target.)
Is this overkill for a .net app?  Any alternatives.  How would you go about debugging this.  Non-specific step-by-step would be appreciated.  Of course, this app is compiled as a RELEASE configuration on the target machine.  The customer will very likely NOT have dev tools installed or debugging tools.  We DO usually have remote control access to the computer.   To re-iterate.  This happens AS SOON AS the customer attempts to run the application and it fails immediately.
What is the quickest path to solving this problem for the customer?
Here is an example of a recent error from the Event Log.
EventType clr20r3.  .exe P2 2010.1.0.0, p3 4B857AFD P4  BLAH BLAH
system.invalidoperation, P10 NIL.
Source:  .NET Runtime 2.0 Error.
EventID:  5000
Thanks in advance.
Seth
Answer: Why not use that?
For customers' machine, you won't be able to do remote debugging. Therefore, it is recommended to capture crash dump for crashing and hang dumps for hang problems, and WinDbg or ADPlus.exe is very useful here.
Ask your end user to launch your application in WinDbg, and execute
<code>.dump /f path
</code>
to save a crash dump, then you can ask for the dump file and analyze the crash.
On target machine, no symbol is required. Symbols are useful when you analyze the crash dump on your own machine, and that's where things such as SOS are useful.
Of course there are other ways to get crash dumps,
http://blogs.msdn.com/lexli/archive/2009/08/23/when-the-application-program-crashes-on-windows.aspx
Comment: Adplus.vbs is obsolete. Please switch to ADPlus.exe in the same folder.
Comment: +1 for using adplus.vbs in crash mode. The debugging tools are a simple, small install, and you can write them a batch file to run adplus in crash mode.  We use this for customers who have problems we can't reproduce in-house
Comment: Lex
Thanks for your answer.  This is exactly the kind of answer I was hoping for.

You said "Ask your end user to launch you appliction in WinDbg, and execute .dump /f path"
Is it obvious how to do that?  How easy is it?  Can you give a brief step-by-step?  I take it the "path" is the path to the dump file.  In any case, perfect answer.  Will take a look now.  Seth
Comment: One other thing.  I found the following url...http://support.microsoft.com/kb/286350.  This seems to describe the vbs script that you say is deprecated.  Can you give an URL to the download for the EXE you mentioned?
Comment: One other thing.  That article specifically mentions that "If you must troubleshoot a program or process that quits unexpectedly during startup" that ADPLUS is not the best choice.  Also...any hints on analyzing the dump file?
Comment: As I already mentioned, Adplus.exe is in the same folder the contains ADplus.vbs (latest Debugging Tools installation).

Execute .dump /f path is not obvious. You can write a test application and play with it. (1. Launch WinDbg, 2. File|Open Executable..., After that you need to see what is displayed the debugger breaks and stops, and determine if that's the time to execute ".dump /f path" or "g".) Regards,
Answer: Edit: Just saw the "happens immediately on startup". Indeed WinDBG can help.
While the Debugging Tools for Windows are indeed mainly ment for native applications, they are usefull for managed applications as well. Not only are managed apps "native" in the end, when they execute, but there is also and in particular the SOS extension for WinDBG or CDB (if you prefer the command line).
Especially (mini-)dumps of crashed applications can be analyzed quite nicely with the SOS extension. If your application is complied in release or debug mode does not matter a whole lot, as long as you've got the matching symbol files (.PDB) at hand when analyzing a dump.
There is a whole lot information out there, way to much to talk about in this answer, but your best bet is searching for "windbg sos".
Concerning the example you gave

EventType clr20r3. .exe P2 2010.1.0.0,
  p3 4B857AFD P4 BLAH BLAH
  system.invalidoperation, P10 NIL.

it could be something else, but to me it looks like an uncaught exception in the .NET application - in this case a System.InvalidOperationException.
If you can get a minidump of the crashed application (look into the ADPlus tool, which is part of debugging tools to get a dump "on demand" or "on event"), then you can load that into WinDBG and use the SOS extensions (commands !clrstack, !dumpstack, !threads, etc.) to figure where that uncaught exception came from.
Answer: I don't think you want the "Windows Debugging Tools". Debugging symbols are for the OS, not the .NET Framework. (Reminder, your Windows.Forms application lives in the .NET Framework, not in the OS.)
Will "Remote Debugging" help at http://msdn.microsoft.com/en-us/library/y7f5zaaa.aspx?
I usually include a "StopSwitch", but this is not a requirement to enable JIT. (See "StopSwitch Stops Execution for Just-In-Time Debugging" at http://missico.spaces.live.com/blog/cns!7178D2C79BA0A7E3!309.entry) This allows my to enable the switch then attach to the running application when it hits the debugger stop statement.
You can debug the "release" builds. The release pdb are helpful for stack traces.
I had this problem before. I enable the StopSwitch, the check was the first line, but JIT was not launch because the problem occurred before the .NET Framework even loaded my application.
Comment: WinDbg can actually be used perfectly to debug .Net applications. Especially with the sos extension. See http://msdn.microsoft.com/en-us/library/bb190764.aspx
Answer: I wrote a blog post with some step by step instructions along with helpful URLs.
http://www.spearsofttech.com/2010/03/09/how-to-use-debugging-tools-for-windows-to-debug-a-net-application/
Seth


Transformar uma lista em um csv pandas em python

Question: Tenho o seguinte código que faz raspagem de dados de um site de leilão:
lista = []
for pagina in range(1,34):
    url = 'https://www.lance24h.com.br/DetalhesLances.php?Codigo=45919&Pagina={0}'.format(pagina)
    response = requests.get(url)
    html = response.content
    soup = BeautifulSoup(html,'lxml')
    lista = []
    for corpo in soup.find_all('tr'):
      lista.append(corpo.text.strip())

novo = []
for x in lista:
    item = x
    for y in ['\n', '\t','\r', '/', '.', '-', '(', ')']:
        item = item.replace(y, "")
    novo.append(item)

Então com retorno eu tendo o seguinte:
['DataValorUsuário',
 '13012021 22:03:02                    R$ 0,59                    Daniel de Santi',
 '13012021 22:03:02                    R$ 0,58                    lordschug',
 '13012021 22:02:50                    R$ 0,57                    socialdomarcos',
 '13012021 22:02:48                    R$ 0,56                    deiaxabs',
 '13012021 22:02:47                    R$ 0,55                    Daniel de Santi',
 '13012021 22:02:35                    R$ 0,54                    lordschug',
 '13012021 22:02:33                    R$ 0,53                    Daniel de Santi',
 '13012021 22:02:27                    R$ 0,52                    socialdomarcos',
 '13012021 22:02:23                    R$ 0,51                    Daniel de Santi',
 '13012021 22:02:11                    R$ 0,50                    lordschug',
 '13012021 22:02:04                    R$ 0,49                    socialdomarcos',
 '13012021 22:02:03                    R$ 0,48                    lordschug',
 '13012021 22:01:54                    R$ 0,47                    Daniel de Santi',
 '13012021 22:01:53                    R$ 0,46                    socialdomarcos',
 '13012021 22:01:42                    R$ 0,45                    lordschug',
 '13012021 22:01:32                    R$ 0,44                    socialdomarcos',
 '13012021 22:01:23                    R$ 0,43                    lordschug',...,]

Agora estou tentando transformar em um arquivo csv que tenha três colunas uma para a data outra para o lance e a última para o nome de quem deu o lance. Já tentei os seguinte códigos:
with open("lances.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(lista)

E tive o seguinte retorno
D,a,t,a,"
",V,a,l,o,r,"
",U,s,u,á,r,i,o
1,3,/,0,1,/,2,0,2,1, ,2,2,:,0,3,:,0,2, , , , , , , , ,"
","
","
", , , , , , , , , , , , ,R,$, ,0,",",5,9, , , , , , , , ,"
","
","
", , , , , , , , , , , , ,D,a,n,i,e,l, ,d,e, ,S,a,n,t,i
1,3,/,0,1,/,2,0,2,1, ,2,2,:,0,3,:,0,2, , , , , , , , ,"
","
","
", , , , , , , , , , , , ,R,$, ,0,",",5,8, , , , , , , , ,"
","
","
", , , , , , , , , , , , ,l,o,r,d,s,c,h,u,g
1,3,/,0,1,/,2,0,2,1, ,2,2,:,0,2,:,5,0, , , , , , , , ,"
","
","
", , , , , , , , , , , , ,R,$, ,0,",",5,7, , , , , , , , ,"
","
","
", , , , , , , , , , , , ,s,o,c,i,a,l,d,o,m,a,r,c,o,s
1,3,/,0,1,/,2,0,2,1, ,2,2,:,0,2,:,4,8, , , , , , , , ,"
","
","

Acredito que o problema está quando eu formato a lista para tirar caracteres indesejados, porém não sei como arrumar isso.
Answer: Defina os parametros na escrita que vai formatar da maneira que deseja
arquivo = open('novoarquivo.csv', 'w', newline='')
#parametros de acordo com os caracteres de escape
escrever= csv.writer(arquivo, delimiter='\t', lineterminator='\n\n')
escrever.writerow(list(range(1,20)) ) #exemplo de escrita
arquivo.close()


Buscar os dados dos últimos 7 dias a partir da data actual (2014-12-11 11:06:09)

Question: Após visualizar a essa pergunta, surgiu a seguinte dúvida que é, no caso que o campo date está no seguinte formato 2014-12-11 11:06:09, como fazer pra retornar apenas os últimos 7 dias?
Answer: Testei aqui e funcionou:
SELECT * FROM sua_tabela WHERE seu_campo
BETWEEN TIMESTAMP(DATE_SUB(NOW(), INTERVAL 7 day)) AND NOW();

Acredito que tenha um jeito mais fácil de fazer.
Answer: Faça assim:
SELECT * FROM sua_tabela WHERE seu_campo
BETWEEN date(date(now()) - 7) and date(now());


a doubt on differential of a map between Manifolds

Question: Let $F:N\rightarrow M$ be a $C^{\infty}$ map, At each point $p\in N$, the map $F$ induces a linear map of tangent spaces, called its differential at $p$,
$F_{*}:T_p N\rightarrow T_{F(p)}M$ as follows. $X_p\in T_pN$ then $F_{*}(X_p)$ is the tangent vector in $T_{F(p)}M$ defined by $$F_{*}((X_p))f=X_p(f\circ F)\in\mathbb{R}$$, I understand that a tangent vector $F_{*}(X_p)$ acts on a $C^{\infty}$ map on $M$, what is the role of $X_p=\sum_{i=1}^{n}a^{i}\partial/dx_i$ here in the definition?, where $\{\partial/dx_{i}\}_{i=1}^{n}$ are basis of tangent space at $p$ of $N$
well, let the basis for tangent space  at $F(p)$  of $M$ be $\{\partial/dy_i\}_{i=1}^{m}$, so then $F_{*}(X_p)=\sum_{i=1}^{m}b^i\partial/dy_i$
Comment: Exactly as below. The key point is that $f\circ F$ is a smooth function $N\to \mathbb{R}$. Since the derivative is local, you can choose a chart and represent the function $f\circ F$ as a map $\mathbb{R}^n\to \mathbb{R}$. In this form, what you wrote is just the standard directional derivative from calculus for a function $\mathbb{R}^n\to \mathbb{R}$ in the direction of $X_p$.
Answer: $X_p$ is a tangent vector in $T_pN$. It should read $$X_p = \sum_{i=1}^n \lambda_i(p) \frac{\partial}{\partial x^i}|_p$$
You somehow missed the coefficients. Applying this to $f$ is another way of stating that you take the derivative of $f$ wrt to that direction.
Answer: You should be carefull not to mix up$\partial$ with $d$. Usually one denotes a basis of $T_p M$ by $\{ \frac{\partial}{\partial x_i}|_p \}_i$ and with $\{ dx_i |_p \}_i$ the dual basis of  $\{ \frac{\partial}{\partial x_i}|_p \}_i$ of $(T_p M)^*$.
Now if you have $X_p = \sum_{i=1}^n a_i \frac{\partial}{\partial x_i}|_p$ where the $a_i$'s are constants you can write
$$F_{*}(X_p)=F_{*}(\sum_{i=1}^n a_i \frac{\partial}{\partial x_i}|_p)=\sum_{i=1}^n a_iF_{*}( \frac{\partial}{\partial x_i}|_p)$$
by the linearity of the differential. Furthermore:
$$F_{*}( \frac{\partial}{\partial x_i}|_p)=\sum_{j=1}^m \frac{\partial(y_j \circ F)}{\partial x_i}|_p)\frac{\partial}{\partial y_j}|_{F(p)}$$
$\{ \frac{\partial(y_j \circ F)}{\partial x_i} \}$ is called the jacobian of $F$.


Qual a maneira correta de usar o flush(); e sleep(); em um foreach?

Question: Fiz uma página em php para gerar um relatório de vendas no formato .csv através do WooCommerce no sistema WordPress.
<?php
//incluir as funções principais do WordPress
require("/home/site/public_html/wp-blog-header.php");
require_once("/home/site/public_html/wp-config.php");
require_once("/home/site/public_html/wp-includes/wp-db.php");
?>

<?php
$order_statuses = array( 'wc-completed');

$customer_orders = wc_get_orders( array (
    'date_completed' => '2020-09-14...2020-09-15',
    'meta_key' => '_customer_user',
    'post_status' => $order_statuses,
    'orderby' => 'date',
    'order' => 'ASC',
    'numberposts' => -1,
) );
$myfile1 = fopen("/home/site/public_html/shop/report/2020.csv", "w") or die("Erro ao abrir relatório!
");
fwrite($myfile1, "\"Data\",\"Pedido\",\"Item\",\"Categoria\",\"Quant.\",\"Valor\",\"Pagamento\",\"Usuário\"\r");
echo '

            Data
            Pedido
            Item
            Categoria
            Quant.
            Valor
            Pagamento
            Usuário

';

foreach($customer_orders as $order ){

    $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;

    foreach($order->get_items() as $item_id => $item){

    $product_id = method_exists( $item, 'get_product_id' ) ? $item->get_product_id() : $item['product_id'];

    if( method_exists( $item, 'get_data' ) ) {
         $item_data = $item->get_data();
         $pedido = $item_data['order_id'];
         $item_name = $item->get_name();
         $produto = $item_data['product_id'];
         $quantity = $item_data['quantity'];
         $total = $item_data['total'];
         $total=str_replace(".", ",", $total);
         $pgto=$order->payment_method_title;
         $order_date_modified=$order->date_completed;
         $data=date_format($order_date_modified, "d/m/Y H:i:s");
         $userid=$order->customer_user;
         $user_info = get_userdata($order->user_id);
         $usuario = $user_info->user_login;
         //$email=$order->billing_email;
    } else {
         $total = wc_get_order_item_meta( $item_id, '_line_total', true );
    }

        foreach( wp_get_post_terms( $produto, 'product_cat' ) as $term ){
            if( $term ){
                $categoria = $term->name;
            }
        }

        echo '
'.$data.'	';
        echo '#'.$pedido.'	';
        echo ''.$item_name.'	';
        echo ''.$categoria.'	';
        echo ''.$quantity.'	';
        echo ''.$total.'	';
        echo ''.$pgto.'	';
        echo ''.$usuario.'	';

        fwrite($myfile1,"\"$data\",\"$pedido\",\"$item_name\",\"$categoria\",\"$quantity\",\"$total\",\"$pgto\",\"$usuario\"\r");

        flush();
        sleep(1);

    }
}

fclose($myfile1);
echo '

';
?>

Adicionei o flush(); e sleep(1); após a gravação de cada linha no arquivo .csv, pois desejo que a tabela seja criada na página do navegador, conforme acontece no exemplo abaixo. onde uma linha aparece a cada segundo:
<?php

    for($i=1;$i<=10;$i++){
        echo 'processing...
';
        flush();
        sleep(1);
    }
?>

Porém a página que criei processa todas as informações de uma só vez e não aos poucos como esperado.
Estou buscando alternativas para gravar os dados sem receber um erro de timeout, pois quando executamos o script para puxar todos os pedidos deste ano o processo é simplesmente interrompido, algumas vezes mostra uma mensagem de timeout no navegador, mas não gera nenhum log de erro.
Comment: Como dá erro de timeout se o processo é interrompido sem erro?
Comment: @Woss me expliquei mal no último paragrafo, algumas vezes mostra uma mensagem de timeout no navegador, mas não gera nenhum log de erro.
Comment: Qual é o tempo máximo para dar timeout que está configurado no servidor?
Comment: @Woss no php.ini está como 'max_execution_time = 5000000', mesmo assim a mensagem "Request Timeout" aparece após 2 minutos de execução
Answer: Em teoria seu script poderia funcionar, mas no manual php explica que muitos servidores não realizam o envio da página até que todo o script tenha sido concluído, mesmo você guardando em buffer parte do código.
A explicação está neste link:
manual flush
Uma solução para isto seria utilizar ajax para ir carregando partes da tela a cada segundo, ou carregar toda a tela com a maior parte oculta e ir exibindo com javascript (display:none => display:block) aos poucos. Particularmente eu escolheria a segunda opção.
Comment: Li alguns artigos para aprender como utilizar o ajax, mas não consegui entender como funcionava e não consegui aplicar no meu script atual. Sobre ir mostrando aos poucos o resultado na tela, nem é importante, no final acabarei trabalhando só com o arquivo .csv criado. Continuarei buscando mais informações sobre ajax pra tentar aplicar aqui, obrigado desde já.
Comment: o que ajuda bastante é a biblioteca jquery que facilita bastante o trabalho com ajax
Comment: obrigado pelas informações, ainda não consegui algo 100%, no servidor tem algo interrompendo a execução da página com 120 segundos apenas quando incluo os arquivos de configuração do wordpress
Comment: se continua usando o flush para despejar buffer a cada 1 segundo você acaba atingindo o limite de tempo de execução da página.
Você pode usar a função set_time_limit() para modificar o tempo, mas ainda não acho que esta seja a melhor solução. O ideal é verificar de tempos em tempos com o ajax e usar appped() do javascript para adicionar os campos novos


String code reduction using single regex

Question: I am using these two regex statement. I want to use only one regex rule to reduce code for all type of spaces that come
strTestIn = strTestIn.replaceAll("[ ]+", " ");
strTestIn = strTestIn.replaceAll("(\\t)+", " ");

what regex I need to use for that??
Answer: strTestIn = strTestIn.replaceAll("\\s+", " ");

See the Pattern class
\s matches whitespace character: [ \t\n\x0B\f\r]
Comment: @Јοеу: not quite sure, I copied that sentence from the documentation. I think it would. You could test that.


Continuous Bag of Words derivation

Question: The continuous bag of words model has the following log probability for observing a sequence of words: $$\log P(\textbf{w})=\sum_{c=1}^{C}\log{P(w_c|w_{c-m},...w_{c-1}, w_{c+1},...,w_{c+m}})$$
I don't fully understand this. Probabilistically, shouln't it be define as:
$$\log P(\textbf{w})=\sum_{c=1}^{C}\log{P(w_c|w_{c-1},...w_{1}, w_{0}})$$
as it is defined with other language models?
Answer: This is how the continuous bag of words is defined. It is not a language model but a model for training word embeddings.
Continuous means having a (small) sliding window over the training corpus. The bag of words part means that the model disregards the order of the words in the context window. Neither of these features is particularly good for language modeling where the order of words matters, and the longer the context, the better.
One way to view Word2Vec training objectives is that you know that language modeling provides a good training signal for word embeddings. However, it is too computationally expensive when you only care about the embeddings. You want a solution that scales for hundreds of thousands of word forms when computing on the CPU. The solution is to simplify the language modeling objective as much as possible while still getting a reasonable training signal for the embeddings, which leads to CBOW and Skip-gram.

Continuous Bag of Words derivation