Python multi-line strings breaks Vim's indent folding

Question: Python's string-literal juxtaposition makes multi-line strings much easier and prettier to write, but when I'm four or five indents deep and want to use the entire row (leading whitespace does not matter), Vim's foldmethod=indent breaks down.
For example:
def getQuotation():
    print "Fetching quotation from the absolutely useless function."
    return ("Four score and seven years ago our fathers brought forth, "
"upon this continent, a new nation, conceived in liberty, and dedicated "
"to the proposition that \"all men are created equal\"")

should be folded as this:
def getQuotation():
+--  4 lines: print "Fetching quotation from the absolutely useless function."--

but instead I get this:
def getQuotation():
+--  2 lines: print "Fetching quotation from the absolutely useless function."--
"upon this continent, a new nation, conceived in liberty, and dedicated "
"to the proposition that \"all men are created equal\"")

I tried setting foldignore=\", but to no avail. Vim's help foldignore offers this to say on the subject:

Used only when 'foldmethod' is "indent".  Lines starting with
  characters in 'foldignore' will get their fold level from surrounding
  lines.  White space is skipped before checking for this character.

Is there something obvious that I'm missing, or will I have to resort to foldmethod=expr, base the foldlevel on the indent, and except the corner cases myself?
EDIT: I've made at least some headway; it turns out that if I add a non-empty line after the strings and "refresh" the indent with set fdm=indent, then the block folds as it's supposed to. Even an empty comment (#) is enough.
Comment: That's not a multiline string, that's implicit string concatenation with several substrings. Why don't you try using actual multiline strings, utilizing the line continuation character `\ ` at the end of each section to have on one line in code? Don't know if that will help you, but it's worth a try. ...What the heck, backslash+backtick is an escape code in comments?
Comment: @JAB: You're right, it's not technically a multi-line string. But your proposed solution doesn't address the issue, which is that vim's folding would still require me to pad out each line to the same indent level, which is not acceptable.
Comment: Have you tried `foldmethod=syntax` instead, and doing `set filetype=python`? `foldmethod=indent` bases folds on indents as the name suggests, so isn't particularly smart when it comes to language specific things.
Comment: @actionshrimp: I was using the syntax folding before, but it just wasn't nearly as effective as indent and defined folds (usually) over broader ranges than I would have liked.
Comment: Since it's not a solution for using Vim's indent folding I'm posting it as a comment... I'm using python_ifold plugin (http://www.vim.org/scripts/script.php?script_id=2002) and the described behavior doesn't happen. Maybe you should try it. If you consider it as a solution I can repost it with more informations and details.
Comment: @Magnun Leno: This only works because it folds functions and classes, nothing else. I did give it a fair shot by modifying the code to also parse for `if`, `elif`, and `else` statements, but that still leaves the problem of the string indent unsolved.
Comment: @kpsfire: Actually my suggestion would be even worse because with the multiple literals, the whitespace wouldn't matter, but it would be kept in the string with my suggestion. I find it interesting that you consider padding each line to the same indent level to be unacceptable, though; personally, when I have multiple lines of code enclosed in brackets or parentheses, I generally align the successive lines with the opening bracket/parenthesis of the first line. It helps indicate that the multiple lines are still part of a single enclosed section. Then again, I also tend to use IDEs/editors...
Comment: ...that support auto-indentation.
Comment: Ah, I agree with you as far as aligning based on the indent, but if I'm already a few indents in, formatting a long string becomes very confined. For example, left-padded with 24 spaces (six standard Python indent levels in) leaves only 54 characters on each line to fill with a string (textwidth=79), rather than utilizing the full line.
Answer:
Is there something obvious that I'm missing, or will I have to resort to foldmethod=expr, base the foldlevel on the indent, and except the corner cases myself?

Short answer: you can't do this with foldmethod=indent, but I found something you can use with foldmethod=expr, so no need to reinvent the wheel.  See the long answer.
Long answer
Just a brief review of how foldmethod=indent works...

Look for text shifted shiftwidth with whitespace from the edge of the page
Insert a new foldlevel
De-indenting takes you down foldlevels

Since the text you have is justified at the edge of the screen, anything involving shiftwidth is eventually broken unless you hack it up as you did.
I looked at several different .vimrc configurations before I found something that would work.  For a cleaner solution than foldmethod=indent, use foldmethod=expr with the ~/.vimrc I have below.  I found it in jneb's bitbucket python-fold repo
As a test, I built a few more cases into your example...
class testclass(object):
    def __init__(self):
        self.testit = None
    def __repr__(self):
        return "guacamole"

def foobarme():
    assert False
    return 42

def getQuotation():
    print "Fetching quotation from the absolutely useless function."
    return ("Four score and seven years ago our fathers brought forth, "
"upon this continent, a new nation, conceived in liberty, and dedicated "
"to the proposition that \"all men are created equal\"")

Using python-fold at the bottom of my ~/.vimrc yields:

And when I hit zR to unfold:

FYI, I use Dmitry Vasiliev's python.vim in  ~/.vim/syntax/python.vim for python syntax highlights.
I copied jneb's vim script below in case the bitbucket repo disappears...

" Fold routines for python code, version 3.2
" Source: http://www.vim.org/scripts/script.php?script_id=2527
" Last Change: 2009 Feb 25
" Author: Jurjen Bos
" Bug fixes and helpful comments: Grissiom, David Froger, Andrew McNabb

" Principles:
" - a def/class starts a fold
" a line with indent less than the previous def/class ends a fold
" empty lines and comment lines are linked to the previous fold
" comment lines outside a def/class are never folded
" other lines outside a def/class are folded together as a group
" for algorithm, see bottom of script

" - optionally, you can get empty lines between folds, see (***)
" - another option is to ignore non-python files see (**)
" - you can also modify the def/class check,
"    allowing for multiline def and class definitions see (*)

" Note for vim 7 users:
" Vim 6 line numbers always take 8 columns, while vim 7 has a numberwidth variable
" you can change the 8 below to &numberwidth if you have vim 7,
" this is only really useful when you plan to use more than 8 columns (i.e. never)

" Note for masochists trying to read this:
" I wanted to keep the functions short, so I replaced occurences of
" if condition
"     statement
" by
" if condition | statement
" wherever I found that useful

" (*)
" class definitions are supposed to ontain a colon on the same line.
" function definitions are *not* required to have a colon, to allow for multiline defs.
" I you disagree, use instead of the pattern '^\s*\(class\s.*:\|def\s\)'
" to enforce : for defs:                     '^\s*\(class\|def\)\s.*:'
" you'll have to do this in two places.
let s:defpat = '^\s*\(@\|class\s.*:\|def\s\)'

" (**) Ignore non-python files
" Commented out because some python files are not recognized by Vim
"if &filetype != 'python'
"    finish
"endif

setlocal foldmethod=expr
setlocal foldexpr=GetPythonFold(v:lnum)
setlocal foldtext=PythonFoldText()

function! PythonFoldText()
  let fs = v:foldstart
  while getline(fs) =~ '^\s*@' | let fs = nextnonblank(fs + 1)
  endwhile
  let line = getline(fs)
  let nnum = nextnonblank(fs + 1)
  let nextline = getline(nnum)
  "get the document string: next line is ''' or """
  if nextline =~ "^\\s\\+[\"']\\{3}\\s*$"
      let line = line . " " . matchstr(getline(nextnonblank(nnum + 1)), '^\s*\zs.*\ze$')
  "next line starts with qoutes, and has text
  elseif nextline =~ "^\\s\\+[\"']\\{1,3}"
      let line = line." ".matchstr(nextline, "^\\s\\+[\"']\\{1,3}\\zs.\\{-}\\ze['\"]\\{0,3}$")
  elseif nextline =~ '^\s\+pass\s*$'
    let line = line . ' pass'
  endif
  "compute the width of the visible part of the window (see Note above)
  let w = winwidth(0) - &foldcolumn - (&number ? 8 : 0)
  let size = 1 + v:foldend - v:foldstart
  "compute expansion string
  let spcs = '................'
  while strlen(spcs) < w | let spcs = spcs . spcs
  endwhile
  "expand tabs (mail me if you have tabstop>10)
  let onetab = strpart('          ', 0, &tabstop)
  let line = substitute(line, '\t', onetab, 'g')
  return strpart(line.spcs, 0, w-strlen(size)-7).'.'.size.' lines'
endfunction

function! GetBlockIndent(lnum)
    " Auxiliary function; determines the indent level of the surrounding def/class
    " "global" lines are level 0, first def &shiftwidth, and so on
    " scan backwards for class/def that is shallower or equal
    let ind = 100
    let p = a:lnum+1
    while indent(p) >= 0
        let p = p - 1
        " skip empty and comment lines
        if getline(p) =~ '^$\|^\s*#' | continue
        " zero-level regular line
        elseif indent(p) == 0 | return 0
        " skip deeper or equal lines
        elseif indent(p) >= ind || getline(p) =~ '^$\|^\s*#' | continue
        " indent is strictly less at this point: check for def/class
        elseif getline(p) =~ s:defpat && getline(p) !~ '^\s*@'
            " level is one more than this def/class
            return indent(p) + &shiftwidth
        endif
        " shallower line that is neither class nor def: continue search at new level
        let ind = indent(p)
    endwhile
    "beginning of file
    return 0
endfunction

" Clever debug code, use to display text for a given moment the statement is executed:
" call PrintIfCount(6, "Line: ".a:lnum.", indent: ".ind.", previous indent: ".pind)
let s:counter=0
function! PrintIfCount(n,t)
    "Print text the nth time this function is called
    let s:counter = s:counter+1
    if s:counter==a:n | echo a:t
    endif
endfunction

function! GetPythonFold(lnum)
    " Determine folding level in Python source (see "higher foldlevel theory" below)
    let line = getline(a:lnum)
    let ind = indent(a:lnum)
    " Case D***: class and def start a fold
    " If previous line is @, it is not the first
    if line =~ s:defpat && getline(prevnonblank(a:lnum-1)) !~ '^\s*@'
        " let's see if this range of 0 or more @'s end in a class/def
        let n = a:lnum
        while getline(n) =~ '^\s*@' | let n = nextnonblank(n + 1)
        endwhile
        " yes, we have a match: this is the first of a real def/class with decorators
        if getline(n) =~ s:defpat
            return ">".(ind/&shiftwidth+1)
        endif
    " Case E***: empty lines fold with previous
    " (***) change '=' to -1 if you want empty lines/comment out of a fold
    elseif line == '' | return '='
    endif
    " now we need the indent from previous
    let p = prevnonblank(a:lnum-1)
    while p>0 && getline(p) =~ '^\s*#' | let p = prevnonblank(p-1)
    endwhile
    let pind = indent(p)
    " If previous was definition: count as one level deeper
    if getline(p) =~ s:defpat && getline(prevnonblank(a:lnum - 1)) !~ '^\s*@'
        let pind = pind + &shiftwidth
    " if begin of file: take zero
    elseif p==0 | let pind = 0
    endif
    " Case S*=* and C*=*: indent equal
    if ind>0 && ind==pind | return '='
    " Case S*>* and C*>*: indent increase
    elseif ind>pind | return '='
    " All cases with 0 indent
    elseif ind==0
        " Case C*=0*: separate global code blocks
        if pind==0 && line =~ '^#' | return 0
        " Case S*<0* and S*=0*: global code
        elseif line !~'^#'
            " TODO: here we need to check GetBlockIndent(a:lnum) for version 3.3
            " Case S*<0*: new global statement if/while/for/try/with
            if 0<pind && line!~'^else\s*:\|^except.*:\|^elif.*:\|^finally\s*:' | return '>1'
            " Case S*=0*, after level 0 comment
            elseif 0==pind && getline(prevnonblank(a:lnum-1)) =~ '^\s*#' | return '>1'
            " Case S*=0*, other, stay 1
            else | return '='
            endif
        endif
        " Case C*<0= and C*<0<: compute next indent
        let n = nextnonblank(a:lnum+1)
        while n>0 && getline(n) =~'^\s*#' | let n = nextnonblank(n+1)
        endwhile
        " Case C*<0=: split definitions
        if indent(n)==0 | return 0
        " Case C*<0<: shallow comment
        else | return -1
        end
    endif
    " now we really need to compute the actual fold indent
    " do the hard computation
    let blockindent = GetBlockIndent(a:lnum)
    " Case SG<* and CG<*: global code, level 1
    if blockindent==0 | return 1
    endif
    " now we need the indent from next
    let n = nextnonblank(a:lnum+1)
    while n>0 && getline(n) =~'^\s*#' | let n = nextnonblank(n+1)
    endwhile
    let nind = indent(n)
    " Case CR<= and CR<>
    endif
    if line =~ '^\s*#' && ind>=nind | return -1
    " Case CR<<: return next indent
    elseif line =~ '^\s*#' | return nind / &shiftwidth
    " Case SR<*: return actual indent
    else | return blockindent / &shiftwidth
    endif
endfunction

" higher foldlevel theory
" There are five kinds of statements: S (code), D (def/class), E (empty), C (comment)

" Note that a decorator statement (beginning with @) counts as definition,
" but that of a sequence of @,@,@,def only the first one counts
" This means that a definiion only counts if not preceded by a decorator

" There are two kinds of folds: R (regular), G (global statements)

" There are five indent situations with respect to the previous non-emtpy non-comment line:
" > (indent), < (dedent), = (same); < and = combine with 0 (indent is zero)
" Note: if the previous line is class/def, its indent is interpreted as one higher

" There are three indent situations with respect to the next (non-E non-C) line:
" > (dedent), < (indent), = (same)

" Situations (in order of the script):
" stat  fold prev   next
" SDEC  RG   ><=00  ><=
" D     *    *      *     begin fold level if previous is not @: '>'.ind/&sw+1
" E     *    *      *     keep with previous: '='
" S     *    =      *     stays the same: '='
" C     *    =      *     combine with previous: '='
" S     *    >      *     stays the same: '='
" C     *    >      *     combine with previous: '='
" C     *    =0     *     separate blocks: 0
" S     *    <0     *     becomes new level 1: >1 (except except/else: 1)
" S     *    =0     *     stays 1: '=' (after level 0 comment: '>1')
" C     *    <0     =     split definitions: 0
" C     *    <0     <     shallow comment: -1
" C     *    <0     >     [never occurs]
" S     G    <      *     global, not the first: 1
" C     G    <      *     indent isn't 0: 1
" C     R    <      =     foldlevel as computed for next line: -1
" C     R    <      >     foldlevel as computed for next line: -1
" S     R    <      *     compute foldlevel the hard way: use function
" C     R    <      <     foldlevel as computed for this line: use function

Comment: This is a brilliant find, thank you so much! I'm still a little astonished that you went to the trouble of not only locating a vimscript that did the trick, but also implementing a test case and posting screenshots of the answer.

Thank you, thank you, thank you.
Answer: You can use python-mode along with FastFold. Python-mode has solved a lot of the problems with folding, and FastFold improves folding speed.


Download pdf programmatically

Question: How can I download a PDF and store to disk using vb.NET or C#?
The URL (of the PDF) has some rediection going on before the final PDF is reached.
I tried the below but the PDF seems corrupted when I attempt to open locally,
Dim PdfFile As FileStream = File.OpenWrite(saveTo)
Dim PdfStream As MemoryStream = GetFileStream(pdfURL)
PdfStream.WriteTo(PdfFile)
PdfStream.Flush()
PdfStream.Close()
PdfFile.Flush()
PdfFile.Close()

Comment: Can you show the GetFileStream() function as well?
Comment: There's no need to call Flush() if you're going to call Close().
Comment: Is the pdf itself corrupt? The code I posted works for the IRS provided pdf. Other setup I can think of is to use the WebClients DownloadData method and writing the byte[] to disk then.
Comment: Well, the pdf size is 4kb so it's definetely not downloaded properly.
Comment: Ok, the problem seems to be the redirection. If I hard code the end url (the url of the pdf after redirection completes) then it works (using downloaddata method).

Trouble is how do I ensure that the document is downloaded after redirection completes??
Comment: The initial url is:

http://www.blahblah.com/NLAAPI.dll/GetObject?ObjectID=34972180

And after a second or two it redirects to:

http://www.blahblah.com/PDFs/BRABB39.PDF
Comment: If its a script based redirect you will probably have to do some html parsing or something to extract the location its redirecting to.
Comment: Ok, so I looked at the contents of the requested url and it is basically a login page. When I browse the link with my broswer I do not get prompted for login because of a cookie, but I guess requesting the page through this code does not take into account the cookies on my machine.

So...

Is there a way to attach the cookie to webclient request?

Or

Can I (after posting the crdentials programmtically) then somehow get the resulting HttpWebResponse saved to a file??

Many thanks.
Comment: Using CookieContainer with WebClient class: http://stackoverflow.com/questions/1777221/using-cookiecontainer-with-webclient-class and apparently the WebClient class follows redirections: http://www.eggheadcafe.com/tutorials/csharp/70511872-c3aa-4e92-a7d7-dd4b09881af5/make-the-webclient-class-follow-redirects-and-get-target-url.aspx although I couldn't find that in the MSDN documentation.
Answer: You can try to use the WebClient (System.Net namespace) class to do this which will avoid any stream work on your side.
The following C# code grabs an IRS form and saves it to C:\Temp.pdf.
using(WebClient client = new WebClient())
{
    client.DownloadFile("http://www.irs.gov/pub/irs-pdf/fw4.pdf", @"C:\Temp.pdf");
}

Comment: Tried that, opening pdf I get....
"Adobe Reader could not open file because it is either not a supported file type or because the file has been damaged blah blah"
Comment: This can work. and make sure u set security permission to IISUSER if you are putting ur code for web page.
Comment: GetFileStream function:
Protected Function GetFileStream(ByVal URL As String) As MemoryStream
 Dim _url As String = URL
 Dim _wb As WebClient = New WebClient
 Dim myBuffer() As Byte
 Dim _str As MemoryStream = Nothing
 Try
 myBuffer = _wb.DownloadData(_url)
 _str = New MemoryStream(myBuffer)
 Catch ex As Exception
 _str = Nothing
 End Try
 Return _str
End Function
Answer: You can also try the following code sample to download pdf files
 Response.ContentType = "Application/pdf";
 Response.AppendHeader("Content-Disposition", "attachment; filename=Test_PDF.pdf");
 Response.TransmitFile(Server.MapPath("~/Files/Test_PDF.pdf"));
 Response.End();

Answer: How might you be able to use client.downloadfile when the URL is pointing a "showdocument.aspx" page.
Example:
https://gaming.nv.gov/modules/showdocument.aspx?documentid=246

Download pdf programmatically


How do I avoid saving usernames and passwords in PowerShell scripts

Question: So basically I want to write a Powershell script which will export the last 1days worth of Backup Logs for Windows Server Backup, format the info into a nice little table, then SMTP send it to an external location outside of the customers local Exchange. I have a smarthost I can use for this purpose, and the credentials etc.
But I don't want to store the UN and Password in the Powershell in plain text, or have the script running using the credentials in plain text.
Is there a way around this?
Cheers!
Comment: See the answer to this SO question:  http://stackoverflow.com/questions/13842611/how-to-pass-credentials-to-rename-command/13844113#13844113
Comment: how are you going to run it? manually, as a scheduled task? With manual, you could ask for input(and use `-assecurestring` to "hide" password input). With Task Scheduler, you can assign credentials to run the job/task, so you just input Your account information when you configure it. Consider creating an non-personal account With Limited rights for scripts like this.
Answer: I have managed to get around similar problems by taking the password as a secure string and saving it, as an "encrypted standard string" to a file named something like "Account.User.pwd" where Account is the name of the account associated with the password and User is the user who generated the secure string (only this user will be able to decrypt that file).
This is pretty similar to the approach used by @Keith if you follow the link in his comment on the question itself above. The approach below is a little easier to follow as it doesn't play directly with the <code>[System.Runtime.InteropServices.Marshal]</code> class.
Converting the password back from the contents of the file is more involved, but here is an example that steps through the process:
<code># Create credential object by prompting user for data
$Credential = Get-Credential

# Encrypt the password to disk
$Credential.Password | ConvertFrom-SecureString | Out-File Account.User.pwd

# Now to read it back again...
$SecureString = Get-Content Account.User.pwd | ConvertTo-SecureString

# Create credential object programmatically
$NewCred = New-Object System.Management.Automation.PSCredential("Account",$SecureString)

# Reveal the password!
$NewCred.GetNetworkCredential().Password
</code>
Thoughts about this approach:

Resist the temptation to dump the password into a variable at the final step to prevent it hanging around in memory (in cleartext) until the variable is trashed. It doesn't cost much typing to convert from the PSCredential each time.
Only the user who generates the file can read it; if multiple users need access to the password for a shared account, each will have to generate such a file (hence the suggested file naming).
This doesn't need to be limited to just passwords. ANY string you want to encrypt to disk could be used as the "password" in the original credential object. Database connection strings, esp. those with username and passwords in them, come to mind...
Use file-system security/ACLs to lock unwanted people away from the pwd file.
Having a file on disk with a password, even if it is an encrypted string, may not be to people's liking. Short of using a third-party password management system, this is a distinct improvement on using only file-system security with a clear-text file. You know it happens...

More information:

ConvertFrom-SecureString
ConvertTo-SecureString
PSCredential class
System.Runtime.InteropServices.Marshal class
How secure is PowerShell's ConvertFrom-SecureString -key

powershell credentials securestring


code to count columns

Question: How do I select the last column from second row and move the cursor one cell above.
For eg. if I am at cell A2, how do I make macro to count the number of columns starting from Row 2 and select the cell above it.
Answer: The following will count the number of columns on row 2 and then select the cell above that one:
Sub foo()
    Dim Lastcol As Long
    Dim ws As Worksheet: Set ws = Sheets("Sheet1")
    'declare and set your worksheet, amend as required
    Lastcol = ws.Cells(2, ws.Columns.Count).End(xlToLeft).Column
    'above count the columns on row 2
    ws.Cells(1, Lastcol).Select
End Sub

Similarly to Count the number of Rows on a given column:
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'get the last row with data on Column A

Comment: Thank you so much. this is really helpful.
Answer: to "select the last column from second row and move the cursor one cell above", just use
Cells(2, Columns.Count).End(xlToLeft).Offset(-1).Select

of course, what above is implicitly referring to currently active worksheet in currently active workbook
Comment: Thank you so much. This is really helpful.

code to count columns


How to prevent caching of field element data in custom field formatter?

Question: I have a custom field formatter that performs dynamic calculations to determine the output. However, for anonymous user's the previous data is always stored until a cache clear is performed.
in the field formatter viewElements() function I have the $elements #cache max-age set to 0. I thought this would resolve the issue but it does not. Am I missing something?
 public function viewElements(FieldItemListInterface $items, $langcode) {

    $elements = [];

    foreach ($this->getEntitiesToView($items, $langcode) as $delta => $file) {
      // Check if gate cookie is set

      if (isset($_COOKIE['Drupal_visitor_resource_gate'])){

        //$tags = $file->getCacheTags();
        //Cache::invalidateTags($tags);
        $item = $file->_referringItem;

        $elements[$delta] = [
          '#theme' => 'file_link',
          '#file' => $file,
          '#description' => $this->getSetting('use_description_as_link_text') ? $item->description : NULL,
          '#cache' => [
            'max-age' => 0,
          ],
        ];

        // Pass field item attributes to the theme function.
        if (isset($item->_attributes)) {
          $elements[$delta] += ['#attributes' => []];
          $elements[$delta]['#attributes'] += $item->_attributes;
          // Unset field item attributes since they have been included in the
          // formatter output and should not be rendered in the field template.
          unset($item->_attributes);
        }
        $elements['#cache']['max-age'] = 0;
        return $elements;
      }else{
...
}

Answer: Can you try adding:
\Drupal::service('page_cache_kill_switch')->trigger();
At the beginning of the viewElements function before the foreach loop?
Another thing to try is to set the following also:
$elements['#cache']['max-age'] = 0;
$elements['#cache']['contexts'] = [];
$elements['#cache']['tags'] = [];`

Comment: Thank you! Adding: \Drupal::service('page_cache_kill_switch')->trigger(); seems to have resolved my issue.
Answer: For anonymous traffic in general there are probably better solutions client-side. If you want to build this server-side in Drupal then better use a session, this will pass the built in page cache for anonymous traffic.
If you want to handle your own cookies you have to uninstall the Internal Page Cache and cache the pages only in the Internal Dynamic Page Cache. Then for better caching performance set a cache context for the cookie instead of max-age:
  $elements['#cache']['contexts'][] = 'cookies:Drupal_visitor_resource_gate';

Answer: The caching is done per entity not per field.
Depending on your use case you might want to consider excluding specific content types from caching or specific nodes
function MODULENAME_node_view(array &$build, NodeInterface $node, $display, $view_mode) {
  // for specific Content types
  if ($node->getType() == 'CONTENTTYPE' && $view_mode == 'full') {
    $build['#cache']['max-age'] = 0;
  }

  // for specific nodes
  if ($node->id() == xxx ) {
    $build['#cache']['max-age'] = 0;
  }
}

or can even try the cache exclude module


Como Retornar Erro de chave Primária já existente em PHP/MySQL?

Question: Boa tarde.
Como retornar um erro quando há uma tentativa de inserção de linha em uma tabela, e a chave primária já existir? Por padrão, o banco de dados não insere a linha. Como mostrar esse erro como "Item já existente"?
Segue parte do cógido:
$mysqli = new mysqli('localhost', 'root', '', 'datalin');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$inclui="INSERT INTO DTC (DTC_CDRDES,DTC_CGC,DTC_TIPDOC,DTC_NUMNFC,DTC_QTDVOL,DTC_DATREC,DTC_PROCES,DTC_FORNEC) VALUES ('$CDRDES','$CNPJ','$TipDoc','$NumNFC','$QTDVol','$DataRec','$proces','$FORNEC')";

mysqli_query($mysqli,$inclui);

if($inclui):
    echo "";
else:
    echo "";
endif;//echo "Cadastro realizado com sucesso!
Agradecemos a atenção.";

mysqli_close($mysqli);

Desde já agradeço a ajuda.
Answer: Use a função mysqli_error(). Aproveito para corrigir um erro de lógica do seu código, seu if($inclui) sempre vai dar true.
$sql="INSERT INTO DTC (DTC_CDRDES,DTC_CGC,DTC_TIPDOC,DTC_NUMNFC,DTC_QTDVOL,DTC_DATREC,DTC_PROCES,DTC_FORNEC) VALUES ('$CDRDES','$CNPJ','$TipDoc','$NumNFC','$QTDVol','$DataRec','$proces','$FORNEC')";

// mysqli_query retorna false se falhar
$sucesso = mysqli_query($mysqli, $sql);

if(!$sucesso) {
    echo mysqli_error($mysqli);
}

Comment: Obrigado pela resposta. Funcionou colocando if($sucesso) sem o "!".
Comment: O `!` é uma negação. Sem isso, vai entrar no `if` quando a query executar sem problemas. Com a exclamação, só entra quando der problema (que pode ser violação de chave primária, precisa olhar a mensagem de erro pra ter certeza).


Upload com ASP.NET Core json vs formdata

Question: Estou usando webapi do asp.net core, inicialmente minhas actions estavam utilizando o atributo [FromBody] nos parametros, assim eu resgatava o valor json enviado pelo front-end. Agora estou implementando uma tela que tem upload, e tive que utilizar formdata para enviar o arquivo, e nesse momento inseri meu objeto (que antes mandava como json) no meu formdata. Dessa forma, precisei alterar meu back-end para que aceitasse o formdata, bastou remover o [FromBody].
Queria poder utilizar minha action, tanto passando formdata como passando um json, é possível? Como?
Answer: Posso exemplificar com Exemplo Minimo, porque, não tem tantos detalhes especifico na pergunta e sobre a pergunta da action ser responsável pelos dois tipos para o receber as informações e o arquivo, infelizmente não dá, o que pode ser feito é como exemplo abaixo, para um envio com jQuery + FormData e outra Action que receba json com [FromBody].
Tenho uma classe Elemento:
public class Elemento
{
    public int Id { get; set; }
    public string Nome { get; set; }
}

e um form na página além com os dois campos, vai ser passado via ajax um imagem de um input type file com FormData:

<form>
<form name="form1" id="form1">
    <input type="text" name="Id" value="1" />
    <input type="text" name="Nome" value="@Guid.NewGuid()" />
    <input type="file" name="arquivo" id="arquivo" />
    <button type="button" onclick="send()">Enviar</button>
</form>

ajax
function send() {
    var items = ($("#form1").serializeArray());
    var form = new FormData();
    for (i = 0; i < items.length; i++)
    {
        form.append(items[i].name.toLocaleLowerCase(), items[i].value);
    }
    form.append('arquivo', $('#arquivo')[0].files[0]);
    $.ajax({
        type: "POST",
        url: "/api/Elementos",
        contentType: false,
        processData: false,
        data: form,
        success: function (message) {
            // code
        },
        error: function () {
            //code
        }
    });
}

controller/action
[HttpPost]
public IActionResult Post(Elemento elemento,IFormFile arquivo)
{
    // aqui também recupera
    var resultForm = Request?.Form;

    // aqui de forma automática
    var ele = elemento;
    var arq = arquivo; // a foto enviado
    return Ok(new { e = elemento });
}

Código da página completa:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - WebApplication2</title>

Index

    <form name="form1" id="form1">
        <input type="text" name="Id" value="1" />
        <input type="text" name="Nome" value="@Guid.NewGuid()" />
        <input type="file" name="arquivo" id="arquivo" />
        <button type="button" onclick="send()">Enviar</button>
    </form>

Debug realizado para testes:

Referencias

FormData
Sending HTML Form Data in ASP.NET Web API: File Upload and Multipart MIME
18.104.22.168 Verbose JSON Format
Updated : Upload Files In ASP.NET Core 1.0 (Form POST And JQuery Ajax)
How to use FormData for ajax file upload - SOEn
Comment: Resposta perfeita!


Menu com banners laterais

Question: Venho trabalhando em um projeto que necessita da implantação de um pedido que aproveite os espaços brancos para que sejam colocados banners de divulgação. Lido com uma estrutura já determinada e diversas vezes tenho problemas de implantação de alguma coisa nova, tendo que apelar as vezes a algumas atitudes não semanticas.
O projeto segue um modelo assim parecido com esse (o original tem MUITAS classes e eu não tenho total acesso, por isso o modelo):

            Categoria

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

            Categoria

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

            Categoria

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

            Categoria

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Porém, ao tentar introduzir um banner em uma li extra em cada categoria, por exemplo, não obtenho sucesso, pois os heights variam de um browser para o outro. A intenção seria a de conseguir esse modelo com um container de 1000px e com a imagem sempre se adaptando de acordo com o número de "rows" de cada departamento:
Comment: Você pode usar javascript para pegar o height da ul menu-container e aplicar no height da sua imagem.
Comment: Onde está o CSS relevante para estas classes?
Comment: Velho, pessoalmente fica complicado dar um help assim.. tem inúmeras formas de se criar CSS pra atender seu objetivo... não tem ao menos algo pronto pra dar como exemplo? Algum site com o mesmo procedimento que voce tenha visto e etc..
Comment: A gente tem um exemplo real postado no site, mas com esses bugs cross browser. Na realidade, acabo não postando as informações devido a estrutura original do código que está bem decadente, e por ser gerado por outros, não da minha parte.
Answer: Jhonny, não use javascript para igualar os heights. Você pode usar flex para que os boxes tenham a mesma altura, usando a propriedade "align-items". Contudo esta técnica é compatível com Internet Explorer versão 10 ou superior.
Sendo assim, caso você queira igualar as alturas em navegadores mais antigos, você pode definir os estilos da estrutura como tabela, como neste exemplo (atente-se para "display: table" e table-layout: fixed;). Depois disso, defina que a imagem tenha altura de 100%.

Menu com banners laterais


Finding the expected value of two normal random variables

Question: Suppose $a_1 = b + c_1$ and $a_2 = 2b + c_2$ where $b, c_1, c_2$ are all $N(0,1)$
Find $E[b|a_1,a_2]$
My attempt:
As $E[b] = 0$, I assume $E[b|a_1, a_2] = 0$. Is this a logical assumption?
Comment: Hint: when you know $a_2$ and $a_1,$ you also know $a_2-a_1$ via subtraction. What information does that give you about $b$?
Comment: `Is this a logical assumption?` No, a _conditional_ mean such as $E[b\mid a_1, a_2]$ is not necessarily equal to the _unconditional_ mean $E[b]$.
Comment: I think a better way to do this is to apply law of total expectation in reverse and work out the joint distribution of a1 and a2?
Comment: This is the second homework problem you've posted today... Neither had much of an "attempt".
Answer: Let $B,C_1,C_2$ be independent $\mathrm{N}(0,1)$ random variables. Define $A_1=B+C_1$ and $A_2=2B+C_2$. Since we are conditioning on the same information, and $C_1$ and $C_2$ have the same distribution, by symmetry we have
$$
  \mathrm{E}[C_1\mid A_1,A_2] = \mathrm{E}[C_2\mid A_1,A_2]
$$
almost surely (we haven't used the independence assumption yet). Hence,
$$
  \mathrm{E}[B\mid A_1,A_2] = \mathrm{E}[B\mid A_1,A_2] + \mathrm{E}[C_2\mid A_1,A_2] - \mathrm{E}[C_1\mid A_1,A_2]
$$
$$
  = \mathrm{E}[B+C_2-C_1\mid A_1,A_2] = \mathrm{E}[A_2-A_1\mid A_1,A_2]
$$
$$
  = \mathrm{E}[A_2\mid A_1,A_2] - \mathrm{E}[A_1\mid A_1,A_2] = A_2 - A_1 = B+C_2-C_1
$$
almost surely. Therefore (Why? Remember the independence assumption and use this. What is the distribution of $-C_1$?),
$$
  \mathrm{E}[B\mid A_1,A_2]\sim \mathrm{N}(0,3) \, .
$$
(If you have any doubts about $\mathrm{E}[B\mid A_1,A_2]$ being a random variable, check this answer.)


how to sort and limit inside document mongodb in php

Question: i have the array here.
http://pastebin.com/i5ZUQNm6
and this from php result.
$result1 = $mo->find(
  array(
    'username' => 'BLABLA',
    'stream' => array('$exists' => true)
  )
);
foreach ($result1 as $obj) {
  print_r($obj);
}

how i sort the [stream] child and limit it to 1 result? and how to find [id_stream] child?
thanks
Answer: To limit, to a single document
use limit(1):

$result1 = $mo->find(   array(
      'username' => 'BLABLA',
      'stream' => array('$exists' => true)   ) )->limit(1);

or
findOne

$result1 = $mo->findOne(   array(
      'username' => 'BLABLA',
      'stream' => array('$exists' => true)   ) );

And to sort the child.
You need to also add at the end ->sort(array("stream.time" => -1));
I've seen the pastebin, and I guess you want to order by date.

Final code:
 $result1 = $mo->findOne(   array(
     'username' => 'BLABLA',
     'stream' => array('$exists' => true)))->sort(array("stream.time" => -1));;

From what I know for limiting to a single value of the array you need a loop
you need to add (inside the find, just after the main array): find(.... , array('streams' => array('$slice' => 1)));
Answer: Using a combination of sort and limit should work - the code in slownage's answer looks like it may be what you need.


Shortest path program

Question: I want to write a shortest path program. I know how the algorithm works, but I don't know where to start
Initially, I thought of using an adjacency matrix but then decided against it because of space. Now I think adjacency list would be better.
Can anyone suggest me a websites or tutorials how to start writing adjacency list to give the input to the program?
Answer: You might start with Boost::Graph, which will provide you both mechanisms for storing graph data and a structure for writing an algorithm that consumes that data.

Shortest path program


Microsoft Graph how to access client directory with a multi-tenant app registration

Question: I've made an app registration in our Azure AD (AAD) that's enabled for multi-tenancy. This registration is successful registered in another (client) AAD tenant (admin consent has been given).
I'm using .Net Core 2.1 and the MSAL 2.0 library for authentication.
I need to access the client AAD with Microsoft Graph from our management app to read the client AAD Groups when I'm logged in with an user from the original AAD (where the app registration was created).
I've followed this article https://learn.microsoft.com/en-us/graph/auth-v2-service and requested a token from the client AAD (Step 4). When I use this token to access the client AAD groups I get an access denied error.
When I create an app registration without multi-tenancy enabled within the client tenant AAD it works just fine. Isn't it possible what I want to achieve? I thought that I'm not the only one who want to access a client AAD from a management app, but I can't find any other articles describing this problem.
Answer:

I need to access the client AAD with Microsoft Graph from our management app to read the client AAD Groups when I'm logged in with an user from the original AAD (where the app registration was created).

You can only login with accounts in client AAD's organization , you can't login with an user from the original AAD . Unless you add the user from the original AAD to client AAD .
For example , you registers an app in AAD1 , you can login with accounts in AAD1 to manage resource which protected by AAD1 ; If app is multi-tenant app , after grant permission in AAD2, users in AAD2 can login app with their accounts to manage resource which protected by AAD2 . Unless you add the user from the original AAD to client AAD as guest user  .

I've followed this article https://learn.microsoft.com/en-us/graph/auth-v2-service and requested a token from the client AAD (Step 4). When I use this token to access the client AAD groups I get an access denied error.

You are acquiring token using Client Credential Flow with app's identity instead of user's identity. You should use OAuth 2.0 code grant flow if you want to login app using user's identity .
Comment: I got it working using the client_credential option. Because of this is the logged in user is not relevant.
Comment: @FerronSW , you can use client_credential flow but it's using app's identity , that means the client app doesn't redirect user to microsoft's login page , that defeat your scenario:`I need to access the client AAD with Microsoft Graph from our management app to read the client AAD Groups when I'm logged in with an user from the original AAD ` . Using client_credential flow doesn't need user to login /
Comment: I know, but this is the best way to achieve what I want. Getting access with a user to another tenant is a bit hacky.


Array de urls - Botão Próximo

Question: PHP
$urls = Array('www.1.com.br','www.2.com.br', 'www.3.com.br');

HTML

<button>Proximo</button>

Como faço para sempre que clicar no botão proximo atualizar só o iframe (não a pagina inteira) na sequencia de urls que estao no array php?
Estou em duvida também se é melhor um array com todas urls em javascript ou php
UPDATE
1 - As 3 respostas funcionaram para mim, mas as 3 tem um porém em comum: quando chega na ultima url do array, ao clicar novamente volta para a primeira url, deveria parar de ter ação ao clicar no botão Proximo quando finalizar as urls do array
2 - nos 3 exemplos a página inteira esta atualizando quando tem alteração na url do iframe
jQuery('#srcFrame').submit(function(){
           $.ajax({
            url: 'updateUrl.php',
            type: '???',
            data: ????,
        });
    })

Como faço pra usar o ajax pra só o iframe atualizar e como deve ser o arquivo updateUrl.php?
Comment: A resposta que você marcou como correta não faz isso que colocou no "*update*", não volta para o primeiro link.
Comment: mas não é para voltar para o primeiro link :) como esta escrito: `ao clicar novamente volta para a primeira url, deveria PARAR DE TER AÇÃO ao clicar no botão Proximo quando finalizar as urls do array`
Comment: E ela não volta, se estiver voltando é porque você usou o código do Ivan (que verifica o índice e, se for igual ao total de links, volta ao primeiro). :)
Comment: não, tanto o ivan como o Lucas fizeram alterações nas respostas durante o update. Se acompanhou, eu confundi e a do Lucas já estava correta,  antes mesmo de eu colocar o Update na minha questão
Comment: Mas aprendi muito com o Ivan tbm, ótimas explicações, mas o resultado final sem atualizar a pagina consegui entender com o Lucas. Novamente muito obrigada a todos
Answer: Capture os elementos através da ID, e crie uma ação no botão, verificando qual o próximo índice que deverá ser clicado, a cada click, soma uma posição, se for igual ao total de url, ele reinicia para o índice 0 (início):
<button id="next">Proximo</button>

Se quiser implementar usando PHP diretamente no javascript, dá pra fazer assim, mas eu não recomendo, prefira enviar os dados via POST ou GET, mas daí ficaria para uma outra pergunta:
<?php $urls = array('http://www.1.com.br',
                    'http://www.2.com.br',
                    'http://www.3.com.br'); ?>

Resolução para os novos casos:

Caso 1:

Caso 2:
Não ficou claro exatamente o problema. Pois ele carrega cada iframe na mesma página, se está atualizando, não tem a ver com o código que publiquei, mas com o resto do código que existe na sua aplicação, acredito eu.
Comment: Funcionou Ivan, os comentarios que colocou no código me ajudaram muito atualizei minha pergunta inserindo duas observações
Comment: Sobre o caso 2 é que quando clica no botão proximo o navegador inteiro tem um refresh, o refresh deveria ser só no iframe, atualizando só o iframe não a pagina inteira
Comment: o window.onload não é um reload. Ele apenas executa o código após a página ser carregada... você pode fazer o teste utilizando apenas páginas em branco, e verá que funciona normalmente.
Comment: sim, entendo, mas sabe aquele icone que usamos para atualizar a pagina no navegador (chrome por exemplo)? então, quando clicamos no botão proximo o icone do navegador roda, no caso de atualizar só o iframe ele não deve rodar, pq vai atualizar só o iframe não a pagina inteira
Comment: bom, você está fazendo uma ação em javascript, javascript não é server-side, se você clicar no botão atualizar, obviamente que ele irá perder tudo. para manter a posição, você teria que gravar a posição no banco via server-side, ou usar sessionStorage para manter um cache.
Comment: Por isso estou tentando entender como usar o Ajax
Comment: Você pode usar somente javascript para isso: `localStorage.setItem('posicao', index)` e captura com: `localStorage.getItem('posicao')`
Comment: A principal finalidade do ajax, é executar ações de maneira assíncrona.
Answer: Com Javascript, você pode alterar o src usando a função attr ou prop a cada evento click do botão, dessa forma:
HTML:

<button>Proximo</button>

Javascript:
var urls = ['www.google.com.br','https://platform.twitter.com/widgets/tweet_button.html', 'www.globo.com.br'];
var frame = $("#frames");
var index = 0;

$("button").click(function(event){
    event.preventDefault();
    if (index < urls.length)
        index++;
    $("#frames").attr("src", urls[index]);
});

JsFiddle: https://jsfiddle.net/lbclucascosta/rmoqa2c7/
event.preventDefault() é uma função que serve para prevenir um comportamento padrão de determinado componente, portanto se você o user no submit, o comportamento padrão de atualizar a página não vai acontecer.
Comment: Obrigada pelas indicações das páginas no manual, seu código funcionou tem 2 coisas que ainda tenho duvida, atualizei minha pergunta
Comment: para parar de ter ação no botão, quando for:
`
 if ( index === urls.length) {
   click_button.disabled = true;
 }`
Comment: Realmente Lucas, o seu quando chega ao final do array não acontece mais nada ao clicar no botão
Comment: `event.preventDefault()` seria no inicio da function? aqui não mudou o comportamento
Comment: agora o botão não funciona na vai para a proxima url
Comment: como faço para que ao ter alteração no scr do iframe usar o preventDefault? Algo como onchange iframe src preventDefault
Comment: Seu codigo funcionou, não estava percebendo pois só tinha o iframe e o botão na pagina, coloquei outros conteudos dinamicos e consegui perceber que esta funcionando. O Chrome da a impressao de estar atualizando a pagina por causa do icone de atualização, testei no IE e de primeira deu pra perceber que só o iframe estava atualizando. Obrigada novamente pelas respostas :)
Answer: Você pode fazer assim:
HTML:

<button id="changeURL">Próximo</button>

JavaScript:
var urls = "<?php echo implode('|', $urls) ?>".split('|');

$('#changeURL').click(function() {
    var i = urls.indexOf($('#displayURL').prop('src'));
    i = (i < 0) ? 0 : i+1;
    if(i <= urls.length-1) {
        $('#displayURL').prop('src', urls[i]);
    }
});

Ele transforma o array PHP em string separando os elementos por pipe, depois o javascript transforma essa string em array novamente, com esse array eu faço a lógica de troca no código abaixo, de acordo com o valor do src do iframe eu consigo achar o index no array e fazer ele ir pro próximo item, a menos que seja o último ou não exista, nesse caso eu seleciono o primeiro item do array.
OBS.: Eu to fazendo a separação da URL por pipe, mas você pode mudar pra qualquer caractere que não tenha nos seus links.
Comment: Obrigada Junior, gostei da ideia de implodir o array php dentro do javascript. Ainda tenho duas duvidas, atualizei minha pergunta
Comment: Atualizei o código pra primeira questão, a segunda você tem certeza que é a página toda que tá atualizando ou só o iframe?

Array de urls - Botão Próximo


Find the general solution of the differential equation $y^{''}-4y^{'}+5y=4e^{2x}\cos x$

Question: I need help with differential equation $$y^{''}-4y^{'}+5y=4e^{2x}\cos{x}$$
I calculated homogeneous solution which I got $$y_{h} = C_{1}e^{2x}\cos{x}+C_{2}e^{2x}\sin{x}$$
I do not know how to set the particular solution.
Any help?
Comment: Undetermined coefficients should work fine.
Comment: What method did you learn to find a particular solution? Guessing?
Comment: I tried to set like $y_{p}=e^{2x}(Acosx+Bsinx)$ but it does not work.
Answer: You correctly obtained the homogeneous solution
$$y_{h}(x)=C_{1}e^{2x}\cos(x)+C_{2}e^{2x}\sin(x).$$
Since $4e^{2x}\cos x$ has the form $P_{n}(x)e^{\alpha x}\cos\beta x$ we try to find a particular solution of the form  $$x^{s}\left((A_{0}x^{n}+A_{1}x^{n-1}+\cdots+A_{0})e^{\alpha t}\cos\beta x)+(B_{0}x^{n}+B_{1}x^{n-1}+\cdots+B_{n})e^{\alpha x}\sin\beta x \right),$$ for $s\in \{0,1,2\}$ such that we ensure that no term in the particular solution is a solution of the corresponding homogeneous solution.
In particular we try with $$y_{p}(x)=x^{s}(Ae^{2x}\cos x+Be^{2x}\sin x).$$

We can not take $s=0$, because that give $y_{p}(x)=Ae^{2x}\cos x+Be^{2x}\sin x$ and we already have these solutions (look at the homogeneous solution found).
We try with $s=1$, so we have $y_{p}(x)=x(Ae^{2x}\cos x+Be^{2x}\sin x)$, this should work. We will see that it does indeed work.

$$y_{p}=Axe^{2x}\cos x+Bxe^{2x}\sin x$$
$$y_{p}'=Ae^{2x}\cos x+2Ae^{2x}x\cos x-Ae^{2x}x\sin x+Be^{2x}x\cos x+Be^{2x}\sin x+2Be^{2x}x\sin x$$
$$y_{p}''=-Ae^{2x}x\cos x+A\cos x(4e^{2x}+4e^{2x}x)-2A(e^{2x}+2e^{2x}x)\sin x+2B\cos x(e^{2x}+2e^{2x}x)-Be^{2x}x\sin x+B(4e^{2x}+4e^{2x}x)\sin x$$
Substitution in $y_{p}''-4y_{p}'+5y_{p}=4e^{2x}\cos x$ and symplify we get $$A=0,\quad B=2$$
So, the particular solution is given by
$$y_{p}(x)=2e^{2x}x\sin x$$
Therefore, general solution is given by
$$y(x)=y_{h}+y_{p}$$
$$\boxed{y(x)=C_{1}e^{2x}cos x+C_{2}e^{2x}\sin x+2e^{2x}x\sin x}$$
Answer: In general, for ODE of the form:
$$y^{(n)} + \sum\limits_{k=1}^{n} a_k y^{(n-k)} = A e^{\alpha x}$$
If $\alpha$ is a root of $\displaystyle\;t^n + \sum\limits_{k=1}^{n} a_k t^{n-k} = 0\;$ with multiplicity $m$, then the particular solutions can be chosen to have the form
$A' e^{\alpha x} x^m$ (or more generally, $e^{\alpha x} \times$ polynomial in $x$ with degree $m$).
For your case, $2\pm i$ are simple roots of $t^2-4t+5 = 0$, you can look for particular solutions among those of the form
$$x(B e^{(2+i)x} + B' e^{(2-i)x}) = x e^{2x}(C \cos x + C' \sin x)
$$
where $B,B',C,C'$ are constants.
By brute force, you can verify $2x e^{2x}\sin x$ is a particular solution you seek.
Answer: Assume that $C_1=C_1(x)$. Then plugging in your solutions, gives
$$
e^{2x} \left[ (C_1''+2C_2')\cos x +(C_2''-2C_1')\sin x  \right]
=4 e^{2x} \cos(x)
$$
Now you have the system
$$
\begin{cases}
C_2''-2C_1'=0\\
C_1''+2C_2'=4
\end{cases}
$$
yielding $\frac12 C_2'''+2 C_2'=4$ i.e., $u''+4u=8$  where $u(x)=C_2'(x)$.
Hence we can find that $u(x)=A \cos(2x)+B\sin(2x)+2$,
$$
C_1=\cos(2x)+c',\ C_2=\sin(2x)+2x+c''
$$
where $c',c''$ are arbitrary constants.
Answer: $$y''-4y'+5y=4e^{2x}\cos x$$
$$(y''-4y'+4y)+y=4e^{2x}\cos x$$
$$(ye^{-2x})''+ye^{-2x}=4\cos x$$
$$v''+v=4\cos x$$
For the particular solution try:
$$v_p=Ax\sin x$$


What is the difference between Doosra and Teesra?

Question: What is the basic difference between Doosra and Teesra? I know off-spinner bowls the other one which is called Doosra but what is Teesra and how is it different to Doosra?
Comment: Well Said! Pehla Doosra Teesra, One Two Three :-)
Answer: Doosra and teesra, both these bowling techniques were invented to deceive the batsman.
Doosra and teesra both are Urdu words which means "the second one" and "the third one" respectively.
Doosra is the technique use by an off spin bowler and it results in leg spin, but the bowling action remains as off-spin (for left-arm bowlers the case is in reverse).
Teesra looks like the ball will turns a lot in off or leg but it results in less turn. The batsman can't judge the ball to where it would turn.
Both these techniques were invented by Saqlain Mushtaq.
Doosra is used well by most of the current off-break bowlers but, teesra is being used successfully by Saeed Ajmal.
Comment: @Yaitzme, if you watched the asia cup match between Pakistan and Bangladesh, they showed Ajmal's variation between Doosra and Teesra. See this [youtube video](http://www.youtube.com/watch?v=4gVQ6PtzX6w) about Ajmal's variation in a test match.
Comment: Could you explain the Teesra a bit more clearly?
I'm still confused.

Doosra is like the off-spinner's analogue of the Googly.
Teesra?
Comment: [This is an interesting read](http://www.espncricinfo.com/page2/content/story/549102.html) - Saeed Ajmal says he doesn't really have a teesra.
Answer: Tesra is actually a cross seaming or scrambled seam delivery. But doosra is a delivery which is built on clockwise and anticlockwise movements. It turns from leg to off stump (for a right-handed batsman).
It can be delivered by two methods:

wrist and back of the hand towards the batsman.
flicking the ball anticlockwise from the middle and second finger.
Answer: Teesra is basically a backspin bowl in which the ball is released in such a way that it spins towards the bowler so due to magnus effect, ball will be in the air flat and after pitching it will either skid or gets slow...hence the batsman will not be able to time the ball correctly.
Answer: Doosra is analogous to googly except it turns more than googly and is very difficult to bowl without chucking wheares teesra is simply a backspiner with very small side turn it is analogus to a leg spinner's Slider When bowling a teesra the bowler keeps the exact grip as the off spin but instead of imparting spin to the ball he simply let go the ball rolling over his fingers just like a seamer does while swinging the ball so the ball skids and reaches the batsman late which can decieve him while facing a quick off spinner
Answer: So far this delivery has been used for well over a hundred years. But the delivery has recently been re-invented by Saqlain Mushtaq and he occasionally used it. He has stated that the teesra is still a work in progress and that he wants to hone the delivery so that the batsman become even more confused about where the ball is going to spin and whether it will spin at all. Saeed Ajmal claimed to have learned this art and has used it occasionally in the 2011 World Cup and after that


Frobenius reciprocity for reductive groups

Question: Let $G$ be finite group and $H$ its subgroup. We assume that everywhere the base field is $\mathbb{C}$. For any characters $\phi$ of $G$-representation and $\psi$ of $H$-representation Frobenius reciprocity states that:
$$
  \langle Ind^G_H(\psi), \phi \rangle_G = \langle \psi, Res^G_H(\phi) \rangle_H \qquad (1)
$$
In particular, this means that multiplicity of $G$-representation in induction of $H$ is equal to the multiplicity of $H$-representation in the restriction of $G$-representation (correct me please if I am wrong somewhere).
Now, let $G$ be reductive Lie group and $H$ its Lie subgroup. Since any $G$-representation is also an $H$-representation, we may define restriction of $G$-representation to subgroup $H$, which will decompose into direct sum of $H$-irreducibles with some multiplicities.
Question: Is there an induction process that builds $G$-representation by given $H$-representation (1)? Does this works?
Answer: Yes, there is. Given a representation $\rho: H\to GL(V)$ you can define $Ind_H^G(\rho)$ to be the space of continuous functions $f:G\to V$ such that $f(gh) = \rho(h^{-1})f(g)$ for $h\in H$ and $g\in G$.
$G$ acts on this space via $(g\cdot f(g'))=f(g^{-1}g').$
Even in this setting, the statement of Frobenius reciprocity holds.
Comment: Can you please provide a reference for that / proof for that?
Comment: I think you can find it in "Compact Lie groups" by Sepanski.
Comment: thanks for the reply, corresponding chapter in the book is very well written for me.


Java Key Listener not working

Question: Trying to make the text field accept only integers
some how it either consumes everything I type in the field or it just lets to type anything
it's simple that's why its hard to find the problem.
<code>JLabel year = new JLabel("Year:");
      final JTextField yeart = new JTextField(10);
      yeart.addKeyListener(new KeyAdapter()
      {
         @Override
         public void keyTyped(KeyEvent e)
         {
            super.keyTyped(e);

            e.getKeyCode();

            if (!(e.getKeyCode() >= 48 || e.getKeyCode() <= 57))
            {
               e.consume();
            }
         }

      });
</code>
Comment: Posting an [SCCEE](http://sccee.org) will get you better results.
Comment: Use a `DocumentListener` or `DocumentFilter` when working with `JTextComponent` instances, and not a `KeyListener`. For example copy-paste will mess up your functionality. Besides that, you can use a `JFormattedTextField` for this as well (see [here](http://stackoverflow.com/a/13424140/1076463) for an example)
Comment: In future, please add the programming language you are using as a tag to your questions, this will help more people to find your questions, which will help get them answered faster.
Comment: Why would i use DocumentListenet or DocumentFilter if i can make this work? this is way more simpler to understand and explain.
Comment: @FancyPants _if I can make this work_. I am saying you cannot: for example copy-paste or drag-and-drop will not work with your `KeyListener`
Comment: @Robin made it work. It's not something fancy and high leveled that I'm doing. My program is just to create bookings for a car rental company. At the moment I don't need those extra features that DocumentListener and DocumentFilter offer.
Comment: `At the moment I don't need those extra features that DocumentListener and DocumentFilter offer` - You would not use a DocumentListener, only a DocumentFilter. Using a filter is NOT an extra feature, it is one of the few ways to get you code working properly, as Robin has already told you. Try pasting the string "abc" into your text field.
Answer: Use && instead ||. (!(e.getKeyCode() >= 48 || e.getKeyCode() <= 57)) will simply return false for every input.
Comment: added && ,now it does not let me to type in anything.
Comment: Use if (!((int)e.getKeyChar() >= 48 && (int)e.getKeyChar() <= 57))
Comment: @FancyPants, `Works now` - try pasting text into the text field.

Java Key Listener not working


How Do I Utilize My Practice Time So It Is Efficient (Clarinet)?

Question: As a high school clarinetist, I have showed skill and potential. I play a Buffet E12F, with a Vandoren Black Diamond mouthpiece, and use 3 1/2 strength V12 Vandoren reeds. I made all-state this past year as a sophomore, but mostly because of raw talent and a week's worth of cram practice before auditions. I do not currently take private lessons and am wondering what I need to focus on during practice time to make it more efficient so that I am able to benefit and grow as a player. As of late I do not know what to focus on in practicing. Some of my biggest downfalls are as follows:
• My tone (I feel that it is bright and weak, failing to embody a full and round signature clarinet tone you may hear from more experienced players like Corrado Giuffredi). My tone also weakens as I play through a variety of dynamics (ex: flat during pianos and long sustain notes like in the ending of Lux Aurumque by Eric Whitacre) and it suffers greatly as I move up the register. I also cannot maintain a full tone in faster pieces, usually giving it up as I focus on note accuracy instead. Recommendations for exercises or anything to better improve this would be helpful.
• My tonguing is very heavy. Something that you can hear during my playing during accidentals like stacattos. My band director pointed out that my playing is often very tongue heavy and reedy. I do not know what I need to do to improve this area of my playing. Any tips on this would help.
• My tonguing is slow and I have a hard time playing faster pieces. My fingers and tongue are often not in synch and I cannot tongue fast. I do not now how to double tongue and cannot tongue a fast string of notes well. I am not sure what needs to be done to improve this aspect of my playing.
• When I am faced with faster moving pieces and larger gaps in between notes that are far apart in the staff, I often am unable to play it. I generally have to fake it even during concerts. Tips for how to sight read would be helpful since I lack heavily in this area. Exercise recommendations that will help improve my ability to play faster and cleaner would also be appreciated.
Even if you have read this far, but are not inclined to answer, I thank you for taking the time to read this. Since we are going through quarantine I have decided to make good use of the vast amounts of free time I have at my disposal. I wish to grow overall as a player and want to return to school better than when I had left it before. Any comments and criticism would be greatly appreciated.
Thank you!
LeNitro
Comment: Can't see how tonguing and accidentals are related. Do not play continuously for hours! Maybe 30 mins with a 30 min break gives your mouth chance to recover.
Comment: Accidentals now that I look back on it shouldn't be an issue. I think I generally tongue heavy so that it affects my playing, but I am not sure what I can do to improve it so that it doesn't impact my overall tone. Staccatos do not get the light unweighted sound usually since my heavy tonguing cancels it out. Thank you for the response on the overall practice length! Whenever I used to practice it was for over an hour. This feedback helps!
Comment: Sadly,  the truth is:  get lessons or risk continuing to develop bad habits that will be very hard to break.   From your descriptions, you don't currently have proper diaphragmatic breath control working, nor are you tonguing properly.   Scales & speed depend on good practice methodologies, which take up several books.
Comment: Ah, alright. My parents will not get me lessons because I do not usually practice at the house. I think that if I practice more I will be able to get lessons. Thanks for the feedback though.
Comment: Concerning the point double tonguing: on brass we play " taka". Clarinetists seem to do different. Have you seen this article: http://www.woodwind.org/clarinet/Study/DoubleTonguing.html
Comment: Oh wow! This article is really helpful. I have heard about double tonguing, but never sought to pursue learning it because of my failed attempts at trying to learn from YouTube videos. Thank you for responding, I'll be sure to use the article's tips in my next practice session!
Answer:
When I am faced with faster moving pieces and larger gaps in between notes that are far apart in the staff, I often am unable to play it. I generally have to fake it even during concerts. Tips for how to sight read would be helpful since I lack heavily in this area. Exercise recommendations that will help improve my ability to play faster and cleaner would also be appreciated.

My advice:
Notate the certain passages in a staff with lines and ledger lines but in stead of dots write the note names tight in the system at the place of the note heads. Then read and play these notes.  If you practice this exercise you will be able to read the notes quite soon.
Comment: Thanks so much! I do not think I have ever thought about it from this approach. I will try to use it next time!


Radius of convergence of power series of sub-stochastic matrix

Question: Suppose I have a connected graph $G = (V,E)$, and a subset of vertices $U$, such that $W$ is the subgraph of $G$ induced by the vertices $V \setminus U$, and that $W$ is also connected.
Now, let $X_n$ be a random walk on $G$ and let $P$ be it's transition probability matrix. Now, let $Q$ be the submatrix of $P$ that corresponds to the vertices $W$. So, $Q$ is a sub-stochastic matrix (i.e. at least $1$ row sums to less than $1$)
I have shown that, for any $i,j \in W$, $\sum_{n=0}^\infty (Q^n)_{ij} = \mathscr{G}_U(i,j) < \infty$, and I have also shown that the power series $\sum_{n=0}^\infty x^n(Q^n)_{ij}$ converges for some $x > 1$, by showing that all eigenvalues of $Q$ are strictly less than $1$.
Now, I want to show that the radius of convergence, $R$, of $\sum_{n=0}^\infty x^n(Q^n)_{ij}$ does not depend on $i$ or $j$.
I am stuck here, and not sure how to proceed.
Answer: I'm pretty sure you're summing over $n$, not $i$.
Assuming that, from diagonalization you have that $(Q^n)_{ij}$ is some linear combination of $\lambda_k^n$ where $\lambda_k$ are all the eigenvalues of $Q$ (say sorted in decreasing order of magnitude). So the radius of convergence is presumably $1/|\lambda_1|$, except for the possibility that somehow $(Q^n)_{ij}$ had no contribution from $\lambda_1$. But the Perron-Frobenius theorem (for general nonnegative matrices, not just stochastic matrices) forbids that, because the eigenvector $v_1$ will have everywhere nonzero entries.
Comment: Yes, summing over $n$, sorry! Also, why are we guaranteed that $Q$ is diagonalizable?
Comment: @jackson5 If it isn't, you can still write down the Jordan normal form version of this statement, but there might be some $n^\ell$'s floating around for the generalized eigenvectors. But $v_1$ will still have everywhere positive entries, so that contribution should determine the radius of convergence. However I see a snag in the periodic case: in this situation you need to be worried that the radius of convergence might go up due to cancellations between terms whose eigenvalues have the same magnitude as $\lambda_1$. In the aperiodic case what I said goes through, however.


In Hapi how can I get access to request payload for GET methods

Question: I am using Nodejs with Hapi for rest api implementation and backend DB is mongo. I have a requirement where user can pass parameters in request payload for a GET call and I need to search accordingly based on those values. In Hapi framework I do not get any payload value when I do a GET method. Is there a way I can get payload. Below is my code.
route:
{
        method: "GET",
        path: `/v1/getProducts`,
        handler: function(request, reply) {
          ProductController.getProducts(request, reply);
        }
}

ProductController:
   const mongoose = require("mongoose");

const Products = require("../models/products");

const getProducts = (req, res) => {
  console.log("I am in getProducts");
  console.log("Headers :", req.headers);
  console.log(req.payload);
  var query = {};
  //If values present in request payload for a query accordingly
  if (req.payload.productName) {
    query["PRODUCT_NAME"] = req.payload.productName;
  }
  if (req.payload.productType) {
    query["PRODUCT_TYPE"] = req.payload.productType;
  }
  if (req.payload.supportHardware) {
    query["HARD_SUPP"] =
      req.payload.supportHardware;
  }

  Products.find(query, "-_v")
    .exec()
    .then(results => {
      console.log(results);
      res({ result: "Success", ProductList: results });
    })
    .catch(err => {
      console.log("GETPRODUCTS RESPONSE: ", err.stack);
      res({ error: { errorId: "xyz", message: err } });
    });
};

module.exports = { getProducts };

But I null value in req.payload
I am in getProducts
Headers : { host: 'localhost:8000',
  'user-agent': 'curl/7.63.0',
  accept: '*/*',
  'content-type': 'application/json',
  authorization: 'Basic bTE3NTg5h1Yi5hdHQuY29tOmJyaWFuSXNDb29sMTg=',
  'content-length': '34',
  SERVICENAME: 'rest/productService/v1/getProducts',
  REQUEST_START_TIME: 1548272230344,
  'X-CSI-ConversationId': 'anscUser~CNG-CSI~1d58d6fd-a981-4bba-b9ed-16964d7cc51b',
  'X-CSI-UniqueTransactionId': 'AnscCsiRestful38856@e1f99082-150e-4b1e-b92f-04bb6c007d65',
  'X-CSI-MessageId': '1b06946e-732d-4075-ba6a-2dc7d13f4f80',
  'X-CSI-TimeToLive': '60000',
  'X-CSI-SequenceNumber': '1',
  'X-CSI-TotalInSequence': '1',
  'X-CSI-ClientApp': 'ansc-csi-restful~N/A',
  DOWNSTREAM_CALLS_INFO: [] }

  null

Comment: Can you `console.log(req.headers)` and update your question with that?
Comment: updated headers content.
Answer: It finally occurred to me that you are passing a payload in a GET request. This is not something you should be doing. You should be passing payload data/lookup values, as query params. Alternatively, you should consider using a POST request instead. Here is some additional info on this topic.
In your case, if you want to continue to use a GET request, you should use the request.query to access the values. Docs here
Something like the below will loop through all the passed in query params and build you a lookUp query to be used in your db lookup. You might want to add a filter or validate the key names as you wouldn't want random keys to be used as lookup fields in your db request
The below replaces req.query with query.

var query = {"PRODUCT_NAME": 123, "PRODUCT_TYPE": 456};

var lookupQuery = Object.keys(query).reduce((lookUp, key) => {
  lookUp[key] = query[key]
  return lookUp
}, {})

console.log(lookupQuery);
Comment: Yeah! I agree that payload with GET method is not the perfect way. But I am not in control of changing the requirement. Max i can propose to use POST/PUT instead of GET. But I want to know if there is a possibility to get hapi server accept the payload in GET and pass it for use. How can I make that possible
Comment: It's not possible for Hapi to 'read' the payload for `GET` requests. Below is the code from Hapi that processes `GET` req's and binds the payload.

`exports.payload = function (request) {

    if (request.method === 'get' ||
        request.method === 'head') {                // When route.method is '*'

        return;
    }

    return internals.input('payload', request);
};`

As you can see, if the method is `get` or `head`, it just returns and does not do anything with the `payload`


SQL server environment

Question: I'm considering a bit of changes in current sales environment. And trying to check all cons and pros.
Current situation.
SQL server (quite decent HP server - server1) + backup server (smaller Dell server - server2).
all sql files and sql server itself are on the server1. If something goes wrong with server1 I will have to manually move to server2.
Connecting to the sql server: 1 HQ (where server located) + 4 sites through VPN.
Now I'm considering 2 scenarios:

Buy some storage system + update existing servers (add ram, upgrade processors) and go for VMWare ESXI.
Rent a server at a datacenter + rent virtual server in case real server goes down. Also rent some space at data storage to keep SQL files there.

Have anyone considered these things and maybe found some good pros/cons list? ;)
Thanks
Answer: Well, it's always up to you - these variants will just have different price and performance, and I can't say which one is better based on provided information.
For #2 you might have "disabled" virtual server (cloud things) - so that you are not paying for it when you don't need it. You may combine this option with your first variant.
Answer: What are your requirements?

Are you looking for automatic failover to the backup server or is the manual process okay?
How much storage is required?
What is the concurrent usage?
If HQ could not connect to the SQL Server because the remote link is down, how does that
affect your productivity?

How old are your current servers and what is their warranty status? Are they within consideration to migrate to ESX servers?
Answer:
Manual is ok also if getting automatic will be costly
Current database is about 17GB (both data file and transaction file)
In current situation if HQ has problems with connection, then other sites are also down. One of the pros of using server in Datacenter is that usually providers react more quickly to the problems in datacenter then to the problems with separate customer :)

Main server is almost 3 years old with standard HP warranty.

SQL server environment


Ninject Generic Repository in MVC

Question: I have a Generic repository interface with its imp as you can see :
  public interface IEntityRepository<T> where T : class
{

    IQueryable<T> GetAll();
    IQueryable<T> FindBy(Expression<Func<T, bool>> predicate);
    bool Add(T entity);
    bool Delete(T entity);
    bool Edit(T entity);

}

Its imp
 public abstract class Repository<C, T> :
       IEntityRepository<T> where T : class where C : WelfateContext, new()
    {

        private C _entities = new C();
        public C Context
        {

            get { return _entities; }
            set { _entities = value; }
        }

        public virtual IQueryable<T> GetAll()
        {

            IQueryable<T> query = _entities.Set<T>();
            return query;
        }

        public IQueryable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {

            IQueryable<T> query = _entities.Set<T>().Where(predicate);
            return query;
        }

        public virtual bool Add(T entity)
        {
            _entities.Set<T>().Add(entity);
            _entities.SaveChanges();
            return true;
        }

        public virtual bool Delete(T entity)
        {
            _entities.Set<T>().Remove(entity);
            _entities.SaveChanges();
            return true;
        }

        public virtual bool Edit(T entity)
        {
            _entities.Entry(entity).State = EntityState.Modified;
            _entities.SaveChanges();
            return true;
        }

    }

In my controller i used it as you can see :
private IEntityRepository<Employee> employeeService;

    public EmployeeController(IEntityRepository<Employee> _employeeService)
    {

        _employeeService = employeeService;
    }

I get this error:
Error activating IEntityRepository{Employee} using binding from IEntityRepository{Employee} to Repository{WelfateContext, Employee}
No constructor was available to create an instance of the implementation type.

Activation path:
 2) Injection of dependency IEntityRepository{Employee} into parameter _employeeService of constructor of type EmployeeController
 1) Request for EmployeeController

Suggestions:
 1) Ensure that the implementation type has a public constructor.
 2) If you have implemented the Singleton pattern, use a binding with InSingletonScope() instead.

Here is my ninject binding
 private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<WelfateContext>().To<WelfateContext>().InRequestScope();
            kernel.Bind<IEntityRepository<Employee>>().To<Repository<WelfateContext, Employee>>();
            kernel.Bind<IEmployeeService>().To<EmployeeService>().InRequestScope();
            kernel.Bind<IEmployeeDomainService>().To<EmployeeDomainService>().InRequestScope();

        }

Comment: You have no constructor in your repository implementation.  You also instantiate your context with your declaration.  Add a constructor that passes in the context.
Answer: Add constractor to repository
   private readonly C _entities;
   public Repository(C context)
   {
     _entities = context;
   }

then you don't need to this code
 public C Context
        {

            get { return _entities; }
            set { _entities = value; }
        }

Ninject Generic Repository in MVC


$\lim_{x\to 0} (1+x)^{1/x}$

Question: This question has an answer here
However, $$\lim_{x\to 0^+} (1+x)^{1/x} = \lim_{x\to 0^-} (1+x)^{1/x} = e$$
And it seems that $\lim_{x\to 0} (1+x)^{1/x} = 1^{undefined} = 1$
Also, I thought the limit in theory does not exist right if the left and right limits don't match the function at the value?
And when I plot it on desmos.com, it shows the value is undefined at $x=0$.
Can someone help clarify please?
Comment: The value is undefined at $x=0$, but the limit still exists.
Comment: Think about this function $f(x) = \frac{(x-2)(x+2)}{x-2}$. This function is not defined at $x=2$, however, $\lim_{x \to 2} f(x) = 4 \ne f(2)$.
Comment: It is undefined at 0.  But it is defined in the neighborhood of 0.
Comment: Also to note that $1^\infty$ is undefined and does not actually equal $1$.
Answer: You're correct that a limit does not exist if the left and right limits don't match - but it's each other that they need to match, not the function. Desmos isn't telling you that the left and right limits don't match, it's telling you that the function is undefined at that point - which is actually completely irrelevant for limits. In fact, the whole point of talking about limits is to deal with the fact that sometimes we can't just plug things in, even though there's a value that "makes sense" there. For example, in the function $f(x) = \frac{x}{x}$, $f$ is not defined at $x = 0$. But $f$ is "obviously" just the constant function $1$, so it "makes sense" to say that $f(0)$ is $1$. So instead of saying the false thing that $\frac{0}{0} = 1$, we use the notation $\lim_{x\to 0}\frac{x}{x} = 1$, which just means "when $x$ is close enough to $0$, $\frac{x}{x}$ is close enough to $1$".
Now, because we're worried about this sort of situation, we have to be very careful about when we plug in numbers. In particular, any situation where the exact value of $x$ is important is concerning - a good example is $\frac{x}{x}$. If we tried to plug in $x = 0$, we might say "well, obviously $\frac{0}{\textrm{anything}}$ is $0$, so this is $0$". But that relies on $x$ being exactly zero, which isn't something we get to do in a limit. This situation is an indeterminate form.
The format $1^{\infty}$ is another good example of this. In the limit you're looking at, you're right that $1 + x$ goes to $1$ and that $\frac{1}{x}$ goes to $\infty$. But while $1^{\textrm{anything}}$ is certainly $1$, $(\textrm{almost} 1)^{\textrm{big number}}$ is not. To take an extreme example, $0.99^{10000}$ is so close to zero that it has forty zeroes following the decimal point. On the other hand, $0.9999^{100}$ is $0.99$ - nearly one. Because we've got this situation, we can't be sure just by looking which will "win"; the bigness of the exponent or the closeness of the base to $1$. We need to use some more powerful tools, which is what the answers in the question you linked to do.
Answer: HINT:
$$
\lim_{n\to\infty}\left(1+\frac1n\right)^n=e.
$$
But if $a_k\to\infty$, we have $m_k\leq a_k\leq n_k$, hence
$$
\lim_{n\to\infty}\left(1+\frac1{a_n}\right)^{a_n}=e.
$$
The rest should be easy.

$\lim_{x\to 0} (1+x)^{1/x}$


Adding image in a cell of jqxgrid

Question: i have used Jqxgrid for a project which successfully loads data from a json string passed to it as a data source. i want to display images/icons in a column cell again each particular entry/row. Following code initializes the grid:
<code> $("#jqxgrid").jqxGrid(
        {
            width: 850,
            source: dataAdapter,
            pageable: true,
            autoheight: true,
            sortable: true,
            altrows: true,
            enabletooltips: true,
            editable: true,
            theme: 'energyblue',
            selectionmode: 'multiplecellsadvanced',
            columns: [
           align: 'right', cellsalign: 'right', cellsformat: 'c2', width: 200 },

              { text: 'SendMail', columngroup: 'Mail Details', datafield: 'ID', width: 50 },
              { text: 'Content Type', columngroup: 'Mail Details', datafield: 'LinkFilename', cellsalign: 'right', align: 'right', width: 200 },
              { text: 'Sender', columngroup: 'Mail Details', datafield: 'Sender', align: 'right', cellsalign: 'right', cellsformat: 'c2', width: 200 },
              { text: 'Date', datafield: 'Created', cellsalign: 'right', cellsrenderer: cellsrenderer, width: 250 },

            ],
            columngroups: [
                { text: 'Mail Details', align: 'center', name: 'Mail Details' }
            ]
        });
</code>
Please guide me through this.
Answer: You can use Image Column in JqxGrid. Tutorial
Comment: Yeah, my fault.. But that isn't what you want?
Comment: Thanks for your suggestion, but its not an image column ( thats only the column name), it's basically'cellsrenderer' property in column definition that does the trick.
Comment: Yeah, I resolved it using the same method a few days back, just couldn't update the post. Thanks anyways. :)

Adding image in a cell of jqxgrid


How to get node's view mode in hook_page_attachments?

Question: I need to get the node's view mode so that in the mymodule_page_attachments, I can add libraries conditionally if the node's view mode is set to full or default. I tried the following but not able to get the nodes view mode once I retrieve the$node` object.
How to get node's view mode in hook_page_attachments?
Here is what we tried:
function mymodule_page_attachments(array &$attachments) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if(is_object($node)) {
     // we tried printing but that didn't result any view_mode field.
     ksm($node);

    // Goal
    if($node['view_mode'] == 'full' or $node['view_mode'] == 'default') {
       // proceed with my logic.
    }
  }
}

Comment: Drupal does not distinct between full and default here. If no full viewmode is given for a certain node type than the default viewmode is used. So you could check whether a given node type implements the full viewmode and apply your conditional logic based on this.
Comment: Is your question rather "How can I attach a library when a node is viewed in a certain view mode?" or "How can I attach a library when a certain view mode for the current single node exists?"
Answer: To attach a library only when a node in a certain view mode is displayed you can use hook_entity_view/hook_ENTITY_TYPE_view like following.
/**
 * Implements hook_ENTITY_TYPE_view().
 */
function MYMODULE_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  $node = $entity;
  if ($node->bundle() === 'page') {
    if ($view_mode === 'full') {
      $build['#attached']['library'][] = 'MYMODULE/foo';
    }
    elseif ($view_mode === 'default') {
      $build['#attached']['library'][] = 'MYMODULE/bar';
    }
  }
}

Comment: This is the correct hook, not only because the node is already available, but also for performance reasons, because the attached library is cached in the metadata of this node and then bubbles up to page level whenever the node is displayed. Always attach content specific libraries to the content and not to the page.
Comment: it will give you "full" view mode even if its using default view mode because full is not defined for particular bundle
Comment: @StefanKorn – True that. It's just I'm not entirely sure what OP really wants. Is it OP wants to look if a certain view mode is defined and add the libraries then (sounds a bit unrealistic but who am I) or is it OP really needs to add a lib if a node in a certain view mode is being displayed (sounds more realistic to me).
Comment: You're right, question could have some clarification. Since OP was exactly asking between full and default and on routeMatch, I thought it's about distincting between full and default. And if you go on routeMatch you will imho by drupal default (entity.node.canonical) never getting anything else then full.
Answer: Drupal does not distinct between full and default here. If no full viewmode is given for a certain node type than the default viewmode is used. So you could check whether a given node type implements the full viewmode and apply your conditional logic based on this, like this:
function hook_page_attachments(array &$attachments) {
  /* @var \Drupal\node\Entity\Node $node */
  $node = \Drupal::routeMatch()->getParameter('node');
  if($node) {
    $view_modes = \Drupal::service('entity_display.repository')->getViewModeOptionsByBundle('node', $node->bundle());
    if (isset($view_modes['full'])) {
      // this is full
    }
    else {
      // this is default
    }
  }
}


Recursive Algorithm Question

Question: I am having a difficult time figuring out where to start this problem.  Any input on where to start would be greatly appreciated.
Consider the recursive algorithm, which operates on a sequence of real numbers, S = {s0, s1, s2, ..., sn):
Function Questo(S)
First := the first element of s
If length(S) is 1
return First
End-if
S1 := S with the first element removed
return first + Questo(S1)
Let sequence T := (4,2,-1,3)
Which value is returned by Questo(T)?
Comment: Start with First:= the first element of T, which is 4.
Comment: Ok starting with 4.  Now length(S) is 1.  If 4 then not 1 it seems.  So 4 is removed.  But that return part confuses me because of no return first.  So return first is 0 + 4 = 4?  I am probably way off but I'm trying.
Comment: length(T) = 4, so skip the first If.  Now S1:=(2,-1,3).
Comment: Seems like the same thing happens with 2,-1, and 3 being removed.  So is it 0?
Comment: Yes, it is a recursive function.  Eventually you will hit length(S) = 1 when S=(3).
Comment: Ok so it's 3 because the length is 1.  So the answer is 3 then.
Comment: Yes, Questo(3) = 3.  Now work your way back up the stack to compute Questo(T).
Comment: So start back at 4?
Comment: No, compute Questo(3), then Questo(-1,3), then Questo(2,-1,3), then Questo(T).
Answer: \begin{align}
\text{Questo}(T)
&= \color{orange}{\text{Questo}(4,2,-1,3)} \\
&= 4 + \color{green}{\text{Questo}(2,-1,3)} \\
&= 4 + 2 + \color{blue}{\text{Questo}(-1,3)} \\
&= 4 + 2 + (-1) + \color{red}{\text{Questo}(3)} \\
&= 4 + 2 + (-1) + \color{red}{3} \\
&= 4 + 2 + \color{blue}{2} \\
&= 4 + \color{green}{4} \\
&= \color{orange}{8}
\end{align}
Comment: Wow so pretty much they are added together.  Why do they all leave Questo including 3?
Comment: For clarity, I added colors to the result of each Questo call.

Recursive Algorithm Question


How can I select a column from a DataFrame so that it has the shape (n, 1) instead of (n,)?

Question: I am separating two columns of a data-frame to use as features and labels respectively:
X = bmi_life_data['BMI']
y = bmi_life_data['Life expectancy']

But I have to reshape the obtained uni-dimensional array ( with shape=(n,) )  to the shape (n, 1) in order for it to be accepted by the regression.fit() function:
X = X.values.reshape(len(X), 1)

Otherwise I get the error:
bmi_life_model = LinearRegression()
bmi_life_model.fit(X, y)

laos_life_exp = bmi_life_model.predict([[21.07931]])

>>>>
ValueError: Found arrays with inconsistent numbers of samples: [  1 163]
None

I also could reshape on the spot when defining X but its pretty much the same. I find this reshaping step tedious so I think there has to be a better way.  I tried to find it but all I found was the difference between matrices and uni-dimensional arrays which was useful info but did not answer my question.
Answer: This should work:
X = bmi_life_data[['BMI']]
y = bmi_life_data[['Life expectancy']]


Question about the definition of the class NP

Question: In the definition of the complexity class $\mathcal {NP}$; Why does one require the existence of an algorithm $\mathcal A$, such that

for each instance $I$ of the problem, there exists a solution $x_0\in Sol(I)$ such that $\mathcal A$ accepts $(I,x_0)$ in polynomial time

rather than

for each instance of the problem and each solution $x_0\in Sol(I)$, $\mathcal A$ accepts $(I,x_0)$ polynomial time

I ask this, because I was told that $\mathcal{NP}$ tries to capture the idea that some problems are hard to solve, but easy to check. And the second definition - it seems naively - would be the right one for this.

What is the reason for not requiring the algorithm to accept every solution to a given instance of the problem?

The only problem with the 2nd version that I could see is that $x_0$ may not be bounded in size polynomially in $|I|$ (so reading it might already take too long). What if one adds a requirement to prevent such a thing?
Thanks for your help!
Answer: The word "solution" is rather confusing here. Instead, try this:

for each instance $I$ of the problem, there exists a string $s$ such that $\mathcal A$ accepts $(I,s)$.

Then, we can call such strings $s$ "solutions". So $I$ is an instance iff there exists a solution for $I$.
The algorithm accepts each solution, but this remark is content-less, because that's how we defined: a solution is something that is accepted by the algorithm.
As for bounds, in this definition both $s$ must have length polynomial in length of $I$, and $\mathcal A$ must be a polynomial time algorithm. Since time is measured relatively to input size, and input to $\mathcal A$ is $(I,s)$, if you allowed $s$ to be long, $\mathcal A$ could perform very long computation.
Comment: Hmm, then I'm not sure I've understood the definitions. It says here in my script: A decision problem $\Pi$ is a tuple $\langle \mathcal I, Sol\rangle$, which consists of a set of problem instances $\mathcal I \subset \Sigma^\ast$ and for each instance $I\in \mathcal I$, the set $Sol(I)\subset \Sigma^\ast$ denotes the set of solutions to $I$. Here $\Sigma$ is an alphabet and $\Sigma^\ast$ are all words over this alphabet. So, from this I would think that the term "solution" is independent of $\mathcal A$ (Note: Definitions translated from German - so terminology might differ from standard one)
Comment: So couldn't then there be an algorithm $\mathcal A$, which accepts $(I,s_I)$ for exactly one $s_I\in Sol(I)$ to each instance $I$, but rejects all other $(I,s)$ (even though there may be many actual solution to the problem among them)? This would then mean, that we'd have to be extremely lucky to pick out the right $s$ amongst $Sol(I)$ for the algorithm to accept it. So, in practice, the problem might not be easy to check at all! Where am I wrong?
Comment: Hm, this is very peculiar, I never saw "decision problem" defined in that way. In standard textbooks, decision problems are defined as subsets of $\Sigma^{\ast}$. Anyway, I suggest you read the definition in the following way: the algorithm has to accept $(I,s_I)$ iff $s_I$ is a solution for $I$, and $I$ is in a language (i.e. has answer "yes") iff there exists a solution for it.
Comment: I have now read through the relevant sections of *Introduction to Algorithms* by T. Cormen, C. Leiserson, R. Rivest, C. Stein. It indeed seems that the definition there does not quite agree with the one given in my script (what they call a 'concrete problem' is what my script calls a "Entscheidungsproblem", i.e. decision problem). But a 'decision problem' seems to be a term usually reserved for a problem with solution set $Sol = \{0,1\}$ and such that for each $x \in \mathcal I$ either $(x,0)\in \Pi$ or $(x,1)\in \Pi$ (but not both). (cont)
Comment: ... So that the problem $\Pi = \langle \mathcal I, Sol\rangle$ in this case can be identified with the language $$L = \{x\in \Sigma^\ast\mid (x,1)\in \Pi\}$$
Comment: I will have to think about the connections between the definitions of $\mathcal{NP}$ given there and in my script. They don't seem to agree either.
Comment: Sam: Yes. Decision problems have either "yes" or "no" answers and are identified with the set of "yes" instances. [Search problems](http://en.wikipedia.org/wiki/Search_problem) correspond to relations. NP is a class of decision problems. There is a functional version of NP - FNP class, and perhaps the script (very confusingly) refers to it. Beware, "[Entscheidungsproblem](http://en.wikipedia.org/wiki/Entscheidungsproblem)" has another meaning, namely it refers to unsolvability of halting problem.
Comment: Thank you very much for the feed-back. I think you may be right about the FNP class. This is the class of all problems for which the corresponding decision problem is in NP, right? So for a given instance $I\in \mathcal I$, the decision problem asks: "$Sol(I) \ne \emptyset$?" and a certificate $y$ for $I$ would be some $y\in Sol(I)$. So that the algorithm $\mathcal A$ would check (in polynomial time in $|I|$), whether $y \in Sol(I)$. This seems to make sense.
Comment: Sam: Yes, this is true, if $(x,y) \in R$ can be decided in polynomial time, then the decision problem whether such $y$ exists given some $x$ is in NP. Looking back at the original question, your doubts about what is the relation between $\mathcal A$ and $Sol(I)$ are justified. I think it's better to require that $\mathcal A$ accepts exactly the set $\{(I,y): y \in Sol(I)\}$.
Comment: O.k. I have now read on in the script, and later on they state in a proof: "Let $\Pi = \langle \mathcal I, Sol\rangle$ be an arbitrary problem in NP, and let $\mathcal A$ be a polynomial-time algorithm, which decides for each pair $I\in \mathcal I$ and $x \in \Sigma^\ast$, whether $x\in Sol(I)$..." So it might be that they've tried to avoid technicalities best as possible (i.e. avoiding formal-language theory) and then simply have stated a slightly wrong/bad definition. The course is more of an overview anyways. Thanks again. =)


REACT DROPZONE: Get data:images after upload

Question: As topic, I want get data:images after upload. I get that if only upload one image. If multiple images how to array it in console?
constructor(props) {
  super(props);
  this.state = {
    image: null
  };
}

onDropMain(mainImage) {
    var that = this
    let reader = new FileReader()
    reader.readAsDataURL(mainImage[0])
    reader.onloadend = function() {
        var result = reader.result
        that.setState({
            mainImage: result
        });
    }
    console.log(reader);
}

This is how I get single data:images, but how about multiple images? Anyone has experience in this?
Answer: To read multiple images:
1. First define a function that will read a single file.
2. Use any loop to call that function for each entry of the array.
3. Use array in state variable to store the result, instead of a single variable.
constructor(props) {
  super(props);
  this.state = {
    image: []
  };
}

Use this function to read multiple files:
onDropMain(mainImage) {
    var that = this;

    function read(file){
        let Reader = new FileReader();
        Reader.onload = function (event) {
            let image = that.state.image.slice();
            image.push(event.target.result);
            that.setState({image}, () => console.log(image));
        };
        Reader.readAsDataURL(file);
    }

    if (mainImage && mainImage.length) {
        [].forEach.call(mainImage, read);
    }
}

Check the answers of this question for details about [].forEach.call(mainImage, read).


"Element type is invalid: expected a string" in the definition of my main component: export const Autocomplete = (props) => {....}

Question: I am new in react.
My main component is defined in the way:
import React from "react";
import { useState } from "react";
export const Autocomplete = (props) => {

return (

  hello

);
};

I am getting this error:

Element type is invalid: expected a string (for built-in components)
or a class/function (for composite components) but got: undefined. You
likely forgot to export your component from the file it's defined in,
or you might have mixed up default and named imports.

this is my index.js
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
 <StrictMode>
  <App />
 </StrictMode>,
rootElement
);

what am I doing wrong? thanks
Answer: Answer
You've made your main component a named export named Autocomplete, but you are importing a default component called App.
Try this:
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import { Autocomplete } from "./App";

const rootElement = document.getElementById("root");

ReactDOM.render(
 <StrictMode>
  <Autocomplete />
 </StrictMode>,
rootElement
);

Explaining Named vs Default Exports
There are two ways of exporting and each way requires you to import the exported member differently.
Named Export/Import
Named exports have to be imported using the same name as the exported member. The import will also have braces around the imported members. You can export multiple members from a single file.
foobar.js
export const foo = 'foo';
export const bar = 'bar';
const baz = 'baz';

// or

const foo = 'foo';
const bar = 'bar';
const baz = 'baz';
export {foo, bar};

main.js
import { foo, bar } from './foobar'

Default Export/Import
Default exports can be imported using any name you want. There will be no braces around the import. You can only default export a single member from a file.
foobar.js
export default {foo: '', bar: ''}; // directly exporting the value (an object), no variable declaration involved

// or

const foobar = {foo: '', bar: ''};
export default foobar;

main.js
import foobar from './foobar';
const foo = foobar.foo;
const bar = foobar.bar;

// or

import whatever from './foobar';
const foo = whatever.foo;
const bar = whatever.bar;

Named and Default Export/Import
You can also have both default and named exports from the same file. You may have seen this with React.
foobar.js
export const foo = 'foo';
export const bar = 'bar';
export default foobar = 'foobar';

main.js
import myFoobar, { foo, bar } from './foobar'
import React, { useState } from 'react';

Comment: thanks for answering, but I do `export default function Autocomplete(props)` it will work. Why?
Comment: @yavg I've updated my answer with an explanation of named vs. default exports.