Php session fixation example and fixes

Question: My question is about this summary on session fixation:

Alice has an account at the bank http://unsafe.com/. Unfortunately, Alice
is not very security savvy.
Mallory is out to get Alice's money from the bank.
Alice has a reasonable level of trust in Mallory, and will visit
links Mallory sends her.

Mallory has determined that http://unsafe.com/ accepts any session
identifier, accepts session identifiers from query strings and has
no security validation. http://unsafe.com/ is thus not secure.
Mallory sends Alice an e-mail: "Hey, check this out, there is a cool new
account summary feature on our
bank,http://unsafe.com/?SID=I_WILL_KNOW_THE_SID". Mallory is trying to
fixate the SID to I_WILL_KNOW_THE_SID.
Alice is interested and
visits http://unsafe.com/?SID=I_WILL_KNOW_THE_SID. The usual log-on
screen pops up, and Alice logs on.
Mallory visits http://unsafe.com/?SID=I_WILL_KNOW_THE_SID and now has unlimited access
to Alice's account. (credit: RichieHindle)

Questions:
Q1 - Is there a way to explicitly prevent the site from accepting any
   session identifier?
Q2 - I don't use the $_GET variable on my site so is there a way to prevent accepting session identifiers from query strings?

Notes: I'm using php 5.4.3 with SSL and will also use session_regenerate_id..
Comment: Worth a read http://phpsec.org/projects/guide/4.html
Answer: You could set the options martinstoeckli mentioned in his answer, but this won't prevent session fixation. It makes session fixation a little harder to attack, but it doesn't prevent it.
As ServerBloke mentioned, you prevent session fixation by using session_regenerate_id() immediately after verifying the user's login information and before you show the first page that requires authentication.
Making it harder for the attacker to exploit session fixation does not prevent session fixation. You must generate a new session ID.
More and more, people are using public unsecured untrusted wi-fi hot spots. Sessions can be sniffed from the air. On a physical network, they can be sniffed off the wire. They can also force you to visit any URL by employing a man-in-the-middle attack. So, session fixation is still a problem, even if the attacker can't send you URLs.
Knowing that sessions (and passwords) can be sniffed, there is another step that is required to prevent session hijacking. That is HTTPS (TLS/SSL).
All protected pages that require authentication should be accessed only over HTTPS. So, the login page (the one where the user sends their username and password) should be accessed via HTTPs. In that same script, you must regenerate a new sessionID. All pages for the remainder of the session must then be accessed via HTTPs to protect the new session ID.
Here's an example pseudocode login.php script:
// Force SSL
if($_SERVER["HTTPS"] != "on") {
  die('Must login via HTTPS');
}

// Load the current sessionID
session_start();

// Validate the login information, being sure to escape the input
...
if (! $valid) {
  die('Invalid login');
}

// Start the new session ID to prevent session fixation
session_regenerate_id();

// Clear the old session
$_SESSION=array();

// Log them in
$_SESSION['user_id'] = $userID;

Comment: Ok. so my ENTIRE site is https/SSL. A user goes to the homepage and the homepage has a login form. at the top of that page I should do session start() and session_regenerate_id? If I'm using SSL then why do I need to regenerate the id? Isn't that just going to negatively impact performance? Also: if I should still use session_regenerate_id even though I have full SSL, then do I need to do it on subsequent pages and also on a timer (every 30 minutes or so?
Comment: I don't know what you mean when you say your entire site is HTTPS/SSL, unless you're forcing SSL by detecting it as above, and redirecting. You'll regenerate the session on the page (PHP script) that processes the login submission, not the home page. It won't affect performance to regenerate the session id one time immediately after you verify the user's credentials. Regenerating the session is still important to prevent session fixation, even with SSL, because there are other ways to exploit session fixation (via a shared computer, etc.).
Comment: @Hoxton, to make a long story short, why not prevent session fixation rather than fight against each way to exploit it?
Comment: 1. I have a .htaccess file that redirects every http page to https so every single page uses SSL encryption.

2. So if the user logs in using valid credentials then I do session start() & Session_regenerate_id or do I first do session start, then they login, then I do session_regenerate_id? Also: I've read I should do it on a timeout too (after 30 minutes).
3. Yes, prevention is better than cure. So by that you mean just use session_regenerate_id or did you have another prevention method in mind?
Comment: @Hoxton., yes, by prevention I mean session_regenerate_id. You need session_start() before session_regenrate_id() because it regenerates the id for the current session and you don't have a session without first doing session_start(). Take a look at first [user provided example](http://www.php.net/manual/en/function.session-regenerate-id.php#107323) for session_regenerate_id(). The .htaccess method should be fine. You will set the login (for example `$_SESSION['user_id'] = $userID`) after session_start(), session_regenerate_id(), and clearing the session.
Answer: If you use session_regenerate_id() everytime a user logs in you will prevent session fixation. As the user logs in, their fixated session ID will be regenerated and thus stopping the attack.
Comment: Yeah but I'm still a bit confused about this.
Heres's usage for this from [link]http://phpsec.org/projects/guide/4.html[/link] but it's very confusing, can anyone clarify?
[code]
session_start();

if (!isset($_SESSION['initiated']))
{ session_regenerate_id(); $_SESSION['initiated'] = true;}
[/code]

"The problem with such a simplistic defense is that an attacker can simply initialize a session for a particular session identifier, and then use that identifier to launch the attack."
Comment: You don't need an `initiated` variable. All you need to do is regenerate the session ID when a user successfully logs in.
Answer: Question 1) If your application needs a session, you will have to send some kind of session id. If your application doesn't use sessions, then there is no need to call session_start(), and ids (whether sent by URL or cookie) are simply not used.
Question 2) You can configure PHP, to accept session ids exclusively from cookies, and to ignore ids from the URL (see session.use_only_cookies). If you do that, you should also check, that the option session.use_trans_sid is set to 0 (this is the default).
Comment: Thanks.
RE: Answer 1: My application does need a session so I think your answer 2 covers the solution.
RE: answer 2: session:use_only_cookies : if this just ignores ids from the url, then it sounds too good to be true,  Are there any side effects? Also: if the default value of session.use_trans_sid = 0, do I need to explicitly set it to 0 just to make sure?
Comment: @Hoxton - It _is_ the recommended way, the only drawback is, that ids in the URL are ignored... This is an advantage in the view of security, but of course it blocks users/systems from using your site, which cannot use cookies (a rare case today). If your site already has use_trans_sid set to 0, there is no need to set it again.
Comment: Ahh you meant in the php.ini file.. These are the settings for my site:
session.use_cookies On
session.use_only_cookies On
session.use_trans_sid 0

Does that mean I'm covered against the fixation attack listed above?
As previously mentioned I'll also be regenerating the id but I'm unsure which solution is best:
1. Start the session first (without SSL), then let the user login (using SSL) and regenerate the session id or:
2. user logs in (using SSL) and session_regenerate_id is used later if they try to make changes to their profile, etc.
Comment: @Hoxton - I read your comment again, i only meant that you should **check** that use_trans_sid is set to 0. You can do this, writing a php file calling the function `phpinfo()` and running it on the server.
Comment: @Hoxton - If you are really that interested in how to secure your session, i would recommend to read this article [Secure session cookie with SSL](http://www.martinstoeckli.ch/php/php.html#ssl_nomim_cookie). It will make session fixation useless (even when successful), because it separates authentication and maintaining the session.
Comment: I read all the info at your link and am not sure I agree with: "Using the session-cookie only to maintain the session, and not for authentication, is a good thing to do, even when the whole site runs with HTTPS only." because, from php.net: "Prediction refers to guessing a valid session identifier. With PHP's native session mechanism, the session identifier is extremely random, and this is unlikely to be the weakest point in your implementation." and since the entire site is SSL, wouldn't the effect of 2 cookies instead of 1 only impact performance negatively?
Comment: @Hoxton - The randomness of the session-id is indeed not the problem here, because nobody tries to truly _guess_ the id. There are a lot of different approaches to hijack the session id, session-fixation is only one of them. Some are based on unsafe configurations, like the `use_trans_sid` when PHP itself would put the id into the URL, and it is difficult to know all the possible weaknesses. All have in common, that you get the privileges, if you get the session-id. It's only logical that attackers target the session-id, but with the second cookie you can prevent even future threats.
Answer: I don't fully understand, is this a really problem?
Q1. I think you need to check is there are a SID recieved from GET of COOKIE in you Session storage already (for example, in database). If YES - its'okay, if no, create a new one on server side and do http redirect with new SID.
Q2. I don't use a php 5.4 but i think the following code will help:
unset($_GET['sid'])

Update: I think the common fix is than only the backend-server can generate a SID identifiers. No user posibilites for this!
Comment: 1. Yes, session fixation attacks really are a problem.

2. I'm not sure your code example would work because as mentioned above, I don't use the $_GET variable on my site.

3. The common fix that you mention. Do you mean the solution listed in the other answers to this question?

Php session fixation example and fixes


Rahmenprogramm nicht gefunden für Include ZR_PO_NUMBER_UC_INT

Question: I try to create an include according to the tutorial SAP ABAP Include Programs. Unfortunately I get the message: Rahmenprogramm nicht gefunden für Include ZR_PO_NUMBER_UC_INT
*&---------------------------------------------------------------------*
*&  Include           ZR_PO_NUMBER_UC_INT
*&---------------------------------------------------------------------*
PROGRAM ZR_PO_NUMBER_UC_INT.
CONDENSE i_PO_NUMBER_UC_1. e_PO_NUMBER_UC_INT =  i_PO_NUMBER_UC_1.

Comment: I'd suggest not to trust that tutorial. Having an introductory statement (https://help.sap.com/abapdocu_731/en/abapprogram.htm) at the beginning of an include is not a good idea without further explanation, and having top-level code (i. e. anything but a class, a module or a subroutine) in an include is a bad idea as well.
Answer: what you're missing is the main program, the report that includes your Include. In your tutorial this program is created in Step 5. So you need something like this:
REPORT Z_INCLUDINGTEST.

INCLUDE ZR_PO_NUMBER_UC_INT.

...


Google Sheets Time-driven Trigger. Need Better Time Accuracy

Question: I have a script in Google to email the PDF of a Google Sheet on a time-driven trigger. The problem is that the range accuracy in time is 60 min. Thats stupidly inaccurate. I want this script to trigger every other day (or every day if I have to) at 10:10AM. Not between 10am-11am. 10:10am.
Is this possible?
Answer: You can use GAS to build a time-driven trigger that is more accurate, but still may not be as accurate as you would like - the documentation states "plus or minus 15 minutes".


alias to replace a text in file

Question: here is a  practical situation.I facing some of my files where there is a common string in these files.I usually will open vi and do some thing like
:%s/text/replacement/g

and I have to do it in many files many many times.
Is there some easy way to do it or some sort of alias that I can create for the same?
Answer: You can use find for finding the target files and then pipe it to sed:

find | xargs sed -i 's/foo/bar/g'

Only replace in .txt files:

find . -name "*.txt" -print | xargs sed -i 's/foo/bar/g'

(from this blog post)
Answer: Ah yes, time for a perl oneliner.  How about this?
perl -pi -e 's/old text/new text/' file

or maybe you want to change all the *.txt files in the current directory?  In that case, how about combining it with GNU parallel:
parallel perl -i.bak -pe 's/foo/bar/' ::: *.txt

With parallel, the ::: means use eveything after this as input files.
or, to change all the txt files in the current directory and below:
find . -name \*txt -print0 | parallel -q -0 perl -i.bak -pe 's/old text/new text/'

Note the -i.bak saves a backup copy of every file that you change, in case you make a mistake.  You can leave that out if you are feeling dangerous.
Anyway obviously the sed answer is the standard one, but there are some fun alternative ways to do it too.  Also if you have a lot of files gnu parallel will be significantly faster as it runs multiple copies in parallel (as one would hope, given the name).
Comment: this is really some new thing for me.I will test it.
Answer: Check out sed, something like this:
sed -i 's/text/replacement/g' file

alias to replace a text in file


How to read and write values in excel using java?

Question:

Sample Excel --> Sorry I'm not allowed to attached a image..
TC No. | Title | Result
1 | State and Vin | Failed
2 |  State and Reg Code | Passed
3 |  Booking a Test Drive | Passed

public class sampleTest{
public static void main(String[] args) throws Exception {
         int iTest = 2, iTest2 = 3;
          if (iTest == iTest2){
              //It will pass a value into the excel (e.g. "Passed")
          }
          else{
             //It will pass a value into the excel (e.g. "Failed")
          }
    }

My program's goal is to generate a report by getting the Passed and Failed results from my tests. My main problem here is on how to read the results from the excel and place the value "Passed" or "Failed" under Result column.
Comment: You can alternatively create a CSV file with the fields that you mentioned and open the csv file with excel.
Comment: I already have an existing excel file. What I need to do is to write "Passed" or "Failed" under the Result column. By the way, I can't use csv file because I need to create a pie chart within the excel file.
Comment: I have edited my answer to demonstrate how to open a xls file and read the content
Answer: Download the apache poi jar from here
Go through these examples which demonstrates how to read/write xls data from a java program
Sample help code:
public static void main(String[] args) throws IOException {
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("sheet");
        Row row = sheet.createRow((short) 0);

        row.createCell(0).setCellValue(1.2);
        row.createCell(1).setCellValue(wb.getCreationHelper().createRichTextString("This is a string"));
        row.createCell(2).setCellValue(true);

        FileOutputStream fileOut = new FileOutputStream("workbook.xls");
        wb.write(fileOut);
        fileOut.close();
    }

This might help you to get started.
The whole flow is:

Create a workbook => The main xls file
Then create a sheet
Then create a row.
For each row create as many cells as you want and fill the cells with different values
Write the workbook like a file.

There can be multiple type of cells see this for more info.
To know how to read an excel file:
InputStream myxls = new FileInputStream("workbook.xls");
        wb     = new HSSFWorkbook(myxls);

         sheet = wb.getSheetAt(0);       // first sheet
         row     = sheet.getRow(0);        // third row
        HSSFCell cell   = (HSSFCell) row.getCell((short)1);  // fourth cell
        if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
            System.out.println("The Cell was a String with value \" " + cell.getStringCellValue()+" \" ");
        } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
            System.out.println("The cell was a number " + cell.getNumericCellValue());
        } else {
            System.out.println("The cell was nothing we're interested in");
        }

For more info see this
Comment: Thanks for that idea. however I already have an existing excel file created - so what I need to do is to write "Passed" or "Failed" under the Result column. i don't know how can i get the exact column so that i can insert the value "Passed" or "Failed" status. I will just read all the answers that was given by -didxga and -Mikko Maunu.
Answer: Via library that will be your interface to Excel document. One option is Apache POI. Excel example code can be found from here.
Other option is Java Excel API.


show amount of results for exposed filter

Question: I have a couple of exposed filters to filter the content in my view.
Most of them are taxonomy terms, now i would like to show how many nodes are tagged with that term behind the taxonomy term.
example:
London (5)
Paris (3)
Madrid (2)
...

Any idea how i can do this?
Answer: Here is some sample code to do this:
function hook_form_alter(&$form, &$form_state, $form_id) {
    switch($form_id) {
        case 'views_exposed_form':

            $allowed_categories = db_query("SELECT 1 as tid, "Term Name (2)" as `name`")->fetchAllKeyed();
            $allowed_categories = array_reverse($allowed_categories, TRUE);
            $allowed_categories['All'] = '- Any -';
            $allowed_categories = array_reverse($allowed_categories, TRUE);

            $form['field_category_tid']['#options'] = $allowed_categories;

            break;
    }
}

Just change the query to return 2 columns - the tid and the name with a count.
Answer: i created a module with a hook_form_alter().
In that function i created a query that counted the nodes attached to a certain taxonomy term and added this number at the end of every term.
Comment: Any chance to see the code you've used for this? THX in advance!
Comment: @Volker: I've just added an answer with some sample code...
Answer: function hook_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id){
    case 'views_exposed_form':
      if ($form_state['view']->name == 'viewname') {
    //must add some bool so this doesn't get into infinite loop
    if(!isset($form_state['view']->gg)){
      $form_state['view']->gg = TRUE;
      $form_state['view']->execute();
    }

    $form['results_count'] = array(
      '#markup' => t('!count results match your criteria', array('!count' => ''.$form_state['view']->total_rows.'')),
      '#weight' => -99,
    );
      }

      break;
  }
}

Comment: Hello and welcome. While this code might answer the question, it would be in a good tone to explain *why* and *how* it is supposed to work, so the OP could learn from it, not only rely on others to write pieces for him. It looks like ideas and knowledge are what he is after, and that's a good thing that should be encouraged :)
Comment: the loop thing was a very useful advice ! thks
Answer: Couple of links (may be useful)

Module Taxonomy Menu, that has count option.
Question about these things, but without trusted answer.
Answer: This is an example from my real site. field_marka_prochnosti is a field of a node represented by a taxonomy vocabulary. I used phpMyAdmin to learn the name of a table and the name of the field of that table to make a query. bricksale_omega is the name of my theme.
function bricksale_omega_form_alter(&$form, &$form_state, $form_id) {
switch($form_id){
case 'views_exposed_form':

  foreach ($form['field_marka_prochnosti_tid']['#options'] as $tid => &$value) {
    $query = db_select('field_data_field_marka_prochnosti', 'f')
            ->condition('f.field_marka_prochnosti_tid', $tid);
    $query->addExpression('COUNT(*)');
    $count = $query->execute()->fetchField();
    $value = $value . ' (' . $count . ')';
  }

  break;
  }
}


sort two files by header so that they are in matching field order

Question: I have two files that each have 700 fields, where 699/700 of the fields have matching headers. I would like to reorder the fields so that they are in the same order in both files (though which order is irrelevant). For example, given:
File1:
FRUIT MSMC1 MSMC24 MSMC2 MSMC10
Apple 1 2 3 2
Pear 2 1 4 5

File2:
VEG MSMC24 MSMC1 MSMC2 MSMC10
Onion 2 1 3 2
Radish 0 3 9 3

I would like both files to have the first field as the fields that are not common to both files, then the rest of the fields in the same order in both files, for example one possible outcome would be:
File1:
FRUIT MSMC1 MSMC2 MSMC10 MSMC24
Apple 1 3 2 2
Pear 2 4 5 1

File2:
VEG MSMC1 MSMC2 MSMC10 MSMC24
Onion 1 3 2 2
Radish 3 9 3 0

Comment: Are the fields separated by space or any whitespace?  Are there ever any quotes or escapes, e.g. `"Green Onion" 1 2 3 4` or `Green\ Onion 1 2 3 4`
Answer: Using data.table, this can help you
First read the files,
 library(data.table)
 dt1 <- fread("file1.csv")
 dt2 <- fread("file2.csv")

then, get the names of the fields, the common ones
 ndt1 <- names(dt1)[-1]
 ndt2 <- names(dt2)[-1]
 common <- intersect(ndt1, ndt2)

and now you can just apply the new order
 setorder(dt1, c(ndt1[1], setdiff(ndt1, common), common))
 setorder(dt2, c(ndt2[1], setdiff(ndt2, common), common))

Comment: In base R, just `common <- intersect(names(dat1),names(dat2)); dat1 <- dat1[c(setdiff(names(dat1),ints),ints)]` etc would be equivalent.
Comment: and the dplyr/ggplot equivalent `library(dplyr); library(ggplot2); as_data_frame(dt1)[ndt1[1] %>% c(setdiff(ndt1, common)) %>% c(common)]`
Comment: How could these answers be modified if one file were to be a subset of the other (not all columns from file 1 are in file2)?
Comment: can you provide an example? the script does not assume there is any shared columns... or the other way around. if all columns of 1 are in 2, then you will just have `setdiff(ndt1, common)`  empty.
Comment: @theo4786 See my updated answer. Includes the `map` construct.
Answer: A perl solution that leaves the first file as is and writes the second file with the columns arranged in the same order as the first file. It reads the 2 files supplied on the command line (which follow the script name).
Update: Added the map $_ // (), phrase to allow the second file to be a subset of the first file. Answer to his question How could these answers be modified if one file were to be a subset of the other (not all columns from file 1 are in file2)? – theo4786
#!/usr/bin/perl
use strict;
use warnings;

# commandline: perl script_name.pl fruits.csv veg.csv

my (undef, @fruit_hdrs) = split ' ', <> and close ARGV;

my @veg_hdrs;

while (<>) {
    my ($name, @cols) = split;

    # only executes for the first line (header line) of second file
    @veg_hdrs = @cols unless @veg_hdrs;

    my %line;
    @line{ @veg_hdrs } = @cols;

    print join(" ", $name, map $_ // (), @line{ @fruit_hdrs } ), "\n";
}

Output is:
VEG MSMC1 MSMC24 MSMC2 MSMC10
Onion 1 2 3 2
Radish 3 0 9 3

Answer: In perl, the tool for this job is a hash slice.
You can access values of a hash as @hash{@keys}.
So something like this:
#!/usr/bin/env perl

use strict;
use warnings;
use Data::Dumper;

my @headers;
my $type;

my @rows;

#iterate data - would do this with a normal 'open'
while ( <DATA> ) {
  #set headers if the leading word is all upper case
  if ( m/^[A-Z]+\s/ ) {
      #seperate out type (VEG/FRUIT) from the other headings.
      chomp ( ( $type, @headers ) = split );
      #print for debugging
      print Dumper \@headers;
  }
  else {
     #create a hash to store this row.
     my %this_row;
     #split the row on whitespace, capturing name and ordered fields by header row.
     ( my $name, @this_row{@headers} ) = split;
     #insert name and type into the hash
     $this_row{name} = $name;
     $this_row{type} = $type;
     #print for debugging
     print Dumper \%this_row;
     #store it in @rows
     push ( @rows, \%this_row );
  }
}

#print output:
#header line
print join ("\t", "name", "type", @headers ),"\n";
#iterate rows, extract ordered by _last_ set of headers.
foreach my $row ( @rows ) {
    print join ( "\t", $row->{name}, $row->{type}, @{$row}{@headers} ),"\n";
}

__DATA__
FRUIT MSMC1 MSMC24 MSMC2 MSMC10
Apple 1 2 3 2
Pear 2 1 4 5
VEG MSMC24 MSMC1 MSMC2 MSMC10
Onion 2 1 3 2
Radish 0 3 9 3

Note - I've used Data::Dumper for diagnostics - those lines can be removed, but I've left them because illustrate what's going on.
Likewise reading from <DATA> - normally you'd open a file handle, or just use while ( <> ) { to read STDIN or files specified on command line.
The ordering of output is based on the last header line 'seen' - you can of course, sort that, or reorder it.
If you need to handle mismatching columns, this will error on the missing one. In this scenario, we can break out map to fill in any blanks, and use a hash for headers to ensure we capture them all.
E.g.;
#!/usr/bin/env perl

use strict;
use warnings;
use Data::Dumper;

my @headers;
my %headers_combined;
my $type;

my @rows;

#iterate data - would do this with a normal 'open'
while ( <DATA> ) {
  #set headers if the leading word is all upper case
  if ( m/^[A-Z]+\s/ ) {
      #seperate out type (VEG/FRUIT) from the other headings.
      chomp ( ( $type, @headers ) = split );
      #add to hash of headers, to preserve uniques
      $headers_combined{$_}++ for @headers;
      #print for debugging
      print Dumper \@headers;
  }
  else {
     #create a hash to store this row.
     my %this_row;
     #split the row on whitespace, capturing name and ordered fields by header row.
     ( my $name, @this_row{@headers} ) = split;
     #insert name and type into the hash
     $this_row{name} = $name;
     $this_row{type} = $type;
     #print for debugging
     print Dumper \%this_row;
     #store it in @rows
     push ( @rows, \%this_row );
  }
}

#print output:
#header line
#note - extract keys from hash, not the @headers array.
#sort is needed to order them, because default is unordered.
print join ("\t", "name", "type", sort keys %headers_combined ),"\n";
#iterate rows, extract ordered by _last_ set of headers.
foreach my $row ( @rows ) {
    print join ( "\t", $row->{name}, $row->{type}, map { $row->{$_} // '' } sort keys %headers_combined ),"\n";
}

__DATA__
FRUIT MSMC1 MSMC24 MSMC2 MSMC10 OTHER
Apple 1 2 3 2 x
Pear 2 1 4 5 y
VEG MSMC24 MSMC1 MSMC2 MSMC10 NOTHING
Onion 2 1 3 2 p
Radish 0 3 9 3 z

Here, map { $row->{$_} // '' } sort keys %headers_combined takes all the keys of the hash, returns them in order, and then extracts that key from the row - or gives an empty space if it's undefined. (thats what // does)
Answer: This will reorder the fields in file2 to match the order in file1:
$ cat tst.awk
FNR==1 {
    fileNr++
    for (i=2;i<=NF;i++) {
        name2nr[fileNr,$i] =  i
        nr2name[fileNr,i]  = $i
    }
}
fileNr==2 {
    printf "%s", $1
    for (i=2;i<=NF;i++) {
        printf "%s%s", OFS, $(name2nr[1,nr2name[2,i]])
    }
    print ""
}

$ awk -f tst.awk file1 file2
VEG MSMC1 MSMC24 MSMC2 MSMC10
Onion 1 2 3 2
Radish 3 0 9 3

With GNU awk you can delete the fileNr++ line and use ARGIND instead of fileNr everywhere else.


To show custom user fields in a view does not work for user with uid 1

Question: I have a view that shows some custom user fields as block on the users profile page. The permission of that view is set to »Access: Permission | View published content«. That means the view should be visible for any visitor.
This works fine on any user profile but not on the  profile of the administrator with the uid 1. On his profile page the view is empty.
Is this a bug or a wanted behaviour? How to solve this?
UPDATE: I tried to solve this by changing the view's access permissions but even if I set them to »none« or »Roles | All« it does not work.
Comment: Perhaps this is because the permission (can) "View Published Content" does not make sense for an admin ... i.e. if you could disable it, you might get locked out of your site...
Comment: @gl2748 It does not work with any permissions. I updated the question.
Answer: Try using "Access: Role" rather than "Access: Permission" and select all user roles (that you'd like to be able to see the view ...
Comment: No, this does not work. Sorry didn't mention that I did try that before…
Comment: What is inside your view?


What chord could the notes 'F A♭ E♭' form?

Question: Can someone please help me understand this chord progression that actually takes the listener from E♭ to B♭. There is a chord at the end of the phrase and I can't understand what chord it comes from. The notes are (F A♭ E♭). Let's call this chord "X".
Here is the progression so you can get this in context.

E♭, E♭, B♭, E♭, Cdim, X, B♭
Answer: It's common to omit some notes when forming a chord (for various reasons; depends on the instrument and the composer).
The aforementioned chord is a Fm7 (no5), which means that you play the notes that form the Fm7 chord (F A♭ C E♭), but you omit the 5th (C), thus getting Fm7 (no 5) or the notes F A♭ E♭.
One of the most common chord notes you're going to omit is the 5th. There is a great thread about this here (it's about omitting notes in jazz, but still it's worth a read):
Which notes are optional in jazz chords?
Answer: The X chord could be an Fm7 and that would perfectly fit in the E♭ scale with the other chords in the progression you mentioned.
Simplified explanation:
The diatonic triads in E♭ scale are: E♭ Fm Gm A♭ B♭ Cm Ddim.
Comment: Thanks, Is there anything else it could be that would give a stronger resolution to Bb? Fm7 sounds fine but I just want other options to hear what else it could be. The music book I have says the chord is a Bb7sus4b9 chord which seems a bit over-the-top since I doubt the composer was thinking of it like that.
Comment: You're not going to find a much stronger resolution than the v7 to i. (In addition, in my experience, you're not going to find a better match for those three notes).
Answer: The other answers are 100% correct: with a motion to E♭ major, the expected diatonic chord here is Fm7 with an omitted fifth (C).
But for the sake of completeness, you could also turn this into an F half-diminished seventh chord, or Fm7♭5. Doing so would mean that this omitted fifth would need to be a C♭. But notice that, since there's no C♭ in the key signature of E♭ (the starting point of this phrase), this is an example of what we call mode mixture. We say that this chord (and the C♭ itself) are borrowed from E♭ minor, the parallel key of E♭ major.
Perhaps also of interest: viewing this chord as a half-diminished seventh makes it enharmonic to the Tristan chord.
Answer: Two alternate progressions:  E♭ -> B♭  (Just do it!). In a march, it is normal to go from tonic in the first section to sub-dominant in the Trio section; why not do the reverse?  Second alternative, E♭ -> F -> B♭.  These keys sit next to each other in the circle of fifths; the transitions are easy on the ear.
[Personal experience- 40 years on keyboard, arranging, etc.]
Comment: How could he use F when he has a Ab?
Answer: I agree with the other answers that it's probably an Fmin7 chord. One thing I'd like to point out is that, in the context you gave, this gives the chord progression E♭, E♭, B♭, E♭, Cdim, Fmin7, B♭. The last three chords plus another E♭ wrapping around to the beginning of the progression are Cdim, Fmin7, B♭, E♭ - which is walking along the circle of fifths before resolving to E♭. This is a very common chord progression. So the interpretation of the chord as Fmin7 is especially likely to be correct!
Answer: One possible voicing/inversion of of {F A♭ E♭} gives rise to a B♭11 with an omitted root and 3rd.
That is to say, F is the fifth, A♭ is the minor 7th, E♭ is the 11th.
Cdim, B11, B♭ is plausible.


When do we need to define variables in loops?

Question: Why is the line "total = 0" necessary in this code?
def sum_to(n):
    total = 0  # <<< this line
    for i in range(n):
        total= total + i
    return total

Also, I've noticed the same for "while" loops and was just wondering if that statement represents the starting number (which is 0), or just as a a way to introduce a foreign variable into an inbuilt function.
Thank you!
Comment: You are performing an operation on a variable that doesn't exist if you do not predefine `total=0` outside of your for loop.
Comment: Did you try that code *without* the `total = 0` line?
Comment: What do you expect `total= total + i` to do if `total` didn't already have a value?
Answer: Basic answer
Python requires you to define the variable that you are going to use if you are doing operations on it.
For example
total+1

#error

NameError: name 'total' is not defined

total = int()
total+1
#output
1

Answer: You are correct that the statement total=0 represents the starting value of total.
If you don't initialize total=0 or some other such statement, the computer won't know what the starting value of total should be.
In other words, without initializing total=some_value_that_you_choose, computer wouldn't "know" enough about the starting value of total to make sense of your code.
Answer: It initialises the variable to a starting value before it is modified by the loop. Consider the alternative without it:
def sum_to(n):
    for i in range(n):
        total = total + i

    return total

On the first iteration of the loop it is asked to perform total + i, but it has never encountered total before and thus has no value it can possibly use for it.
If you ran that modified function you would get an error
UnboundLocalError: local variable 'total' referenced before assignment

telling you that you are attempting to access a variable that has never been assigned a value. In this case Python can see that you are eventually going to give it a value, hence "before assignment". In a different context where this is not true the error might be
NameError: name 'total' is not defined

which means the variable is completely unknown.


Erro ao fazer upload de ficheiros

Question: Pretendo fazer upload de ficheiros, onde insiro o nome do ficheiro em base de dados e o ficheiro numa pasta no servidor.
Estou a tentar desta forma:
HTML:
<form class="form5" method="post" enctype="multipart/form-data">

Add Arquivo...
<input type="file" id="arquivo" name="arquivo">

</form>

<button type="button" class="btn btn-danger" data-dismiss="modal">Cancelar</button>
<button type="button" class="btn btn-success" id="mensagem-sucesso" onclick="inserir_anexos()">Gravar</button>

JS:
function inserir_anexos()
{
    var dadosajax = {
        'CodigoUtente' : $("#CodigoUtente6").val(),
        'arquivo' : $("#arquivo").val()
    };
    $.ajax({
        url: './recebe_upload',
        type: 'POST',
        cache: false,
        data: dadosajax,
        error: function(){
            Swal.fire("Erro!", "Tente novamente. Caso persista o erro, contatar Administrador!", "error");
        },
        success: function(result)
        {
            $('.form5')[0].reset();
            Swal.fire('Boa!', 'Gravado com sucesso!', 'success');
        }
    });
}

o PHP tenho desta forma:
$CodigoUtente = mysqli_real_escape_string($conn, $_POST["CodigoUtente"]);
$Colaborador = $_SESSION['usuarioId'];
$pathToSave = "/var/www/html/wp-content/themes/sparkling/alimentacao";

if (!file_exists($pathToSave)) {
    mkdir("$pathToSave", 0777);
}

   if ($_POST['arquivo']) {
        $dir = $pathToSave;
        $tmpName = $_POST['arquivo']['tmp_name'];

        $name = $_POST['arquivo']['name'];
        preg_match_all('/\.[a-zA-Z0-9]+/', $name, $extensao);
        if (!in_array(strtolower(current(end($extensao))), array('.txt', '.pdf', '.doc', '.xls', '.xlms'))) {
            echo('Permitido apenas arquivos doc,xls,pdf e txt.');

            die;
        }

       if (move_uploaded_file($tmpName, $dir.$name)) {
            echo('Arquivo adicionado com sucesso.');
        } else {
            echo('Erro ao adicionar arquivo.');
        }

           $query = 'INSERT INTO raddb.UploadArquivo(CodigoUtente, arquivo, Colaborador)
           VALUES ( ?, ?, ?)';
           $stmt = $conn->prepare( $query );
           $stmt->bind_param("sss", $CodigoUtente, $name, $Colaborador);
           $stmt->execute();
    }

Mas quando faço gravar recebo esta mensagem na consola:

Permitido apenas arquivos doc,xls,pdf e txt.

E estou a fazer insert de um pdsf como mostro na imgem:

E na consola do browser o nome do ficheiro também é enviado, como mostro na imagem:

Mas nem insere na base de dados nem guarda o ficheiro pdf na pasta indicado.
Podem ajudar?
Answer: "nem insere na base de dados nem guarda o ficheiro pdf na pasta indicado"
Sim, por causa do die ele para o processamento e não insere. Essa validação pode ser mais simples, tente assim no lugar do preg_match_all e um regex:
$permitidos = array('txt', 'pdf', 'doc', 'xls', 'xlms');
$name = $_POST['arquivo']['name'];
$extensao = pathinfo($name, PATHINFO_EXTENSION);
if (!in_array($extensao, $permitidos)) {
    echo('Permitido apenas arquivos doc,xls,pdf e txt.');

    die;
}

Comment: alterei essa parte do código, mas continua a parar o processamento no die
Comment: sim, mas isso é esperado correcto? se a extensão não for permitida deve parar ai, senão vai inserir um arquivo inválido. Se fizer upload de um arquivo com extensão válida funciona? No na minha resposta o nome do input estava errado, veja se está testando com esse código que está agora pf
Comment: estou a fazer upload de um arquivo com a extensão pdf, é uma extensão válida, mas o processamento para sempre no die.
Comment: @RicardoPontual, `pathinfo()` retorna a extensão do arquivo sem o ponto o que faz co o que sempre caia dentro do 'if'
Comment: tem razão @AugustoVasques, testei aqui e estava com esse problema... copiei esse codigo de uma pagina aqui, mas colei o array que estava na pergunta e não me atentei nisso, vou atualizar a resposta
Answer: Está dando erro porque $_POST['arquivo'] retorna uma string obtida com o elemento <input type="file" id="arquivo" name="arquivo"> e quando faz...

$tmpName = $_POST['arquivo']['tmp_name'];
$name = $_POST['arquivo']['name'];

...tanto $tmpName e $name são indefinidos.
if ($_POST['arquivo']) {
        $dir = $pathToSave;
        $name = $_POST['arquivo'];
        // Não estou certo que temp seja uma pasta do cliente, acredito que deva ser o endereço de uma pasta dentro do servido mas a pergunta não deixa claro.
        $tmpName = pathinfo($name, PATHINFO_DIRNAME);

        // PATHINFO_EXTENSION retorna a extensão sem o ponto
        $extensao = pathinfo($name, PATHINFO_EXTENSION);
        if (!in_array($extensao, ['txt', 'pdf', 'doc', 'xls', 'xlms'])) {
            echo('Permitido apenas arquivos doc,xls,pdf e txt.');

            die;
        }

        // continue com o seu código a partir desse ponto

Answer: O problema estava ao enviar os dados no ajax. Para resolver o meu problema, alterei o js.
Assim a variável arquivo já não é enviada como string, mas sim como file
$(document).ready(function (e) {
 $(".form5").on('submit',(function(e) {
  e.preventDefault();
  $.ajax({
         url: "./recebe_upload",
   type: "POST",
   data:  new FormData(this),
   contentType: false,
         cache: false,
   processData:false,
   beforeSend : function()
   {
    //$("#preview").fadeOut();
    $("#err").fadeOut();
   },
   success: function(data)
      {
    if(data=='invalid')
    {
     // invalid file format.
     $("#err").html("Invalid File !").fadeIn();
    }
    else
    {
     // view uploaded file.
     $("#preview").html(data).fadeIn();
     $("#arquivo").val("");
     $("#dataModal5").modal("hide");
    }
      },
     error: function(e)
      {
    $("#err").html(e).fadeIn();
      }
    });
 }));
});

e no php ficou desta forma:
$codigo = $_POST['CodUtente'];
$Colaborador = $_SESSION['usuarioId'];

$pathToSave = "/var/www/html/wp-content/themes/sparkling/arquivo_psicologia/";

if (!file_exists($pathToSave)) {
    mkdir("$pathToSave", 0777);
}
if ($_FILES) {
   if ($_FILES['arquivo']) {
        $dir = $pathToSave;
        $tmpName = $_FILES['arquivo']['tmp_name'];

        $name = $_FILES['arquivo']['name'];
        preg_match_all('/\.[a-zA-Z0-9]+/', $name, $extensao);
        if (!in_array(strtolower(current(end($extensao))), array('.txt', '.pdf', '.doc', '.xls', '.xlms'))) {
            echo('Permitido apenas arquivos doc,xls,pdf e txt.');

            die;
        }

       if (move_uploaded_file($tmpName, $dir.$name)) {
            echo('Arquivo adicionado com sucesso.');
        } else {
            echo('Erro ao adicionar arquivo.');
        }

           $query = 'INSERT INTO raddb.UploadArquivo(CodigoUtente, arquivo, Colaborador)
           VALUES ( ?, ?, ?)';
           $stmt = $conn->prepare( $query );
           $stmt->bind_param("sss", $codigo, $name, $Colaborador);
           $stmt->execute();
    }
}

Erro ao fazer upload de ficheiros


How to display a block only for an article with a specific node id?

Question: I have quickly seen view reference and context module. Though they can display a view or block to a specific content type, I'm not sure if they can do it within a specific node.
As an example: I want to display a block only for an article with node id 3.
Can that be done?
Answer: I would steer clear of using PHP for block visibility.  If you type something wrong you can break any number of things.
Just go to your block settings, and take a look at the vertical tabs at the bottom of the page.  The first option is Pages.  Just change the radio button to "Only the listed pages" and enter node/3 in the box.
EDIT
If you use the Views Reference module mentioned in your question, then you can quite easily embed a Views block as one of your fields just as any other field.  The field itself can't be exclusive to a node ID, only an entity type.  However, you could just leave it blank for the other entities of the same type and use Field Permissions if you are worried about other people using the field incorrectly/at all.
One unrelated helpful hint with Views Reference - I generally tag my "reference-able" views with the same tag (i.e. Embeddable, Referenceable e.t.c.).  then you can easily select which Views to make available to the Views Reference field.
You MIGHT be able to embed blocks with Entity Reference combined with BEAN or Boxes, but I'm not 100% sure.  Failing this you are probably looking at breaking up the entire $content variable in the template and embedding it yourself (which would mean much more maintenance if fields get added or removed), using Views and turning the whole content types into blocks that can be positioned (MUCH effort).
Comment: Aaah, I see.  The question could probably have been clearer.  Either way, you're going to need more help, as the `module_invoke()` part will still render the block outside of  your `$content` variable unless you break up the entire variable and render everything separately in the template.
Comment: no my friend, lets suppose I want put a block between my node `body` . your method not ok with it.
Comment: I agree with Zhilevan because thats exactly is my purpose, put the block as part of the node content.
Comment: Ah, I also read the other answer wrong at first - I thought you meant PHP for block vsibility on the settings page.  I'll have my coffee now and come back later ;-)
Comment: @Chapabu be appetite :)
Answer: To render something inside a node body, you need an input filter  to be able to write something like [block:foo:bar] and have the bar block from the foo module rendered. Unfortunately, a dedicated module does seems to exists on Drupal.org. Actually, one exists but is for Drupal 5 and has only a development release.
Using the PHP filter as suggested in others answers is an easy option. But this is a hacky one and not recommended. It opens to gate to a lot of abuses and potential headache debugging code stored in the database.
Comment: If you search for it, you will find that a lot of stuffs in  core stuffs are considered hacky by core maintainers themselves. Just assist conversations at DrupalCons or follow issues in the issue queues. PHP filter is one of them. Yes it works, yes it allow site builders to quickly meets many needs. But for a developer this is a quick and (extremely) dirty solution that create hard to maintain website. It is also a security risk.
Comment: hacky? if php filter was hacky not cosider it as drupal core modules  :(. if roles with high permission admit use php filter there is no worring. at least it's implementable
Answer: You could try the Insert Block module. Still in dev, but may be useful.
Answer: You should be able to get this to work using the Rules block visibility module. Here is a quote from its project page:

The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:

Need to show a block only for users registered more than a month ago?
Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
What about displaying or hiding a block based on current weather conditions?

All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules intercept the URL corresponding to your article, which appears to be a node, with node id = 3.
Adding a Rules Condition like "if it is /node/3" is really like a getting started with Rules Conditions. If needed, just copy (import) the Rules example included in my answer to "How to make the permissions of a module more granular?" and finetune it a bit to fit your needs.
Answer: NEW
Enable php filter module ,  add new content in body section  do something like this picture
(load your module accrding below notes)

if we wanted to place this custom block into a page, we would simply substitute these values into our PHP code snippet (which we place in a node (page or other content type)) as follows:
Drupal 7

<?php
$block = module_invoke('block', 'block_view', 26);
print render($block);
?>

Drupal 6 And Earlier
<?php
$block = module_invoke('block', 'block', 'view', 26);
print $block['content'];
?>

Notice that the middle two terms ('block', 'view') always stay the same. You're simply updating the first and last term.
Comment: There are huge caveats needed when using the PHP filter. It should not be promoted as a good tool to do everything including the kitchen sink on a Drupal website. Because it store code in the database it prevent proper version tracking of that code. Leading to maintenance and evolution nightmares. Because it allow administrator to write any code on the page, it can easily lead to borken pages (ie. PHP Fatal Error) or worse, broken site (broken code in a block/node displayed on all pages including admin pages) hard to investigate and harder to fix.
Comment: I'm not sure why you would want to do this when there are settings in the UI for exactly what the op wants.
Comment: THis might be "similar" to the link mentioned but what Im looking is a module than a snippet of code.
Comment: @ARGO, ok I am expain in another way, see the edit


Questions about app I just submitted to the App Store

Question: First off, can apps have an underscore in the name? The name I chose was taken, but I realized that because of the logo and style of the game it would work with an underscore at the end, so that's the name I used in iTunes connect. Will Apple reject it for this? I haven't seen any apps with an underscore in them.
Second, I'm testing the release version of my app (compiled using the release settings), and my in app purchase no longer works. It says invalid username/password, but it doesn't say sandbox mode. Is this normal? Will it work whenever the app is released?  Also, will the iAds load real ads and will Game Center not be in sandbox mode? I'm pretty sure Game Center wasn't in sandbox the first time I started the release, but now it is.
Thanks in advance for the help!
Comment: Is there a specific way you have to search for it? When I search for _ or "_" only two apps show up, and neither have an underscore.
Comment: My mistake. Sorry. I was looking at the suggested searches when you enter _. You're right though. When I hit search it only has two apps. Sorry.
Answer: Relax... Take a deep breath and calm down. The IAP is most likely not yet approved, iAds will show just fine, and GameCenter login depends more on if you use a test account or not, and it will be fine most likely.
First app?
:)
Comment: Yep! Thanks, I figured that was the case. The only thing I'm still kind of concerned about is the underscore. I haven't been able to find an app in the App Store with one, even though it was allowed in iTunes connect.
Comment: Only Apple will be able to give you an answer on that one definitely.


Localizar o índice do maior e do menor valor de um array

Question: Como faço para localizar a posição do maior e menor elemento de um array em JavaScript?
Com o reduce eu consegui localizar o maior e o menor elemento, porém preciso pegar a posição (índice) também deles dentro do array.
Maior numero:
var array = ["885.9", "984.9", "444.9", "528.9", "528.9"];
var maior_numero = array.map(Number).reduce(function(numero1, numero2) {
  return Math.max(numero1, numero2);
});

console.log(maior_numero );

Menor número:
var array = ["88", "999", "12", "123", "230"];
var menor_numero = array.map(Number).reduce(function(numero1, numero2) {
  return Math.min(numero1, numero2);
});

console.log(menor_numero );

Comment: Obrigado Wallace pelo retorno, então esse código que você me ajudou está pegando o valor do elemento. Além do valor preciso pegar em qual posição ele se encontra no array, poderia me ajudar?
Comment: Acho que o `reduce` aí é meio desnecessário.  Você poderia ter feito algo como `Math.max.apply(null, ["885.9", "984.9", "444.9", "528.9", "528.9"])`
Answer: Você pode utilizar um for simples, armazenando os índices do maior e menor número e modificando-os, se necessário.
Desse modo, você só precisará de varrer o array uma única vez.
Algo assim:

function indexes(arr) {
  if (!arr.length) {
    return null;
  }

  let max = 0;
  let min = 0;

  for (let i = 0; i < arr.length; i++) {
    const current = arr[i];

    if (current > arr[max]) {
      max = i;
    }

    if (current < arr[min]) {
      min = i;
    }
  }

  return { max, min };
}

console.log(indexes([3, 5, 6, 2, 1, 4])); // { max: 2, min: 4 }
console.log(indexes([1, 2])); // { max: 1, min: 0 }
console.log(indexes([])); // null

Não faz muito sentido você passar diretamente um array de strings para Math.max ou algo do tipo, já que é o tipo de dado incorreto. É pertinente converter os elementos antes de tentar compará-los, ou você pode acabar encontrando algumas situações bizarras, já que a comparação entre strings é diferente da comparação entre números.
Podemos modificar o código acima para lidar com arrays de strings:

function indexes(arr) {
  if (!arr.length) {
    return null;
  }

  let max = 0;
  let min = 0;

  for (let i = 0; i < arr.length; i++) {
    const current = parseFloat(arr[i]);

    if (current > parseFloat(arr[max])) {
      max = i;
    }

    if (current < parseFloat(arr[min])) {
      min = i;
    }
  }

  return { max, min };
}

console.log(indexes(["885.9", "984.9", "444.9", "528.9", "528.9"])); // { max: 1, min: 2 }

O JavaScript possui alguns mecanismos nativos de coerção automática de tipo, mas nem sempre fazem sentido. Para evitar problemas (que de fato ocorrerão se você não tratar os dados da forma correta — veja um exemplo aqui), prefira sempre realizar conversões explícitas. :-)
Comment: Muito obrigado Luiz Felipe, me ajudou muito! Abraço!
Answer: Para pegar o valor maior ou menor, você pode fazer simplesmente assim:
var arr = ["885.9", "984.9", "444.9", "528.9", "528.9"];
var maior = Math.max.apply(null, arr)

Agora para pegar a posição basta usar indexOf

var arr = ["885.9", "984.9", "444.9", "528.9", "528.9"].map(Number);
var maior = Math.max.apply(null, arr)

console.log(maior);

console.log(arr.indexOf(maior));

Note que, no caso do indexOf, precisei chamar map(Number), isso porque indexOf considera o tipo da variável. Como Math.max retorna Number, indexOf retornaria -1, por não encontrar o valor do mesmo tipo e mesmo valor (já que seu array é uma lista de strings).
Para não precisar converter tudo com o map, você poderia também usar um toString() no retorno de Math.max ou Math.min.

var arr = ["885.9", "984.9", "444.9", "528.9", "528.9"];
var maior = Math.max.apply(null, arr)

console.log(maior);

console.log(arr.indexOf(maior.toString()));

Simplificando o código para compreensão:
var arr = ["885.9", "984.9", "444.9", "528.9", "528.9"];

var maior = Math.max.apply(null, arr)
var posicao_maior = arr.indexOf(maior.toString()));

var menor = Math.min.apply(null, arr)
var posicao_menor = arr.indexOf(menor.toString()));

Nota: Para encontrar o valor de Math.min, a regra é a mesma do código que fiz acima com Math.max, basta substituir.
Comment: Muito obrigado Wallace, me ajudou muito também! Abraço!
Answer: Amigo, outra sugestão para resolução é:


Ionic Cordova FCM Error node:844

Question: I get the below error when I try to run or to build android, after installing
cordova-plugin-fcm Plugin.
(node:844) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Invalid data, chunk must be a string or buffer, not object
(node:844) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exxit code.
have anyone any idea?
Answer: Remove the android platform:
ionic cordova platform remove android

Then reinstall:
ionic cordova platform add firstname.lastname@example.com

Now you should be able to install cordova-plugin-fcm without errors:
ionic cordova plugin add cordova-plugin-fcm

Comment: Thanks for your answer, but  I'm still getting the same error.
Comment: Try with a new project and add the platform with email@example.com

Ionic Cordova FCM Error node:844


Create printer localport from a network printer in windows 7

Question: I'm having a problem to install a printer using localport,
The printer is installed on a pc with windows 7 and I need to install it in another PC with Windows 2008 R2 creating a new localport for the network printer
but when I create the port tells me "access denied", the pc with widnows 7 has an simple account with no password and all permissions assigned to the printer (If I install the network printer from the IP, without localport, it print fine)
I need to install the printer using localport because I need to print from a java web using glassfish and also I need not have to create a user account with password in windows 7
How I can do this?
Comment: By "localport" do you mean like LPT1, etc?
Comment: i mean creating a new localport that point to \\192.168.1.104\HPLaserJ, for example, when i install the network printer locally. link: http://support.microsoft.com/kb/282842
Answer: You can do this even as a non-administrator: net use lpt1 \\192.168.1.104\HPLaserJ. This will map the printer to your LPT1 port.
If you just want a regular install of a network printer, browse to \192.168.1.104, right-click the printer and choose "Connect".
If this fails, then you have a sharing permissions issue. Check your event logs for details.
Comment: net use work, but glassfish still don't see the printer. this port only work in the current user? i need that the created port works for all user, like a locally installed printer. thx
Comment: Current user yes unfortunately. If this isn't working you'd need to investigate why the denied access is occurring.
Comment: the denied access is occurring because the admin user is disabled on the pc with windows 7 and simple file sharing is enabled. i set the admin account to enabled and set a password for it and everything is working now - thx


Como obter o endereço IP a partir da saída XML do nmap com um "vendor" específico utilizando ElementTree? no Python

Question: Utilizando a saída XML do nmap para as máquinas virtuais alcançáveis, rodando na mesma máquina hóspede - obtida com nmap -oX output.xml -sP 192.168.2.*, gostaria de obter o endereço IP de cada máquina cujo atributo "vendor" seja QEMU Virtual NIC. Escolhi usar a API XML ElementTree para fazê-lo, mas estou tendo dificuldades para isolar os elementos host com os elementos address especificados.
Segue um trecho da saída XML a ser utilizada:
<host><status state="up" reason="arp-response"/>
<address addr="192.168.2.93" addrtype="ipv4"/>
<address addr="52:54:00:E2:17:31" addrtype="mac" vendor="QEMU Virtual NIC"/>
<hostnames>
</hostnames>
<times srtt="1023" rttvar="5000" to="100000"/>
</host>
<host><status state="up" reason="arp-response"/>
<address addr="192.168.2.96" addrtype="ipv4"/>
<address addr="52:54:00:45:86:8A" addrtype="mac" vendor="QEMU Virtual NIC"/>
<hostnames>
</hostnames>
<times srtt="155" rttvar="5000" to="100000"/>
</host>
<host><status state="up" reason="arp-response"/>
<address addr="192.168.2.103" addrtype="ipv4"/>
<address addr="52:54:00:61:7A:E5" addrtype="mac" vendor="QEMU Virtual NIC"/>
<hostnames>
</hostnames>
<times srtt="391" rttvar="5000" to="100000"/>
</host>

Utilizando o comando findall e a sintaxe XPath abaixo, foi possível encontrar os elementos que possuem o atributo "vendor" desejado:
import xml.etree.ElementTree as ET
tree = ET.parse('output.xml')
tree.findall("./host/address/[@vendor='QEMU Virtual NIC']")

Porém, o que realmente quero, são os elementos host que contêm os elementos address encontrados acima, de forma que eu possa encontrar os outros sub-elementos de tipo "ipv4" para o mesmo host e assim, conseguir seu endereço IP. Alguém pode me ajudar a conseguir isto usando XPath e ElementTree?
Answer: Não há um meio direto de se encontrar ancestrais através do ElementTree, mas essa pergunta no SOEN mostra meios de se contornar isso, por exemplo:
parent_map = {c:p for p in tree.iter() for c in p}

ou (para versões de Python que não suportam dict comprehension):
parent_map = dict((c, p) for p in tree.getiterator() for c in p)

A partir daí você consegue achar os hosts a partir dos addresses retornados:
[parent_map[x] for x in tree.findall("./host/address/[@vendor='QEMU VirtualNIC']")]

Se necessário, você pode colocar os resultados num set (caso o mesmo host possa possuir mais de um endereço que se encaixe no filtro).
Comment: Obrigado pela resposta @mgibsonbr, mas na pergunta semelhante que fiz no site em inglês me responderam pouco tempo atrás com uma forma em que se pode andar "para cima" na hierarquia utilizando "..", veja: http://stackoverflow.com/a/22312105/1007502
Comment: @Claudio Hm, ok. Não sabia ao certo o quanto de XPath o ElementTree dava suporte, mas se ele permite `..` então é tranquilo.
Comment: Sim... é meu primeiro contato com isso no Python então nem sonhava que era possível também, mas acabei achando mais simples que o parent_map ai, é um pouco "criptico" não? hehe..
Answer: Uma forma mais simples de obter o resultado desejado seria a seguinte expressão, a qual resultou desta outra outra resposta no site em inglês. Reproduzo-a aqui no site em português, pois pode ser útil para alguém que não domine o inglês:
[i.get('addr') for i in tree.findall(
...     './host/address[@vendor="QEMU Virtual NIC"]/../address[@addrtype="ipv4"]')]


Is there a way to export ALL translations into a single .PO file?

Question: To translate my website, I need to export translations one by one per group type.
This gets to be confusing as some fields share core terms ect...
Is there a way to do a consolidated ONE .po file for all translations?
Answer: Each entry in .po file has only two strings;
<code>msgid untranslated-string
msgstr translated-string
</code>
Thus, by it's very nature it can only keep two languages: original and one translation. So no, there is no way to do it because format does not support that. For details, see documentation.


How to theme table row to link particular column data?

Question: I have created a list of table records in admin section using the following code.
class userDownloadedFiles extends ControllerBase{ public function userList() {
$header = array(

  array('data' => $this->t('Username'), 'field' => 'name', 'sort' => 'asc'),
  array('data' => $this->t('Email'), 'field' => 'mail', 'sort' => 'asc'),
);

$db = \Drupal::database();
$query = $db->select('users','u');
$query->innerJoin('users_field_data','ufd','u.uid=ufd.uid');
$query->fields('ufd', array('name','mail'));
$table_sort = $query->extend('Drupal\Core\Database\Query\TableSortExtender')
                    ->orderByHeader($header);
// Limit the rows to 20 for each page.
$pager = $table_sort->extend('Drupal\Core\Database\Query\PagerSelectExtender')
                    ->limit(20);
$result = $pager->execute();

// Populate the rows.
$rows = array();
foreach($result as $row) {
  //Get URL to user profile
  $profile_url = \Drupal::service('path.alias_manager')->getAliasByPath('/user/'.$row->uid);

  $rows[] = array('data' => array(
    'name' => "$row->name",
    'mail' => $row->mail,
  ));
}

// The table description.
$build = array(
  '#markup' => t('List of users who have downloaded model drawing or requested an account for downloading one.')
);

// Generate the table.
$build['user_info_table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#empty' =>t('There are no records yet.'),
  '#rows' => $rows,
);

// Finally add the pager.
$build['pager'] = array(
  '#type' => 'pager'
);
return $build;  }}

But the a tag used in username column is displayed as it is not appearing as link. This is how it appearing
Please guide me how to make it likable and how would I do it for other columns too.
Answer: You can try using the render element syntax for a Link element, like this:
$rows[] = array(
  'name' => array(
    '#title' => $row->name,
    '#type' => 'link',
    '#url' => $profile_url
  ),
  'mail' => array(
    '#title' => $row->mail,
    '#type' => 'link',
    '#url' => 'mailto:' .  $row->mail,
  ),
);

That way you can stick to a more consistent coding style, i.e. render arrays for presentation.
Answer: You need to create your link using FormattableMarkup:
use Drupal\Component\Render\FormattableMarkup;

$rows[] = array('data' => array(
  'name' => new FormattableMarkup('@name', [':link' => $profile_url, '@name' => $row->name]),
  'mail' => $row->mail,
));

Comment: Any possible way to make the whole row clickable? Like we can wrap name and mail in the same hyperlink.


Anagram char arrays

Question: So i have this algorithm in my c++ book
int anagrams(char *x, char *y) {
  char *p;
  if (!*x && !*y) return 1;
  p = strchr(y, *x);
  if (!p) return 0;
  *p = NULL;
  strcat(y, p + 1);
  return anagrams(x + 1, y)
}

It takes x first element, verifies if y has it, and if y has it, it is deleted. I don't really understand.
So, strchr returns a pointer to where x appears in y. And after that, i don't really understand.By the way
char a[] = "children" ;
char *p = strchr(a, 'i') ;
*p = NULL";

Why here everything after 'h' dissapears? P points to 'i', so shouldn t just 'i' dissapear?
Thanks! (i m still a beginner)
Comment: Are you sure that this a C++ book? The code rather looks like pure C. (It doesn't mean that it cannot be compiled in C++ as well but idiomatic C++ code should be taught in a different way.) FYI: [Kate Gregory "Stop teaching C"](https://www.youtube.com/watch?v=YnWhqhNdYyk) ;-)
Comment: Sure, my bad, my book is c/c++
Comment: For your first exposed snippet, please, provide an example how it is called. Even better would be to make a [mcve].
Answer: Concerning Why here everything after 'h' dissapears?:
char a[] = "children" ;
char *p = strchr(a, 'i') ;
*p = NULL";

There is a typo: It should probably be *p = NULL; (The double quote " is wrong.)

p is of type char*. Applying the de-reference operator * results in the pointee type. Hence, the expression *p is of type char. (Please, don't confuse this with the declaration char *p which declares a variable p of type char*.) NULL is intended to denote a null pointer. (In C, it might be defined as #define NULL (void*)0. In C++, nullptr should be favored over NULL.) Assigning a null pointer to a char is … confusing but the C compiler (as well as the C++ compiler) probably implicitly converts it back to a plain 0.
I compiled this with gcc -std=c11 as well as with g++ -std=c++17. In both cases, the compiler makes a warning but provides an executable binary:

C: Live Demo on coliru
Output:
warning: assignment to 'char' from 'void *' makes integer from pointer without a cast [-Wint-conversion]
  *p = NULL;

C++: Live Demo on coliru
Output:
warning: converting to non-pointer type 'char' from NULL [-Wconversion-null]
  *p = NULL;

So, it should be *p = 0; or even more clearly *p = '\0'; which is semantically identical but exposes the intention more clearly.

Considering this, a fixed version would be:
char a[] = "children" ;
char *p = strchr(a, 'i') ;
*p = '\0';

It overrides the element with i with a \0 which is the string terminator in C strings.
char a[] was before:
{ 'c', 'h', 'i', 'l', 'd', 'r', 'e', 'n', '\0' }

and becomes after this assignment
{ 'c', 'h', '\0', 'l', 'd', 'r', 'e', 'n', '\0' }

So, it still has the same length but using it with a C string function (like e.g. printf("%s", a);) will consider the first found string terminator.
Hence, it will print ch only.
Demo for illustration:
#include <cstring>
#include <cstdio>
#include <iomanip>
#include <iostream>

int main()
{
  char a[] = "children" ;
  char *p = strchr(a, 'i') ;
  *p = '\0';
  // printing a c string
  printf("a[]: '%s'\n", a);
  // print a[] element wise
  std::cout << "a[]: {";
  const char *sep = " ";
  for (char c : a) {
    std::cout << sep << '\'';
    if (c >= ' ' && c < '\x7f') std::cout << c;
    else std::cout << '\\' << std::oct << (unsigned)(unsigned char)c << std::dec;
    std::cout << '\'';
    sep = ", ";
  }
  std::cout << " }\n";
}

Output:
a[]: 'ch'
a[]: { 'c', 'h', '\0', 'l', 'd', 'r', 'e', 'n', '\0' }

Live Demo on coliru

A note about OPs C/C++ book:
It is a fact that the language C++ evolved out of the already existing language C. C and C++ are still related to each other. E.g. parts of the C standard library are adopted in the C++ standard library.
Nevertheless, these are two independent languages with their respective own standards.

There are C statements which work in C++ as well.
There are things in C which work in C++ a bit different.
There are things in C which doesn't work in C++ and vice versa.

Examples for the last:

auto is a valid storage class in C. In C++, this meaning has been invalidated since C++11, and the keyword got a new semantic: placeholder type specifier
Variable Length Arrays are an optional feature of the C99 standard (and newer) but not of any C++ standard. Some compilers (e.g. g++) support it as proprietary extension in C++.
Type Punning with union is legalized (to some degree) by the C standard but prohibited by the C++ standard.
Of course, C++ introduced a variety of new keywords (with new semantics) like e.g. class and template which are not available in C and would be interpreted as plain identifiers.

An (admittedly a bit contrived) example to show that the same source code may result in different semantics in C vs. C++:
  auto a = 'a';
  printf("sizeof a: %d\n", (int)sizeof a);

In C11:
#include <string.h>
#include <stdio.h>

int main()
{
  auto a = 'a';
  printf("sizeof a: %d\n", (int)sizeof a);
}

Output:
sizeof a: 4

Live Demo on coliru
auto is storage class. A type is missing in auto a. The C compiler defaults it to int.
In C++11:
#include <cstring>
#include <cstdio>

using std::printf; // pull printf() into global scope

int main()
{
  auto a = 'a';
  printf("sizeof a: %d\n", (int)sizeof a);
}

Output:
sizeof a: 1

Live Demo on coliru
auto determines the type of a from its initialization. In C++, character constants are of type char (in opposition to C, where they have type int).

Anagram char arrays


How is $\lim_{x\to 0}[(1+5x)^{\frac{1}{5x}}]^{10}=e^{10}$?

Question: Problem:
I was doing trying to find the value of $$\lim_{x\to 0}(1+5x)^{\frac{3x+2}{x}}$$
and I at some point reached these steps in my book:
$$\lim_{x\to 0}(1+5x)^3.\lim_{x\to 0}[(1+5x)^{\frac{1}{5x}}]^{10}$$
$$(1+5\times0)^3.e^{10}$$
Question:

How does $\lim_{x\to 0}[(1+5x)^{\frac{1}{5x}}]^{10}=e^{10}$?
Answer: It is based on the definition of $e$:
\begin{align*}
e = \exp(1) = \lim_{x\to 0}(1 + x)^{1/x}
\end{align*}
So you can obtain the desired result by means of the substitution $x = 5y$.
Comment: Another equivalent definition is

$$e = \lim_{x\to\infty}\left(1 + \frac{1}{x}\right)^{x}$$
Comment: Is this true only when $\lim_{x\to 0}$?


$G$-equivariant map between Lie group representations

Question: Say $f: A \rightarrow B$ is a $G$-equivariant map between finite dimensional $G$-representations, for some semi-simple Lie group $G$. If I know:

$B$ decomposes into irreducibles as $B = B_1 \oplus ... \oplus B_k$
$f(a) \in B_i$ for some $a \in A$, $f(a) \neq 0$

Must the decomposition of $A$ into irreducible $G$-reps contain a copy of $B_i$? Does the answer change depending on whether $f(a)$ is a highest weight vector for $B_i$?
Comment: Minor correction: $0 \neq f(a)\in B_i.$
Answer: It depends on the context, but the answer to your first question should be yes if you are thinking of complex semi-simple Lie groups. Indeed, this should be true in any setting where your representations decompose into irreducibles for purely formal reasons.
First a reduction: Schur's lemma holds in the context of Lie group representations, so every map to an irreducible $G$-rep is either zero or surjective. If $V = G\cdot a \subseteq A$ is the cyclic subrep generated by $a$, then of course $f$ defines a $G$-morphism $V \to B_i$ which is surjective (as long as $f(a) \neq 0$). From this we can see that $B_i$ is a quotient of $V$.
So your first question is equivalent to the following fundamental question: does every irrep which arises as a quotient of a $G$-representation $V$ actually arise as a subrepresentation? Equivalently, does every sub-representation have a complement? This is equivalent to asking for complete reducibility, as shown here.
For (edit: forgot to emphasize semisimple) Lie algebras, the answer is affirmative (this the fundamental result of Weyl) and the same basic result holds for compact Lie groups (one can construct complements by some kind of Reynolds averaging argument, or equivalently, one can normalize the representation to be a unitary representation and then construct complements via orthogonality). Since every semisimple complex Lie group has a compact real form, the result holds in that context too.
Comment: The last paragraph seems a little off to me. Weyl's theorem holds for **semisimple** Lie algebras specifically and if it holds for a Lie algebra it works for any of its Lie groups as well so we have no need to appeal to compact real forms (except as a way to prove Weyl's theorem itself)
Comment: How does the argument go for passing from Lie algebras to an arbitrary (maybe connected?) Lie groups for it? For the simply connected G you have an equivalence, and then the ones which descend to some other G' are the subcategory which are invariant for the action of the fundamental group? How do you know every splitting of a representation which descends also descends?
Comment: My instinct is to try to think of things in terms of twisting to the compact real form of the group, which is why I emphasized it in the last sentence.
Comment: Simply using the fact that invariant subspaces for the Lie algebra representation are invariant subspaces for the Lie group representation (if the latter exists). See [here](https://math.stackexchange.com/questions/1604850/a-subspace-is-invariant-by-the-lie-group-if-it-is-invariant-by-the-lie-algebra), for example. Note the representation descends to representations on these subspaces simply by restriction.


A differentiable multivariable function

Question: I know the chain rule for the multivariable functions works when the partial derivatives are continous but if the function is just differentiable does the chain rule work ? I mean if $z = f(x,y)$ is differentiable function and $x = g(t) , y = h(t)$ are also differentiable functions can we write :
$\frac{dz}{dt} = \frac{\partial f}{\partial x}\times \frac{dx}{dt} + \frac{\partial f}{\partial y}\times \frac{dy}{dt}$
Comment: This is related and will help https://math.stackexchange.com/questions/799913/why-cant-i-use-the-chain-rule-on-fx-y-fracxy2x2-y2?rq=1.
Answer: The derivative, if it exists, of a function $f:\mathbb R^n\to \mathbb R^m$ at a point $x$ is a  $\textit{linear transformation}\ f'(x):\mathbb R^n\to \mathbb R^m$ that satisifies
$\tag 1 f(x+h)-f(x)=f'(x)h+r(h)\ \text{where}\  r=o(|h|)$.
Now, suppose $\phi:\mathbb R\to \mathbb R^2:t\mapsto (g(t),h(t))$ and $f:\mathbb R^2\to \mathbb R$. If $\phi $ is differentiable at $t=t_0$ and $f$ is differentiable at $(g(t_0),h(t_0))$, then we can apply the chain rule to assert that $f\circ \phi:\mathbb R \to \mathbb R$ is differentiable at $t=t_0$ and
$(f\circ \phi)'(t_0):\mathbb R\to \mathbb R$ exists and is equal to $f'(\phi(t_0))\circ \phi'(t_0).$
So far, nothing to do with partials.
Of course, it turns out that if the derivative exists then it matches your formula.
And if the relevant partial derivatives are continuous, the derivative exists and the formula is also satisfied.
On the other hand, if one or more of the partials is $not$ continuous at a given point, the derivative may or may not exist there, and you need to check directly to see if $(1)$  is satisfied.

A differentiable multivariable function


Copiar QVector local para QVector de Classe

Question: É o seguinte estou fazendo na unha um gráfico LineChart para um trabalho de aula, estou com enormes dificuldades com a linguagem C++, em certa parte do código passo por parametro um QVector<QPoint>, e quero pintar na função DrawLine esses points, mas para isso pensei que copiar o QVector<QPoint> que mando para o método, para um QVector<QPoint> global da classe mas não consigo copiar, alguém me da uma ajuda ?
#pragma once
#include <QFrame>
#include <QWidget>
#include <QHBoxLayout>
#include <QPaintEvent>
#include <QPainter>
#include <QMainWindow>
#include <QLabel>
#include <QVector>

class LineChart : public QFrame
{
    Q_OBJECT
    public:
        LineChart();
        void addSeries(QVector<QPoint> series, QColor color);
        void setAxisX(QVector<QString> values);
        void setAxisY(QVector<QString> values);
        void setLabelX(QString name);
        void setLabelY(QString name);
        void setTitle(QString title);
        void paintEvent(QPaintEvent* paint);

        // keyPressEvent(QKeyEvent *event);
    private:
        //QFrame *frame;
        QGridLayout *layout;
        QLabel *label;
        int x0,x1,y0,y1;
        QPoint *point;
        QPoint *point2;
        QVector<QPoint> *vector;
        //QPushButton *button;
};

void LineChart::addSeries(QVector<QPoint> series, QColor color){
    vector = new QVector<QPoint>;
    vector = series;
}

void LineChart::paintEvent(QPaintEvent *event){
    QFrame::paintEvent(event);
    QPainter painter(this);

    qDebug() << point->rx() ;
    qDebug() << point->ry();
    qDebug() << point2->rx() ;
    qDebug() << point2->ry();

    //painter.drawLine(point->rx(),point2->ry(),point->rx(),point2->ry());
    for(int i = 0 ; i< vector->length() ; i++){

    }

    qDebug() << "paintEventinvocado!";
}

Comment: Você pode meramente atribuir um QVector ao outro, pelo `operator=`. Tentou isso?
Answer: Primeiramente, este código de exemplo mostra alguns problemas em conceitos básicos da linguagem C++ (Você aparenta ter um conhecimento da linguagem Java e esta utilizando C++ como se fosse ela). Seria interessante você estudar esse conceitos fazendo programas mais básicos antes de criar uma aplicação complexa com interface gráfica.
Alguns desses problemas são:

Uso excessivo de ponteiros para casos onde não são necessários. (QVector<QPoint> * vector declarado como variável membro de LineChart, por exemplo)
Não definição de construtor de cópia, operador de atribuição e destrutor quando sua classe possui ponteiros. Não ter isso faz com que memória seja vazada em alguns momentos ( C++ não faz coleta de lixo, você tem que chamar delete quando terminar de usar espaços de memória alocados dinamicamente com o new) e que objetos internos da classe sejam compartilhados entre cópias desta.

Tendo dito isso, o problema no seu código que faz com que você não consiga copiar o vetor esta no seguinte trecho:
vector = new QVector<QPoint>;
vector = series;

Aqui vector é um QVector<QPoint> * e logo na linha seguinte você tenta atribuir uma variável do tipo QVector<QPoint> ao ponteiro, o que não é valido. Para efetuar a cópia é necessário derreferenciar o ponteiro como no código à seguir:
*vector = series; // *vector é um QVector<QPoint>

Uma solução ainda mais idiomática utilizando os recurso do C++ é usar o construtor de cópia da classe QVector, sendo assim o código inteiro da função se tornaria:
vector = new QVector<QPoint>(series);

Criando um novo objeto que já é uma cópia do original.
Comment: Nota: `QVector` implementa **copy-on-write**. Então criar cópias desse objeto é leve e não acarreta cópias de todos os elementos.
Comment: @GuilhermeBernal Editei minha resposta para retirar a ressalva sobre o custo da cópia. Obrigado pela informação! :)


Discrete Math - Question on Sets

Question: Been trying for a while to figure out how to solve this question.
Let A = {n ∈ N | n ≥ 1 and n = 4j − 3 for some j ∈ N} and B = {n ∈ N | n ≥ 0 and n = 2k + 1 for some k ∈ N}.
Prove that A ⊆ B. Here, N = {0, 1, 2, 3, . . . }.
Answer: Take an arbitrary element $x \in A$. Then, by the definition of set $A$, we can
$$x = 4j - 3$$
for some $j \in \mathbb{N}$. Moreover, since $4j - 3 \geq 1$ and $x \equiv 1 \pmod{2}$, we know that $x$ is an odd positive integer. This is precisely the requirement an element needs to satisfy in order to be in set $B$. Thus, $x$ is also in set $B$.
Since we have shown that an arbitrary element of $A$ also lies in $B$, we conclude that $A \subseteq B$. So we're done.

Discrete Math - Question on Sets


Convergence and Limit of the infinite series

Question: How can I find the limit of the series
$$
\sum_{t=1}^{\infty} \frac{\ln(c+2^{t-1})}{2^t} \;\;\text{where}\; c > 0
$$
Since the terms are positive, and I have an intuition that $a_{n-1} \geq a_n$, the series converge to a limit point.
I tried to analytically show that the terms are decreasing, as below
$$
\frac{\ln(c+2^{n-1})}{2^n} \leq \frac{\ln(2^{n-1}+2^{n-1})}{2^n} \leq \frac{\ln 2}{2^{n-1}}
$$
But I am not sure about the selection of the upper bound for the constant $c$.  How can I show that the series converge and find the limit of it ?
Comment: "I used an to denote the nth term in the partial sum of the series" Then **say so in the question**.
Comment: Are you after a proof of the convergence of the series or after the exact value of its sum? (Unrelated: What do you call $a_n$?)
Comment: Seems pretty hard to find the sum. Differentiating w.r.t. $a$ does not yield promising result by WolframAlpha…
Comment: @Did  I am interested in the exact value of the limit of the series.  I did not understand the part "What do you call $a_n$". I used $a_n$ to denote the $n^{th}$ term in the partial sum of the series.
Comment: If $\;a_n\;$ for you is the series' general addend, as it is usually denoted, then it is false that if $\;\{a_n\}\;$ is positive and monotone descending the series $\;\sum a_n\;$ converges...
Comment: @DonAntonio, yes true. It guarantees that the alternating sign series converges right ?.  As Fred shown below, we can make use of the fact that the series converges as per comparison test.
Answer: There is $N \in \mathbb N$ such that $a \le 2^n$ for all $n>N$. Thus
$0 \le a_n:=\frac{\ln(a+2^{n-1})}{2^n} \leq \frac{\ln(2^{n-1}+2^{n-1})}{2^n} =n\frac{\ln 2}{2^{n}}=:b_n$ for all $n>N$.
The ratio test shows that $ \sum b_n$ is convergent, hence $\sum a_n$ is convergent.
Answer: Hint. As regards convergence note that
$$\frac{a_{n+1}}{a_n}=\frac{\ln(c+2^{n})}{2^{n+1}}\cdot \frac{2^n}{\ln(c+2^{n-1})}=
\frac{1}{2}\cdot \frac{\ln(c+2^{n})}{\ln(c+2^{n-1})}\sim \frac{1}{2}\cdot \frac{n\ln(2)}{(n-1)\ln(2)}\to \frac{1}{2}$$
where $a_n=\dfrac{\ln(c+2^{n-1})}{2^n}>0$. What may we conclude?
Comment: this indicates that the limit is less than $\frac{1}{2}$, right ?.  Is it tight or can we find the exact value ?
Comment: @Shew The limit of the ratio $\frac{a_{n+1}}{a_n}$ is eaxactly $1/2$.


Solve $\frac3x - \frac4y = 1$ and $\frac7x + \frac2y = \frac{11}{12}$

Question: How can we solve the following simultaneous equations:
$$\frac3x - \frac4y = 1$$
$$\frac7x + \frac2y = \frac{11}{12}$$
Comment: We can proceed directly. Or else let $s=1/x$ and $t=1/y$. Then we are solving the system of linear equations $3s-4t=1$, $7s+2t=\frac{11}{12}$. You can probably handle a system of $2$ linear equations in $2$ unknowns.
Answer: Take $\frac{1}{x}$ as $w$ and $\frac{1}{y}$ as $v$ . Now you will get two linear equations . Solve the two equations for $w$ and $v$ and the subsequently put $w=1/x$ and $v=1/y$ .
Answer: $\frac{3}{x}-\frac{4}{y}=1$ ---(1)
$\frac{7}{x}+\frac{2}{y}=\frac{11}{12}$ ---(2)
2(2): $\frac{14}{x}+\frac{4}{y}=\frac{11}{6}$ ---(3)
(1)+(3): $\frac{17}{x}=\frac{17}{6}$
Hence $x=6$, and $y=-8$.
Answer: Hint:
Solve one for one of the variables, substitute back into the second and solve for other variable.
From the first equation, we have:
$$x = \dfrac{3y}{y+4}$$
Answer: One way to solve two equations like this is to add a multiple of one to the other.  For example, Take $2$ times the second equation and add it to the first.  Explicitly,
$$(\frac{3}{x}-\frac{4}{y})+2(\frac{7}{x}+\frac{2}{y})=1+2\left(\frac{11}{12}\right)  $$
This gives us that,
$$\frac{17}{x}=\frac{17}{6} $$
Multiply both sides, by $x$ and then 6 to get,
$$(6)(17)=17x $$
so,
$$x=6 $$
Once we have what $x$ is equal to we can plug that back into one of our equations.  Let's do that with the first equation.
$$ \frac{1}{2}-\frac{4}{y}=1$$
Solving this gets us that $y=-8$.  You can check your answer by making sure this $x,y$ pair satisfy both equations at once.  Hope that helps!


Capistrano -- the task `staging:symlink' does not exist

Question: I'm attempting to deploy to a server via Capistrano and I keep getting the error the task `staging:symlink' does not exist.
I've run cap:deploy setup and cap deploy successfully getting the releases and shared directories created but the above error always shows at the end and I think it's stopping my code from getting moved to the root of the directory where it belongs.
I'm new at using Capistrano and I've Googled the issue but I cannot find anything that helps. I can include my code and everything I just don't know what to show to help... let me know!
Thanks for any help you can provide!
Answer: The built-in symlink task for capistrano 2.x is cap deploy:symlink.
staging:symlink is not a valid task, unless you've defined it yourself. If you're not defining this, you are accidentally calling it somewhere in your config files (deploy.rb or one of your staging config files, if you're using multistage).
Additionally, deploy:symlink should be called automatically as part of the deploy task. You don't need to call it manually.


equinumerous between a finite and infinite set

Question: I need to write a proof that, given A is a finite set and B is an infinite set, show that A is equinumerous to a subset of B. I understand to show this I need to show a bijection.
I can get the injectivity easily. What I don't understand is how A is how to show A surjective to a subset of B. By the definition of surjection that for each y in B there must exists an x in A such that f(x) = y. Can I just state that is MUST be a subset or else it wouldn't be surjective and therefore A would fail to be equinumerious to a subset of B?
Can I even apply those definitions because they involve a function when the question doesn't mention functions at all?
Comment: Your logic can't include "or else [...] A would fail to be equinumerous to a subset of B", because that's exactly what you're trying to prove, and it sounds like you have in mind a contradiction along the lines of "the thing I'm supposed to prove wouldn't be true, which is a contradiction"
Comment: It is, but the way you seem to be contemplating its structure seems, to me, to be that the contradiction is that "I know this thing is true. If it weren't true, that would contradict the fact that it is."
Comment: I thought that was the entire point of using a contradiction.
Comment: When you write, "I can get the injectivity easily", do you mean you know how to construct an injective mapping $f:A \to B$?
Answer: You will need to define a function from $A$ to $B$ and then show it is a bijection.
I don't know how technical of a proof they are looking for, but it seems trivial to just say that if $A$ is finite (say, $A = \{ a_1, a_2, ..., a_n \}$ for some number $n$), and $B$ is infinite, then obviously there will be a subset $B'$ of $B$ of size $n$, and so you can say $B' = \{ b_1, b_2, ..., b_n \}$. And then you can define $f(a_i) = b_i$ for all $1 \le i \le n$, and show that this $f$ is a bijection.


Why do you need to show A(1) before proving A(n) by induction?

Question: My instructor stated that in order to have a valid proof by mathematical induction, you first have to show A(1) holds, and then assume A(n) to deduce A(n+2). Why is the first step necessary if we are going to assume A(n) though?
I get that showing A(1) is true suggests that A(n) might be, but that could very easily not be the case. Perhaps A(3) does not hold. So why logical benefit do we gain by proving A(1) before completing a more general proof by induction?
Comment: You have to knock over the first domino to make the rest of them fall.
Comment: Can you state the principle of mathematical induction you are using?
Comment: In an induction process, we always need to start from an outset point which could be $1$ or anything else, but for sure without proving for a proper outset, your proof is not complete.
Comment: Let's prove by induction that all natural numbers are bigger than $1000$. In fact, if $n\ge 1000$, then $n+1\ge 1001\ge1000$. QED.
Answer: A proof by induction has two parts, and you have to prove each of them:

$(i)\quad$ $A(n)$ implies $A(n+1)$, for all natural numbers $n$;
$(ii)\quad$ $A(1)$ is true.

Together, these two facts imply that $A(n)$ is true for all natural numbers $n$. For example, to see $A(3)$ is true (given these two facts), we argue as follows:

We know $A(1)$ is true by $(ii)$.
Since $A(1)$ is true, $A(1+1)$ is also true by $(i)$.
Since $A(1+1)$ is true, $A(1+1+1)$ is also true by $(i)$.
So $A(3)$ is true!

However, we need both pieces for induction to work. For example, let $A(n)$ be the property "$n=n-3$." Then:

Clearly (for any $n$) if $A(n)$ is true, then $A(n+1)$ is also true: since $A(n)$ means $n=n-3$, so $n+1=n-3+1$, so $n+1=(n+1)-3$ - but this is just $A(n+1)$!
However, $A(n)$ is in fact false for every $n$.
Comment: @IgnorantCuriosity How could that happen? If "$A(1)$" is true, and "$A(1)$ implies $A(2)$" is true (this is a special case of "$A(n)$ implies $A(n+1)$", then *of course* "$A(2)$" is true; that's what "implies" means. (See https://en.wikipedia.org/wiki/What_the_Tortoise_Said_to_Achilles for an amusing exchange around this.) Now of course, what can happen in practice is that I *think* that I've proved "$A(1)$", and I *think* that I've proved "$A(n)\rightarrow A(n+1)$", and I *also think* that I've proved "Not $A(2)$." In this case, I know that *at least one of my proofs is wrong*.
Comment: Thanks for the response. What if you showed A(1) held, and showed that assuming A(n) allows you to deduce A(n+1), but it turned out A(2) was false? Or is there something preventing a case like this from arising?
Comment: (Technically, there's also the possibility that *the axioms I'm using are inconsistent*. But I think that's just going to muddy things at first; for now, assume that the axioms we're using are in fact true statements about the world of mathematics. This is an assumption that you can explore in more detail - and maybe even reject! - down the road; but for now I think getting a good grasp of induction comes first.)
Comment: I don't have an example of a statement that shows this happening, but my question comes from seeing your demonstration that a false A(n) can deduce A(n+1), and the false theorem that n^2 + n + 41 generates primes. In this case, it holds for the first 39 numbers, but not the 40th. I suppose the fact that we have no way of proving whether something generates primes comes into play here, but initially the scenario of having a true A(1), and deducing A(n+1) from a false A(n) seemed plausible.
Comment: @IgnorantCuriosity Ah, I think I see the issue: what we prove in the *inductive step* of a proof by induction is that $A(n)$ implies $A(n+1)$ **for every $n$**. And we don't just give a plausibility argument - we have to *prove* it. So in a case like you mention, what's going on is: we see $A(1)$; we see that $A(n)\rightarrow A(n+1)$ is true for a whole bunch of specific $n$s; but *that's not a proof* that $A(n)\rightarrow A(n+1)$ is true *for every $n$!* And so that's the difference. "Proof by induction" is not just generalizing from a bunch of cases.
Comment: (By the way, these are great questions you're asking, and thinking critically about proofs/proof methods is **definitely** something you should keep doing! I hope I don't come off as dismissive.)
Answer: What you're really showing in the step case is that if $A(n)$ is true, then $A(n+1)$ is true.  So you're showing $A(n) \implies A(n+1)$.  With just this, you don't know if your statement is true for any actual values of $n$.  When you prove it for a value, for example $A(1)$, that together with $A(n) \implies A(n+1)$ gives you $A(1) \implies A(2) \implies A(3) \implies ...$ so you can just follow that chain of implications and your statement is true for any $n \geq 1$
For example: The induction step of "All integers are of the form $\frac{2k+1}{2}$ for some integer $k$" is true since $\frac{2k+1}{2} + 1 = \frac{2(k+1)+1}{2}$. You can't verify it for any value of $n$ though, since no integers are actually of that form.
Comment: After posting I see that my answer is more or less the same as Noah's, but I'll leave it up in case it's useful to someone.
Answer: The reason proof by induction works is because of the well-ordering principle (WOP) of the natural numbers. The well-ordering principle says any nonempty subset of the natural numbers has a least element. It turns out that WOP is logically equvalent to the principle of mathematical induction (PMI). This is fairly straightforward to prove as follows:
$WOP\leftarrow PMI$ Suppose $S$ has no minimal element. Then $ n = 1 \notin S$, because otherwise $n$ would be minimal. Similarly $n = 2 \notin S$, because then $2$ would be minimal, since $n = 1$ is not in $S$. Suppose none of $1, 2, \cdots, n$ is in $S$. Then $n+1 \notin S$, because otherwise it would be minimal. Then by induction $S%$ is empty, a contradiction.
$WOP\leftarrow PMI$ Suppose $P(1)$ is true, and $P(n+1)$ is true whenever $P(n)$ is true. If $P(k)$ is not true for all integers, then let $S$ be the non-empty set of $k$ for which $P(k)$ is not true. By well-ordering $S$ has a least element, which cannot be $k = 1$. But then $P(k-1)$ is true, and so $P(k)$ is true, a contradiction.
So clearly WOP is true iff PMI is true. A lot of teachers don't like going through this in basic rigorous mathematics courses, which to me is a big mistake. Students need to understand why induction works,it's a critical method of proof.
How's that?


How to "hear" polyrhythms?

Question: I've ben playing drums for about 22 years now and am quite capable around the kit. I've been working on some more complex polyrhythmic stuff, like 9/8 grooves with 7/8 or 5/8 ostinatos on the hats/ride and, while I can do them, I find that my ear is drawn to the ostinato meter, and the groove sounds very robotic; in fact, I struggle to play the groove without writing it out. Here's a simple example of a 9/8 groove with 5/8 ostinato:

When I play it, it feels (and therefore probably sounds) like a confusing 5/8 groove instead of a straightforward 9/8 groove with polyrhythmic cymbal work. My question is: how can I train my ear to hear the groove meter and let the ostinato be the autopilot portion? Obviously it takes practice, but if anyone has any pointers for "hearing" one rhythmic piece instead of the other, I'd appreciate the ideas.
Comment: This is polymeter (rather than polyrhythm).
Comment: @Aaron isn't it both?  Any drum kit pattern is polyrhythm unless all the instruments are struck at the same time.  I mean, you could write it as three independent parts, with for example the top line being alternate quarters and dotted quarters (or equivalent tied notes according to the meter) without changing the performance (other than making it more difficult -- or easier? -- for the performer to read).
Answer: It might be refreshing to study a genre built on polyrhythm/-meter. Have you done a deep dive into West African music? What if you incorporated pitched percussion—marimba, etc., or just a drum pad with pitched instruments—and then you have melodic interactions emerging.
Disclaimer, I'm no expert in West African music or much else. But I suspect the bottom line is that we're inclined to think of "the whole"—the additive rhythm that is the sum total of the interlocking parts, like how 4 against 3 yields "pass the goddamn butter"—but the real fun lies in holding multiple grooves in our head at the same time rather than just calculating their interference pattern. This becomes almost some sort of mindfulness exercise—if you can get both "plates spinning," try shifting your attention from one to the other and back again, without letting either stop. Rinse and repeat with more plates.
Answer: I find that hearing a polymeter is the same as feeling it, so I train the latter.
I practice patterns like the one in the question away from the instrument, just tapping my hands on my lap. A few approaches I find most effective.

Get both hands going, then practice counting one meter (e.g., counting 5), then the other (e.g., counting 9), out loud. The out loud part is the key, because it's easier to cheat or miss mistakes if one counts silently. Out loud is harder, because it requires extra brain space.
Get one hand going, then add the other. One direction is near always harder than the other, which will help focus your practice.
With both of the above, after it can be done easily, switch hands.
When it can be done both hands, with each hand responsible for each meter, do it with the feet, then one hand and one foot, then ... clicking my tongue, snapping my fingers, nodding my head in one meter and counting the other. Basically, constantly come up with new ways to confuse my body and work through the polymeter again.
If you really want to drive yourself nuts, set a metronome for a third pulse pattern.

For an approach to polyrhythm, see How to tackle this tricky rhythm -- nested triplets?
Comment: When you tap with your hands are you tapping just the '1' or are you tapping all five or all seven or whatever beats within the tuplet? If you are tapping all the beats, how do you distinguish '1 from all the others?
Comment: @BrianTHOMAS That's the role of the audible counting.
Comment: I'm sorry Aaron I don't understand what you mean. I want to though. Can you break it down into smaller steps?
Comment: @BrianTHOMAS One hand taps the 9/8 rhythm, then other taps the 5/8 rhythm. Then I count either to 9 or to 5 along with the two rhythms, so my counting is "in sync" with one hand but not the other in terms of where the 1 falls. But the hands themselves still have to maintain the proper accent patter for their respective meter/rhythm.
Comment: @BrianTHOMAS Another way to think of it is that I tap the OP example as written, and then I rewrite it in 5/8 (i.e., change the placement of the bar lines) and practice tapping/counting that as well.

How to "hear" polyrhythms?


Actionscript 3 call a javascript function

Question: is it possible to call javascript functions inside flash (as3)? How about not in the same domain? Can you provide an example snippet for samedomain and not same domain?
thanks!
Comment: There are about ten other questions on the same topic.  Try using google or the search field in the top right corner of this page...
Comment: You mean call javascript functions from flash? I think you should clarify the question, perhaps provide an example or scenario.
Answer: Using the ExternalInterface you can communicate with JavaScript from Flash, however only in the window where the Flash application is running.
It is as easy as doing:
ExternalInterface.call("jsFunctionName", argument, argument, ...);

To do the reverse (calling Flash from JavaScript) you do the following first:
ExternalInterface.addCallback("jsFunctionName", callbackFunction);

function callbackFunction(arg:String):void {
    trace(arg);
}

And then you can call jsFunctionName("foo") from JavaScript.
See the adobe docs for more info on that.
As for your cross domain, you can't as far as I know, but you may be able to proxy the call via your server.
Comment: can we also use to execute some random javascript passed as a string argument to the function ?
Comment: No as far as I know it just takes a global function name and calls that.