text:
Q: PHP sendmail, values not passing through to email I have a contact form on an html page that is using a php script on seperate php page to send text values entered into input boxes in an email
Everything is working except the text entered in the forms input boxes are not passing through, they are blank
Below is what I am doing:
HTML
    <form class="form-inline" action="mail_handler.php" method="post"
     enctype="multipart/form-data">

                      <input type="text" class="form-control color01 background13 border-color08" name="name" placeholder="Name" required>

                      <input type="email" class="form-control color01 background13 border-color08" name="email" placeholder="Email" required>

                      <input type="text" class="form-control color01 background13 border-color08" name="number" placeholder="Phone/Cellphone Number">

                      <input type="text" class="form-control color01 background13 border-color08" name="company" placeholder="Company name">

                      <textarea class="form-control color01 background13 border-color08" rows="3" placeholder="type your message here" name="message" required></textarea>

                  <button type="submit" value="submit" name="submit" class="btn more background07 color01 color01-hover01" >book</button>

              </form>

PHP
<?php
$name = $_POST['name'];
$number = $_POST['number'];
$email = $_POST['email'];
$company = $_POST['company'];
$message = $_POST['message'];

$from = 'From: info@recipient.com';
$to = 'myemail@gmail.com'; //email
$subject = 'website booking enquiry';
$message = "From: $name\n Number: $number\n E-Mail: $email\n Company:
$company\n Message: $message\n ";

$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html\r\n";
$headers = 'From: info@recipient.com' . "\r\n" .
'Reply-To: $email' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
header( "Location: index.html" );//if u wish to get redirected
?>

A: This is getting too long for comments, therefore I have submitted the following.
You have quite a few errors in your code.
You've missed a concatenate/dot for your last header and is "breaking the chain" as it were, and variables don't get parsed in single quotes
Also the first header should not have a leading dot.
$name = $_POST['name'];
$number = $_POST['number'];
$email = $_POST['email'];
$company = $_POST['company'];
$message = $_POST['message'];

$from = 'From: info@recipient.com';
$to = 'myemail@gmail.com'; //email
$subject = 'website booking enquiry';
$message = "From: $name\n Number: $number\n E-Mail: $email\n Company:
$company\n Message: $message\n ";

$headers  = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html\r\n";
$headers .= 'From: info@recipient.com' . "\r\n" .
"Reply-To: $email" . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
header( "Location: index.html" );//if u wish to get redirected
exit;

You should also check for empty fields, because anyone can submit with nothing filled and you will get empty results.
I.e.:
if(!empty($_POST['name']) || !empty($_POST['email'])) {

// Assign variables to the POST arrays and process mail

$name = $_POST['name'];
$number = $_POST['number'];
$email = $_POST['email'];
$company = $_POST['company'];
$message = $_POST['message'];

// ... rest of your code

}

Note: || means "OR". You can use that, or && which means "AND", or a mix of both.

Footnotes:
\n will not show the data on separate lines, should that be the goal, since you are using HTML headers.
You will need to use
 if that is what you want to do here.
Consult the manual on mail:

*

*http://php.net/manual/en/function.mail.php
A few other alternatives to PHP's mail(), are PHPMailer and Swiftmailer:

*

*https://github.com/PHPMailer/PHPMailer

*http://swiftmailer.org/

As stated in comments:

enctype="multipart/form-data" - remove that from your form element. – CBroe"

That can be safely removed since you're not dealing with files.
If this is a server issue, then you will need to find out what the problem is and is beyond the scope of the question.


text:
Q: Automatically update my Gsheet with an SQL data base I need to update a file automatically that already has data in it.
The document is filled with an SQL data base thanks to the code below
However, I want it to update itself everyday without deleting any data that are already in the document and only adding new ones (don't want any duplicates).
function readData(db, queryString) {
  //connect to the database
  var server = 'your-servername-OR-serverPublicIpAddress';
  var username = 'your-sql-username';
  var password = 'your-password';

  var dbUrl = 'jdbc:sqlserver://' + server + ':1433;databaseName=' + db;

  var conn = Jdbc.getConnection(dbUrl, username, password );

  //query the data
  var stmt = conn.createStatement();
  var exec_query = stmt.executeQuery(queryString);

  var metaData = exec_query.getMetaData();
  var numCols = metaData.getColumnCount();

  //save query data to an array
  var result=[]; //initiate a blank array

  //save the column header
  header = []; //initiate the header row
  for (var col = 0; col < numCols; col++) {
    header.push(metaData.getColumnName(col + 1)); //add the name of each column to the header row
  };
  result.push(header);//after the header row is formed, put it to the result array

  //save the data of each row
  while (exec_query.next()) {
    row_data = [];
    for (var col = 0; col < numCols; col++) {
      row_data.push(exec_query.getString(col + 1));//add data of each column to the row data
      //Logger.log(row_data);
    };
    result.push(row_data); // add row data to result
    //Logger.log(result);
  };
  exec_query.close();
  return result
};

function pushDataToGoogleSheet(data, SheetName) {

  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = SpreadsheetApp.setActiveSheet(spreadsheet.getSheetByName(SheetName));
  var lastRow = sheet.getLastRow();

  sheet.getRange(lastRow+1, 1, data.length, data[0].length).setValues(data);
  sheet.getDataRange().removeDuplicates();
};

function main() {
  db = 'YOUR_DATABASE_NAME'
  SQLquery = 'YOUR_SQL_QUERY'
  raw_statistics = readData(db, SQLquery); //get raw statistics
  pushDataToGoogleSheet(raw_statistics, 'YOUR_SHEET_NAME'); //push to google sheet
};

function main() {
  db = 'YOUR_DATABASE_NAME'
  SQLquery = 'YOUR_SQL_QUERY'
  raw_statistics = readData(db, SQLquery); //get raw statistics
  pushDataToGoogleSheet(raw_statistics, 'YOUR_SHEET_NAME'); //push to google sheet
};

However, in the pushDataToGoogleSheet it says that it can't define the length. So, I don't know if I put the right thing for data or not or if there is an issue in my code...
Do you have an idea ?
Thank you for your help !

redpajama_set_name: RedPajamaStackExchange


text:
Q: Setting the index after merging with pandas? Executing the following merge
import pandas as pd
s = pd.Series(range(5, 10), index=range(10, 15), name='score')
df = pd.DataFrame({'id': (11, 13), 'value': ('a', 'b')})
pd.merge(s, df, 'left', left_index=True, right_on='id')

results in this data frame:
     score  id value
NaN      5  10   NaN
0.0      6  11     a
NaN      7  12   NaN
1.0      8  13     b
NaN      9  14   NaN

Why does Pandas take the index from the right data frame as the index for the result, instead of the index from the left series, even though I specified both a left merge and left_index=True? The documentation says

left: use only keys from left frame

which I interpreted differently from the result I am actually getting. What I expected was the following data frame.
    score  id value
10      5  10   NaN
11      6  11     a
12      7  12   NaN
13      8  13     b
14      9  14   NaN

I am using Python 3.7.5 with Pandas 0.25.3.

A: You can do this with reset_index:
df = pd.merge(s,df, 'left', left_index=True, right_on='id').reset_index(drop=True).set_index('id').rename_axis(index=None)
df.insert(1, 'id', df.index)

    score  id value
10      5  10   NaN
11      6  11     a
12      7  12   NaN
13      8  13     b
14      9  14   NaN

A: Here's what happens:

*

*the output index is the intersection of the index/column merge keys [0, 1].

*missing keys are replaced with NaN

*NaNs result in the index type being upcasted to float
To set the index, just assign to it:
s2 = pd.merge(s, df, how='left', left_index=True, right_on='id')
s2.index = s.index

    score  id value
10      5  10   NaN
11      6  11     a
12      7  12   NaN
13      8  13     b
14      9  14   NaN

You can also merge on s (just because I dislike calling pd.merge directly):
(s.to_frame()
  .merge(df, how='left', left_index=True, right_on='id')
  .set_axis(s.index, axis=0, inplace=False))

    score  id value
10      5  10   NaN
11      6  11     a
12      7  12   NaN
13      8  13     b
14      9  14   NaN

A: Since I do not need the duplicated information in both the id column and the index, I went with a combination of the answers from cs95 and oppressionslayer, and did the following:
pd.merge(s, df, 'left', left_index=True, right_on='id').set_index('id')

Which results in this data frame:
    score value
id
10      5   NaN
11      6     a
12      7   NaN
13      8     b
14      9   NaN

Since this is different from what I initially asked for, I am leaving the answer from cs95 as the accepted answer, but I think this use case needs to be documented as well.


text:
Q: SSH tunnel error for root: sys_tun_open: failed to configure tunnel (mode 1): Operation not permitted I try to set up an ssh vpn (Debian OS server and client both).
I changed /etc/ssh/sshd_config (the server):
PermitTunnel yes
PermitRootLogin without-password

but when I try to connect (the client):
$ ssh -NTCf -vvvw  0:0 root@server-ip

...
debug1: Authentication succeeded (publickey).
Authenticated to <server-ip> ([<server-ip>]:22).
debug1: Requesting tun unit 0 in mode 1
debug1: sys_tun_open: failed to configure tunnel (mode 1): Operation not permitted
Tunnel device open failed.
Could not request tunnel forwarding.
...

What can be wrong? Please help!
UPDATE
I tried to run ssh as root, but still has errors  (the client):
# ssh -i ~user/.ssh/id_rsa -NTCf -vvvw any root@server-ip
....
debug1: Requesting tun unit 2147483647 in mode 1
debug1: sys_tun_open: tunnel mode 1 fd 5
Tunnel device open failed.
Could not request tunnel forwarding.
debug2: fd 3 setting TCP_NODELAY
...

Client configuration:
OpenSSH_7.7p1 Debian-2, OpenSSL 1.0.2o  27 Mar 2018
Linux 4.16.0-2-amd64 #1 SMP Debian 4.16.12-1 (2018-05-27) x86_64
Debian GNU/Linux testing (buster)

A: The creation of a network interface requires root (or at least CAP_NET_ADMIN) privileges. The error message tells the client ssh command couldn't create the tun0 interface, as confirmed by this strace excerpt when running the client ssh:
21510 open("/dev/net/tun", O_RDWR)      = 4
21510 ioctl(4, TUNSETIFF, 0x7fff5f9f1530) = -1 EPERM (Operation not permitted)
21510 close(4)                          = 0
21510 write(2, "Tunnel device open failed.\r\n", 28) = 28
21510 write(2, "Could not request tunnel forward"..., 38) = 38

The simpliest is to run it as root, for example (configuring and) using sudo or su -c and probably providing the right ssh key using -i (or it could pick root's ssh key instead). On a Debian client, this works:
su -c 'ssh -i ~myuser/.ssh/id_rsa -NTCf -w 0:0 root@server-ip'

You should replace -w 0:0 with -w any while testing to avoid clashing.
An alternate method, still requiring root (or CAP_NET_ADMIN) anyway, is to create in advance the interface following the common naming convention (tunX with X the number reused later in the ssh parameter) but giving the access to the ssh user to this interface:
# ip tuntap add name tun0 mode tun user myuser
# ip address add 192.0.2.10/24 dev tun0
# ip link set dev tun0 up

The same can be done (by root) on remote server if the remote ssh user won't be root.
The ssh command (running as myuser, eg: ssh -NTCf -w 0:0 remoteuser@server-ip)  will then be able to tunnel the traffic by using the pre-existing tunnel interfaces with matching names.
If you don't have any privileges on the client side, nor are allowed instead to run VMs or containers with network access to server-ip, you probably can't succeed.
NOTE: at the time of this Q/A, as OP found, in Debian buster (testing at this time) the packages openssh-client and openssh-server version 1:7.7p1-2 had a bug preventing the use of tun/tap tunnels. The fix in Debian was made available since (Debian) version 1:7.7p1-3.


text:
Q: convolution on 2 by 2 matrices Let $m$ be a positive integer, and let $A_1,B_1 \in \operatorname{SL}(2,\mathbb{Z})$. Can one always find matrices  $A_2,B_2 \in \operatorname{SL}(2,\mathbb{Z})$ such that
$$
A_1 \left( \begin{array}{cc}
m^{-1} & 0  \\
0& m\end{array} \right)B_1 =A_2 \left( \begin{array}{cc}
m & 0  \\
0& m^{-1}\end{array} \right)B_2
$$
PS: $\operatorname{SL}(2,\mathbb{Z})$ are the set of all $2\times 2$ matrices $A$ with entries in $\mathbb{Z}$ and $\det(A)=1$.
Many thanks.

A: Hint:
let
$J= \left( \begin{array}{cc}
0 & 1  \\
-1& 0\end{array} \right)$. Note that $J^2=-I$ and $$J \left( \begin{array}{cc}
m^{-1} & 0  \\
0& m\end{array} \right)(-J)= \left( \begin{array}{cc}
m & 0  \\
0& m^{-1}\end{array} \right)$$


text:
Q: Remove extra blank lines from SyntaxHighlighter I'm using SyntaxHighlighter in my blogger blog. But since few days it adds extra blank lines in my code. It only happens to new posts only. Can anyone please tell me how to remove these extra blank lines. I saw similar question. But it does not clearly answered. Thanks in advance.

A: This not exactly an issue with the SyntaxHighlighter - recently the blogger adds the
 tag for the ENTER.

A: Or use HTML encoder. There are some sites that encode HTML. Use them before posting to blog.

A: If we just copy and paste from windows notepad the blogger adds
 tags twice for cr and lf. So don't just copy and paste from notepad. Use blogger draft editor if it is really wanted.

A: Use the newest version of the syntaxhighlighter


text:
Q: Socket TCP/IP Octave I have created a socket TCP/IP server in C:
On the client-side, I used a script Octave to implement socket TCP/IP client
Even though the script has been terminated, but the server is still open, I would like to know what is the element which can keep the connection alive?
I saw that the Octave window is still open which contains the variables also, and I think that is the reason makes the connection is still alive. But I need some explanations about this problem.
I did the same things with a client in Python but the server is closed even I did not close the socket.


text:
Q: Out parameters and exceptions Say I have the following code:
    static void Fjuk(out string str)
    {
        str = "fjuk!";
        throw new Exception();
    }

    static void Main(string[] args)
    {
        string s = null;
        try
        {
            Fjuk(out s);
        }
        catch (Exception)
        {
            Console.WriteLine(s ?? "");
        }
    }

When I test it, s has been initialized to "fjuk!" when it's used in the catch block.
Is this guaranteed by specification or is it implementation dependent? (I have searched the C# 3 spec but couldn't find out myself)

A: It's "guaranteed" because out parameter change the value with the memory address of the parameter.

The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed.

from MSDN

A: If the method throws an exception, the output parameter is not guaranteed to be set. If the method exits without an exception, the output parameter is guaranteed to be set.
In your case, the method will always set the output parameter, but the compiler doesn't analyse the code of the method in that way. If the method exits with an exception, the output parameter is still not considered to be definitely set.
Your code in the exception handler doesn't rely on the variable being set by the method call, as you are setting the variable when it's created. If you don't set the variable when it's created, the exception handler can't use it, because it's not guaranteed to be set:
string s;
try {
  Fjuk(out s);
  Console.WriteLine(s); // here the variable is guaranteed to be set
} catch (Exception) {
  Console.WriteLine(s); // here it's not, so this won't compile
}

A: Pretty much, that is an aspect of what out means; firstly, note that out doesn't really exist - we only really need to consider ref (out is just ref with some "definite assignment" tweaks at the compiler). ref means "pass the address of this" - if we change the value via the address, then that shows immediately - it is, after all, updating the memory on the stack of Main. It can't abstract this (to delay the write) because the value could be, for example, some oversized struct that is using ref specifically for the purpose of avoiding copying it on the stack (an approach used extensively in XNA etc).

A: It's guaranteed from the perspective of Fjuk but not of Main.
In Fjuk the exception is thrown after the parameter is set. While there can be re-orderings done by compiler, jitter, and CPU, there will not be re-orderings such that the order observed by a single thread changes. Since a single thread could "notice" if the parameter wasn't set before the exception thrown, the parameter is guaranteed to be set.
In Main though, we have no knowledge of the details of Fjuk's implementation, so when the compiler analyses Main, it can't depend on that. Hence in the variation where we don't assign a value to s before the call:
static void Main()
{
    string s;
    try
    {
        Fjuk(out s);
        Console.WriteLine(s ?? "");//fine
    }
    catch (Exception)
    {
        Console.WriteLine(s ?? "");//compiler error
    }
    Console.WriteLine(s ?? "");//compiler error
}

The first attempt to use s immediately after the call to Fjuk is fine, because one can only get there if Fjuk succeeded, and if Fjuk succeeded then s must be assigned. In the second and third case though, it's possible to arrive at those lines without Fjuk succeeding, and since one cannot tell by analysis of Main whether an exception could be thrown before s is set, the uses of s must be prohibited.

A: From the C# Language Specification section 5.1.6 Output Parameters

Following the normal completion of a function member or delegate invocation, each variable that was passed as an output parameter is considered assigned in that execution path.

In other words

*

*out parameters are always assigned.

*any previous value is overwritten.

*but if the function throws an exception, the compiler assumes they are not assigned.

In practice

*

*You never need to worry about this.

*If you attempt to use an unassigned variable, the compiler will generate an error.

*So out parameters in C# are entirely safe - if they compile, they work.


text:
Q: C Char Array Define Length Using Variable Not Working void reverses(char s[])
{
    int i, count;
    i = count = 0;

    // Get the total character count in array
    while (s[count] != '\0') ++count;

    char copy[count];

Char array copy is only being defined when an integer is being used directly, such as char copy[15]; or char copy[DEFINED];.
I'm passing it an integer via the int count;, which has a declared value, so why isn't my array being defined?
I found an error in my code after that which is copied here, sorry.
I was using a while loop to do the reversing-- changing that to a for loop fixed the problem.
Many of your answers were very helpful to me anyway. So, Thank You David Cullen, Vlad from Moscos, R Sahu, user0815, and haccks
Vlad's answer is fantastic, thanks for enlightening me-- I will give much thought to your answer.
David Cullen's exactly followed my logic and gets the correct answer!

A: This code produced the expected output:
#include <stdio.h>

void reverses(char s[])
{
    int i, count;
    i = count = 0;

    while (s[count] != '\0') ++count;

    printf("count = %d\n", count);

    char copy[count + 1];

    for (i = 0; i < count; i++) {
        copy[count - i - 1] = s[i];
    }
    copy[count] = '\0';

    printf("copy = %s\n", copy);
}

int main(void)
{
    reverses("string");
}

Output:
count = 6
copy = gnirts

This was tested with gcc on OS X:

Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin13.4.0
Thread model: posix

A: It seems that your compiler does not support variable length arrays.
Take into account that to write function reverse there is no need to define an auxiliary array. The function can be written the following way
char * reverse( char s[] )
{
    size_t i = 0, n = 0;

    while ( s[n] ) ++n;

    for ( ; i < n / 2; i++ )
    {
        char c = s[i];
        s[i] = s[n-i-1];
        s[n-i-1] = c;
    }

    return s;
}

A: Variable length arrays is one of the feature added to C99. You need to compile your code with flag -std=c99 in GCC.
You should also note, if you are using MSVS, that MSVS does not support VLAs.

A: The proper way to implement variable length arrays in C is with malloc.
#include <stdlib.h>

void makeArrayOfSize(int size) {
   // Create memory for array
   char *chars = (char *)malloc(size * sizeof(char));

   // Do business logic

   free(chars); // ALWAYS free pointers to allocated memory to avoid leaks
}

Though, you can make a string reverser without copying the string (IF it is not hard-coded to the string table)...
void reverse(char* string) {
   int length = 0;
   int index = 0;
   char temp;

   // Ensure string is not null
   if (!string) {
      return;
   }

   // Get length assuming string has proper '\0' char at the end
   while (string[length]) {
      ++length;
   }

   // Play catch!
   while (index < length / 2) {
      temp = string[index++];
      string[index - 1] = string[length - index];
      string[length - index] = temp;
   }
}

Disclaimer: I didn't compile or run this code... but it reminded me of an old homework assignment so I found it nostalgic to give it a shot :)
Edit: Compiled this code. Works perfectly unless the string is hard-coded in the string table (will produce a bus error). Also will not crash if string is empty.
Took longer to write a good test than the code but here's the test and the output showing working dynamic data, but an error on the hard string:
int main(int argc, char** arcv) {
   char *string;
   char string0[0];
   char string1[1];
   char string2[2];
   char string3[3];
   char string4[4];
   char string5[5];
   char string6[6];
   char *string7 = "abcdef";

   string2[0] = 'a';

   string3[0] = 'a';
   string3[1] = 'b';

   string4[0] = 'a';
   string4[1] = 'b';
   string4[2] = 'c';

   string5[0] = 'a';
   string5[1] = 'b';
   string5[2] = 'c';
   string5[3] = 'd';

   string6[0] = 'a';
   string6[1] = 'b';
   string6[2] = 'c';
   string6[3] = 'd';
   string6[4] = 'e';

   printf("String: %s\n", string);
   reverse(string);
   printf("Reverse String: %s\n", string);

   printf("String0: %s\n", string0);
   reverse(string0);
   printf("Reverse String0: %s\n", string0);

   printf("String1: %s\n", string1);
   reverse(string1);
   printf("Reverse String1: %s\n", string1);

   printf("String2: %s\n", string2);
   reverse(string2);
   printf("Reverse String2: %s\n", string2);

   printf("String3: %s\n", string3);
   reverse(string3);
   printf("Reverse String3: %s\n", string3);

   printf("String4: %s\n", string4);
   reverse(string4);
   printf("Reverse String4: %s\n", string4);

   printf("String5: %s\n", string5);
   reverse(string5);
   printf("Reverse String5: %s\n", string5);

   printf("String6: %s\n", string6);
   reverse(string6);
   printf("Reverse String6: %s\n", string6);

   printf("String7: %s\n", string7);
   printf("(error after this)\n");
   reverse(string7);
   printf("Reverse String7: %s\n", string7);

   return 0;
}

Output:
String: (null)
Reverse String: (null)
String0:
Reverse String0:
String1:
Reverse String1:
String2: a
Reverse String2: a
String3: ab
Reverse String3: ba
String4: abc
Reverse String4: cba
String5: abcd
Reverse String5: dcba
String6: abcde
Reverse String6: edcba
String7: abcdef
(error after this)
Bus error: 10

A: in earlier versions of C, a variable could only be defined immediately after an open brace '{'
so enclose the variable definition and the associated/following code in braces.
I.E.
{
    char copy[count+1];
    ..... // other associated code that uses the 'copy' variable
}


text:
Q: Script won't work properly-- new to scripting I am trying to write a script that accepts one parameter that contains a directory name and check to see if it exits.  The name of the script should be: script_practice_3.sh and pass blc to the script.  For example: ./script_practice_3.sh blc
For some reason, my script does not work and i do not know why. I am knew to unix script writing and it is really frustrating me.
#!/bin/bash

echo "What is the parameter name that contains the script name: "
read SCRIPT

echo "What is the parameter name that contains the value blc: "
read VALUE

if [ "$?" = "0" ]
then
 echo "You must provide one parameter"
elif [ "$?" > "1" ]
then
 echo "You must provide only one parameter"
else
 test -d $SCRIPT
 if [ "$?" = "0" ]
 then
  echo "Already exists"
 else
 mkdir $VALUE
 echo "directory created"
fi

A: The special variable $? is the exit status of the most recently run command.  The number of arguments given to the script (the number of positional parameters) is given by $#.
You can't use > to compare whether a value is numerically larger than another.  For that, use -gt.  The > test is a test for determining the sort order of strings ("b sort after a, so "b" > "a"").
You also lack a ] on one of the tests.
I'm also uncertain why you read two values interactively if you are expecting the script to be given a single argument on its command line.
Suggestion:
#!/bin/sh

if [ "$#" -ne 1 ]; then
   echo need exactly one argument >&2
   exit 1
elif [ -d "$1" ]; then
   printf '"%s" is already a directory\n' "$1" >&2
   exit 1
elif ! mkdir "$1"; then
   printf 'failed to create directory "%s"\n' "$1" >&2
   exit 1
fi

printf 'Successfully created directory "%s"\n' "$1"

The $1 that is use throughout this script is the first positional parameter (the first argument given to the script).
The middle test here is actually not needed as mkdir (without its -p option) would complain if trying to create an already existing directory, so this would be caught by the last test.
This script would be invoked as you propose in the question,
./script.sh "some directory name"


text:
Q: Sincronizar hilos en Java Tengo un ejercicio de hilos para grabar y leer un fichero de texto en Java, pero lo que no consigo es que se sincronicen los hilos. De la forma que lo tengo los hilos interfieren el uno con el otro, y a la hora de escribir en el fichero entra a la vez el hilo para la lectura. Como podría sincronizar los hilos en el código que tengo? Gracias de antemano.
Código:
public class Ejercicio7 extends Thread
{
    public static void main(String[] args)
    {
        Thread hilo1 = new Ejercicio7(); hilo1.setName("hilo1");
        Thread hilo2 = new Ejercicio7(); hilo2.setName("hilo2");

        hilo1.start();
        hilo2.start();
    }

    public void run()
    {
        if(Thread.currentThread().getName().equals("hilo1"))
        {
            grabarFicheroTexto();
        }
        else
        {
            try {
                leerFicheroTexto();
            } catch (IOException e) {e.printStackTrace();}
        }
    }

    public static void grabarFicheroTexto()
    {
        char c;
        try{
            System.out.println("Vas a escribir en un fichero de texto en Java\n");
            System.out.print("Escribe aqui: ");
            FileWriter fichero=new FileWriter("..\\Threads\\src\\ejercicio7\\Archivo.txt");
            StringBuffer str=new StringBuffer();
            while ((c=(char)System.in.read())!='\n')
                str.append(c);
            String cadena=new String(str);
            fichero.write(cadena);

            if (fichero!=null)
                fichero.close();
        }catch(IOException ex){}
        System.out.println("FICHERO ESCRITO CORRECTAMENTE");
    }
    public static void leerFicheroTexto()throws IOException
    {
        System.out.println("Estas leyendo un fichero de texto en Java\n");
        FileReader fr = new FileReader("..\\Threads\\src\\ejercicio7\\Archivo.txt");
        BufferedReader br = new BufferedReader(fr);
        String s;

        while((s = br.readLine()) != null) {
          System.out.println(s);
        }
        fr.close();
    }
}

A: Utiliza synchronized para sincronizar los accesos al metodo.
Esto lo que hace es que si se esta ejecutando el metodo grabarFicheroTexto() entonces el objeto quedara bloqueado para que no se pueda acceder a el dentro del bloque synchronized desde otro hilo hasta que termine lo que mantendra la ejecución sincronizada.
Para lograr esto crea una variable statica que sera el semafaro entre el acceso a un metodo o otro y la utilizas dentro del bloque synchronized(lock){ ... }:
public class Ejercicio7 extends Thread
{

   public static readonly Object lock = new Object();

    public static void main(String[] args)
    {
        Thread hilo1 = new Ejercicio7(); hilo1.setName("hilo1");
        Thread hilo2 = new Ejercicio7(); hilo2.setName("hilo2");

        hilo1.start();
        hilo2.start();
    }

    public void run()
    {
        if(Thread.currentThread().getName().equals("hilo1"))
        {
            grabarFicheroTexto();
        }
        else
        {
            try {
                leerFicheroTexto();
            } catch (IOException e) {e.printStackTrace();}
        }
    }

    public static void grabarFicheroTexto()
    {

        synchronized(lock)
        {
            char c;
            try{
                System.out.println("Vas a escribir en un fichero de texto en Java\n");
                System.out.print("Escribe aqui: ");
                FileWriter fichero=new FileWriter("..\\Threads\\src\\ejercicio7\\Archivo.txt");
                StringBuffer str=new StringBuffer();
                while ((c=(char)System.in.read())!='\n')
                    str.append(c);
                String cadena=new String(str);
                fichero.write(cadena);

                if (fichero!=null)
                    fichero.close();
            }catch(IOException ex){}
            System.out.println("FICHERO ESCRITO CORRECTAMENTE");

        }
    }
    public static void leerFicheroTexto()throws IOException
    {
        synchronized(lock){

            System.out.println("Estas leyendo un fichero de texto en Java\n");
            FileReader fr = new FileReader("..\\Threads\\src\\ejercicio7\\Archivo.txt");
            BufferedReader br = new BufferedReader(fr);
            String s;

            while((s = br.readLine()) != null) {
              System.out.println(s);
            }
            fr.close();
        }
    }
}

A: Utiliza los métodos aquire and release mediante un objeto Semaphore para bloquear el hilo de lectura si se esta escribiendo y viceversa.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.Semaphore;

public class Ejercicio7 extends Thread

{
    public static Semaphore mutex = new Semaphore(1, true);

    public static void main(String[] args) throws InterruptedException
    {
        Thread hilo1 = new Ejercicio7(); hilo1.setName("hilo1");
        Thread hilo2 = new Ejercicio7(); hilo2.setName("hilo2");

        hilo1.start();
        hilo2.start();
    }

    public void run()
    {

        if(Thread.currentThread().getName().equals("hilo1"))
        {
            grabarFicheroTexto();
        }

        else
        {
            try {
                leerFicheroTexto();
            } catch (IOException e) {e.printStackTrace();}
        }
    }

    public static void grabarFicheroTexto()
    {

        mutex.acquireUninterruptibly();
        char c;
        String contenido = "";
        try{
            System.out.println("Vas a escribir en un fichero de texto en Java\n");
            System.out.print("Escribe aqui: ");
            FileWriter fichero=new FileWriter("Archivo.txt");
            StringBuffer str=new StringBuffer();
            while (true){
                c=(char)System.in.read();
                if(c == ' ')
                    contenido = "";
                if(c == '\n')
                    if(contenido.trim().equalsIgnoreCase("fin"))
                        break;
                    else contenido = "";
                contenido += c;
                str.append(c);
            }
            String cadena=new String(str);
            cadena = cadena.replace("fin", "");
            fichero.write(cadena);

            if (fichero!=null)
                fichero.close();
        }catch(IOException ex){}
        System.out.println("FICHERO ESCRITO CORRECTAMENTE");

        mutex.release();
    }
    public static void leerFicheroTexto()throws IOException
    {

        mutex.acquireUninterruptibly();

        System.out.println("Estas leyendo un fichero de texto en Java\n");
        FileReader fr = new FileReader("Archivo.txt");
        BufferedReader br = new BufferedReader(fr);
        String s;

        while((s = br.readLine()) != null) {
          System.out.println(s);
        }
        fr.close();

        mutex.release();

    }
}

OUTPUT


text:
Q: Why does tab.url from the callback of "chrome.tabs.onUpdated.addListener()" return undefined? For my Chrome extension, I need to show the pageAction only on a certain website. I used to do this with declarativeContent, but it isn't supported on Firefox, so I have to do it the manual way. The answers to this question suggested that you could simply use something like this:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
  if (changeInfo.status === "complete" && tab.url) {
    if (tab.url.match(/google.com/)) {
      chrome.pageAction.show(tabId);
    }
  }
});

This didn't work for me, so I modified the code in the background script to look like this:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
  console.log("Tab updated! Tab URL: " + tab.url);
});

Every time you update a tab the console just prints Tab updated! Tab URL: undefined a few times. I also tried to query the tab like the answers to this question said, which produces the same output.
The other files of the extension are:
manifest.json:
{
  "name": "Test",
  "version": "1.0",
  "description": "Test for StackOverflow",

  "permissions": ["activeTab"],

  "background": {
    "scripts": ["background.js"]
  },
  "page_action": {
    "default_popup": "popup.html"
  },
  "manifest_version": 2
}

popup.html:
<!DOCTYPE html>
<html>
  <body>
    This is a popup!
  </body>
</html>

A: You are missing the tabs permission from your manifest.json file. With this permission the URL of the tab should also be logged to the console.
"permissions": ["activeTab", "tabs"] // <-- This

manifest.json:
{
  "name": "Test",
  "version": "1.0",
  "description": "Test for StackOverflow",

  "permissions": ["activeTab", "tabs"],

  "background": {
    "scripts": ["background.js"]
  },
  "page_action": {
    "default_popup": "popup.html"
  },
  "manifest_version": 2
}


text:
Q: How to plot piecewise cosine and make it periodic? Hi I have this piecewise function and its graph :cosine and right graph
I supposed to implement that piecewise in python and get the same graph at the next.
My code is this :
import numpy as np
import matplotlib.pyplot as plt

def f(time):

    T   = time
    Ts1 = 0.3
    Ts2 = 0.4
    ind = 0

    t_axis = np.linspace(0,T,100)
    ft=np.arange(100.0)

    for t in t_axis:

        if t<Ts1:
            ft[ind] = (np.cos(np.pi*t/Ts1))
            ind += 1
        elif Ts1<=t<Ts2:
            ft[ind] = (np.cos(np.pi*(t+Ts2-Ts1)/(Ts1)))
            ind += 1
        else:
            ft[ind] = (0)
            ind +=1

return ft,t_axis

a,b = f(1)
plt.plot(b,a)
plt.show()

And unfotunately i get this weird graph :
my weird graph
{{{ I didn't made the multiplication of e(t) and the constants. Because in the end this can not change the graph (just brings some amplification or level shifting i figure out.) }}}
And here are my questions:
1- Is my code OK for that function ?
2- Could it be something related with the values of Ts1 and Ts2. Because i chosed them randomly.
3-If i achieve to get the right graph, how should i change the cosine argument in order to visualise graph over a couple periods ?

A: I'm not sure what the graph of the first link represents.
1 - Your code is ok for e(t) function.
2 - If we are talking about discontinuity in the graph, It might be related to given values. You may try Ts1=0.2, Ts2=0.6 and add 1 to equations.
ft[ind] = (np.cos(np.pi*(t+Ts2-Ts1)/(Ts1))) + 1 like that.
3 - I think, easiest way to achieve this is to add the following line at the beginning of for loop:
t = t % period
By applying some of these steps, I get something like this:

Not sure if it is what you want. If you want an output like the one in the first link then you should give more information about that graph. Why are there two plots? What is E(la) and E(lv)? etc.
Update :
Code generating the graph above :
import numpy as np
import matplotlib.pyplot as plt

def f(time):

    T   = time
    Ts1 = 0.2
    Ts2 = 0.6
    ind = 0
    period = 1

    t_axis = np.linspace(0,T,1000)
    ft=np.arange(1000.0)

    for t in t_axis:

        t = t % period
        if t<Ts1:
            ft[ind] = (np.cos(np.pi*t/Ts1)) + 1
            ind += 1
        elif Ts1<=t<Ts2:
            ft[ind] = (np.cos(np.pi*(t+Ts2-Ts1)/(Ts1))) + 1
            ind += 1
        else:
            ft[ind] = (0)
            ind +=1

    return ft,t_axis

a,b = f(2)
plt.plot(b,a)
plt.show()


text:
Q: I am calling an ASMX web service from javascript and it is preveting my session from timing out EDIT 2:
I have a background process running on the server side based on a schedule or an end user's request, and i need to show an image to all the users to keep him notified that this process is running, or take out the image when the process is finished.
EDIT 2 Finished
I am calling an ASMX web service which is located in my website hosted on my IIS from javascript and it is preveting my session from timing out.
Why does a call from the client to the webservice prevent the session on my website to timeout ?
Is there a way to prevent it ?
Please tell me if you need more clarity in my question or more details.
EDIT 1:
Based on the information and the link provided by @Rene147 in the answer below as well as some googling, i tried the following on the side of my webservice :
[WebMethod(EnableSession=false)]
public string GetSummary()
{
    HttpContext.Current.Response.Cookies.Remove(System.Web.Security.FormsAuthentication.FormsCookieName);
    return "something";
}

But it turns out that HttpContext.Current.Response.Cookies is always empty.
Any hints ?

A: According to my understanding of your last edit - if you want to read cookie's value, you need to use Context.Request.Cookies instead of Response.
[WebMethod(EnableSession = false)]
public string GetSummary()
{
    HttpCookie decryptedCookie =
        Context.Request.Cookies[FormsAuthentication.FormsCookieName];

    return "something";
}

A: By default Forms Authentication uses Sliding Expiration.  This means that each time you make a request to the server your cookies expiration is reset (with some caveats).
To disable Sliding Expiration set "slidingExpiration" in your web.config to false. Taken from Sliding Expiration
<authentication mode="Forms">
  <forms loginUrl="member_login.aspx"
    name=".ASPXFORMSAUTH"
    cookieless="UseCookies"
    requireSSL="true"
    slidingExpiration="false" />
</authentication>


text:
Q: how to update an entity in Entity Framework 4 .NET my code is something like this:
public class Program
{
 [STAThread]
 static void main()
 {
  DataAccessClass dal = new DataAccessClass();
  List<Person> list = dal.GetPersons();
  Person p = list[0];
  p.LastName = "Changed!";
  dal.Update(p);
 }
}

public class DataAccessClass
{
 public static List<Person> GetPersons()
 {
  MyDBEntities context = new MyDBEntities();
  return context.Persons.ToList();
 }

 public void Update(Person p)
 {
  // what sould be written here?
 }
}

now please tell me what should i write in the Update() method?
everything i write , encounters various exceptions.
(please pay attention that the data loaded is tracked , connected or something like that)

A: Taken from Employee Info Starter Kit, you can consider the code snippet as below:
public void UpdateEmployee(Employee updatedEmployee)
        {
            //attaching and making ready for parsistance
            if (updatedEmployee.EntityState == EntityState.Detached)
                _DatabaseContext.Employees.Attach(updatedEmployee);
            _DatabaseContext.ObjectStateManager.ChangeObjectState(updatedEmployee, System.Data.EntityState.Modified);
            _DatabaseContext.SaveChanges();
        }

A: The problem is that your Person entities are still attached to context created in GetPersons. If you want to work with attached entities you have to use same context instance in both select and update operations. You have two choices to solve your problem.
1) Correctly handled attached entities
public class Program
{
  [STAThread]
  static void main()
  {
    using (DataAccessClass dal = new DataAccessClass())
    {
      List<Person> list = dal.GetPersons();
      Person p = list[0];
      p.LastName = "Changed!";
      dal.Save();
    }
  }
}

public class DataAccessClass : IDisposable
{
  private MyDBEntities _context = new MyDBEntities();

  public List<Person> GetPersons()
  {
    return _context.Persons.ToList();
  }

  public void Save()
  {
    // Context tracks changes on your entities. You don't have to do anything. Simply call
    // SaveChanges and all changes in all loaded entities will be done in DB.
    _context.SaveChanges();
  }

  public void Dispose()
  {
    if (_context != null)
    {
      _context.Dispose();
      _context = null;
    }
  }
}

2) Don't use attached entities
public class Program
{
  [STAThread]
  static void main()
  {
    DataAccessClass dal = new DataAccessClass())
    List<Person> list = DataAccessClass.GetPersons();
    Person p = list[0];
    p.LastName = "Changed!";
    dal.Update(p);
  }
}

public class DataAccessClass
{
  public static List<Person> GetPersons()
  {
    // Closing context will detach entities
    using (MyDBEntities context = new MyDBEntities())
    {
      return context.Persons.ToList();
    }
  }

  public void Update(Person p)
  {
    using (MyDBEntities context = new MyDBEntities())
    {
      context.Persons.Attach(p);
      // Detached entities don't track changes so after attaching you have to say
      // what changes have been done
      context.ObjectStateManager.ChangeObjectState(p, System.Data.EntityState.Modified);
      context.SaveChanges();
    }
  }
}

A: does not work when you have a property on entity which is a ConcurrencyToken.
At least for me. Because you then get a OptimisticConcurrencyException.
What i do (and i think this is not an optimum solution),
facts:
- I use a new context because of n-tier. So, the previous/original entity with its values are not known. Either you supplies the context with original and old (bah) or like me load original first prior to update:

 T originalItem = sessionManager.Set().Single(x => x.ID == changedEntity.ID);
        if(changedEntity.lastChangedDate != originalItem.lastChangedDate)
            throw new OptimisticConcurrencyException(String.Format("Trying to update entity with lastChangedDate {0} using lastChangedDate {1}!", originalItem.lastChangedDate, changedEntity.lastChangedDate));

        ObjectStateEntry state = sessionManager.ObjectStateManager.GetObjectStateEntry(originalItem);
        state.ApplyCurrentValues(changedEntity);
        state.ChangeState(System.Data.EntityState.Modified);
        sessionManager.SaveChanges();

If you know something better, please let me know.
Atam


text:
Q: select single value from linq I Have a dataTable called dt that filled from Database. the SQL Command is:
SELECT s.keyName,s.value FROM setting as s

after I fill dataTable I want to select a single value from filled dt. So I tried to do some linq that here I show:
if (dtSetting.Rows.Count > 0)
  {
      var r1 = (from r in dtSetting.AsEnumerable()
       where r.Field<string>("keyName") == "logoName"
       select r.Field<string>("value"));

       MessageBox.Show(r1.ToString());
  }

but I can't see the value of s.value and r1.show says that

system.data.enumerableRowCollection`1[system.String]

How can I implement this code to get a real value of the specific column?

A: Your r1 is an IEnumerable < string >. You should select an item from it.
Example:
   MessageBox.Show(r1.First());

A: r1 variable is IEnumarable, so you can get the value by applying index . You can use First() and ElementAt() too.
 if (r1.Count() > 0)
    MessageBox.Show(r1.ToList()[0].ToString());
    //MessageBox.Show(r1.First());
    //MessageBox.Show(r1.ElementAt(0));


text:
Q: Force Angular2 to reload component on navigate In Angular2 RC1 and lower calling a route link always causes a component to reload:
<a [routerLink]="['/page', {id: 1}]">A link </a>

Using Angular2, none RC, the component isn't reloaded if its navigating to itself with different parameters.  Is there any way to get the reload behavior back?
I understand the other way of dealing with this, subscribing from the ActivatedRoute and detected variable changes, but this causes the component logic to increase in complexity.

A: Although you've mentioned 'ActivatedRoute' and how it will complex your code, I think that this will help other people that are facing this problem when they're reaching your question, like me :) .
This topic will answer your question.
This code below (pasted from the topic above), is where the 'magic' is happening.
If you'll place your 'reload' code in this subsribe function, your component will reload.
ngOnInit() {
   this.sub = this.route.params.subscribe(params => {
      this.id = +params['id']; // (+) converts string 'id' to a number
      // Some 'reload' coding
      // In a real app: dispatch action to load the details here.
   });
}

A: A simple way to do this is to force the template to reload using *ngIf. You would need a variable that "turns the component off and on". If the values of variables have changed before this off/on behaviour, they will be rendered when the view is on again.


text:
Q: Please can moderators have a "take the discussion to chat" post notice? If there are a large number of comments then when they are rolled up only (some of) the up-voted ones are shown until you hit the "Add comment" link. Therefore if we respond to a "more than 20 comments posted" flag by adding a comment along the lines:

Can any of these comments be usefully incorporated into the post? If not please take the discussion to [chat]

This comment is not immediately visible and only becomes so it it has a lot of up-votes.
For example - see this question on Programmers. The system generated the "more than 20 comments posted" message and I added a comment along the lines of the one above. Even though it's been upvoted it's still not visible on the default view. Having it visible would act as a deterrent to people adding more noise.
Initially I thought it would be really useful if we moderators could "pin" such comments so that they were always visible - but I don't think a general purpose solution which only has limited use is required. We already have the ability to add post notices, so:
I'd like to request a new post notice option for this situation.
Alternatively add the ability to prevent comments being added (time limited of course) with a system message telling people to either incorporate the comments into the post or take the conversation to chat.

A: I like the idea, but I'm not sure of adding a feature when one that we have could suffice. How about just a post notice that says:

This post has received many constructive comments. Please be sure that all relevant information from the comment discussion is incorporated into this post. To help, you can edit the post as needed and refrain from adding unnecessary comments. If a comment below appears to be obsolete, please flag it as such.

I believe the current expiration settings for post notices would be fine for this as well. Additionally, the formality of a notice might be more effective.
I agree 100% that we need something.


text:
Q: SQL index with in clause Our application has suddenly gone slow in one of the env. The only change I have done is changed the SQL. Before release, the SQL was something like this
Select EmployeeId
From Employee
Where Dept='CS'
  and record_state='ACTIVE'
  and EmployeeTypeId ='1'

After release SQL is
Select EmployeeId
From Employee Where Dept='CS'
 and record_state='ACTIVE'
 and EmployeeTypeId IN ('1','2')

The index on this table is employee_state_id_index (Dept,record_state,EmployeeTypeId )
The index has not been changed. Does this index not help the new SQL? does the new SQL scan the whole table? I have no idea how indexes work with in clause. Appreciate your help and comments
The explain plan for the query is
| Id  | Operation         | Name                     | Rows  | Bytes | Cost (%CPU)|

|   0 | DELETE STATEMENT  |                          |     1 |    57 |     4   (0)|
|   1 |  DELETE           | Employee                 |       |       |            |
|*  2 |   INDEX RANGE SCAN| employee_state_id_index  |     1 |    57 |     4   (0)|
--------------------------------------------------------------------------------

Predicate Information (identified by operation id):

PLAN_TABLE_OUTPUT

   2 - access("C"."Dept"='CS' AND
              "C"."RECORD_STATE"='ACTIVE')
       filter("C"."EmployeeTypeId"='1' OR
              "C"."EmployeeTypeId"='2')

A: The solution to the problem we faced, was reindexing the table. The table had a 10 million records and we recently cleaned up the data in the table (when we realized that we had duplicate records) and that reduced it to almost half of the amount of records it previously had. So we thought we will give a try with reindexing, since anyway it needed it. And that helped :)


text:
Q: PostgreSQL calculating average and standard deviation for hour of the day I have a collection of event data with timestamps and I want to know the average (arithmetic mean) hour of day these events occur and the standard deviation (in hours). The timestamps are in UTC timezone but the events are the result of user activity that might have occurred in a different timezone, e.g. UTC+12, and I don't know which.
This seems straight forward enough to do but due to the cyclical nature of 24 hour time it's not obvious. (For example 23 and 0 hours are close together in practice, but not mathematically.)
Here's an example:
Given these hours: 3, 4, 3, 0, 21, 23, 4, the mean looks to be 8.3 and the standard deviation (population) 8.8. But if those events occurred in UTC+12 that would be incorrect as the "real" hours would be 15, 16, 15, 12, 9, 11, 16, which gives a mean of 13.4, standard dev (pop) 2.6.
What is the best way to calculate the correct mean (in UTC it would be 13.4) and stddev (pop) (2.6)?
Example data (events table):
id |     timestamp
---+--------------------
1  | 2016-05-20 03:00:00
2  | 2016-05-20 04:00:00
3  | 2016-05-20 03:00:00
4  | 2016-05-20 00:00:00
5  | 2016-05-20 21:00:00
6  | 2016-05-20 23:00:00
7  | 2016-05-20 04:00:00

The PostgreSQL query I'm using right now is the following:
SELECT CAST(avg(extract(epoch FROM timestamp::TIME)) AS dec(18, 10)),
       CAST(stddev_pop(extract(epoch FROM timestamp::TIME)) AS dec(18, 10))
FROM   events

Current result:
      Mean       |      Stddev
-----------------+-----------------
29828.5714285714 | 31602.4282198023

(This is in seconds, this in hours is mean 8.3 and std dev 8.8.)
Expected result is mean ~13.4, std dev ~2.6.

A: You can use AT TIME ZONE to convert the timezone.
SET TIME ZONE 'UTC';

WITH
test(id, dummy_time) as
(
values
(1, TIMESTAMP '2016-05-20 03:00:00'),
(2, TIMESTAMP '2016-05-20 04:00:00'),
(3, TIMESTAMP '2016-05-20 03:00:00'),
(4, TIMESTAMP '2016-05-20 00:00:00'),
(5, TIMESTAMP '2016-05-20 21:00:00'),
(6, TIMESTAMP '2016-05-20 23:00:00'),
(7, TIMESTAMP '2016-05-20 04:00:00')
)

SELECT      avg(date_part('HOUR', dummy_time AT TIME ZONE 'UTC+12')) as AVERAGE_HOUR,
            stddev_pop(date_part('HOUR', dummy_time AT TIME ZONE 'UTC+12')) as STDEV_HOUR

FROM        test

This gives the 13.4 mean and 2.6 stdev you are looking for.


text:
Q: Remove "yak" from a string I am working on a codingbat problem:Given a string, return a version where all the "yak" are removed, but the "a" can be any char. The "yak" strings will not overlap. I am look at the solution but there is one part of that code I do not understand.....
How come the first part of the if statement "i = i+ 2" could return the string and you don't need anything else? I mean after all these three conditions are met and just write i = i + 2,and that's it. that is going to give you a String as a result. I don't get it, please help.
public String stringYak(String str) {
  String result = "";

  for (int i=0; i<str.length(); i++) {
    // Look for i starting a "yak" -- advance i in that case
    if (i+2<str.length() && str.charAt(i)=='y' && str.charAt(i+2)=='k') {
      i =  i + 2;
    } else { // Otherwise do the normal append
      result = result + str.charAt(i);
    }
  }

  return result;
}

A: This may not be the style of answer you want, but a simple call to String#replaceAll() should work:
String str = "Some string yak containing yok.";
str = str.replaceAll("y.k", "");

A: The code is selecting what characters to put in the new string.
We go through the characters one by one.
If we run into a "y.k", skip this whole section
Else add the character to the new string.

[a][b][y][c][k][d] => New String: [a] (a is okay)
  .|..........................
[a][b][y][c][k][d] => New String: [a][b] (b is okay)
  ......|.....................
[a][b][y][c][k][d] => New String: [a][b] (Oops! We have run into the y.k
  pattern, skip it)   ..........|.................
[a][b][y][c][k][d] => New String: [a][b][d] (d is okay)
  .....................|......
Final String: [a][b][d]

A: Doing i = i + 2 is not going to give you any String it is simply incrementing the for loop so you do not need to re-evaluate the next two chars as they have already been evaluated.
The key point is in the else part, which will append the char if it is not y and the character after-next is also not k


text:
Q: Rails console scrollback So I have two developer machines, running the same version of Rails and Ruby. One machine has scrollback functionality that survives exit and console restart. The other machine forgets everything on exit. Any idea why this is happening? How can I get a persistent scrollback buffer on my other machine?

A: You probably have the wirble gem installed on one machine and not the other.

A: Do you have irb history enabled on one machine and not the other?
http://macdevelopertips.com/ruby/ruby-irb-command-history.html
You may have a ~/.irbrc and a ~/.irb-history file somewhere on the machine that is keeping history.


text:
Q: Smartsheet-api and Python SDK certificate verify failed I am having a basic problem with the SmartSheet Python SDK.
I am using Python 3.4
Using the following sample code from the SmartSheet docs:
import smartsheet

smartsheet = smartsheet.Smartsheet(MY_TOKEN_HERE)

me = smartsheet.Users.get_current_user()

print(me)

the line me = smartsheet.Users.get_current_user()
will cause multiple errors of this type
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600)

My token works with both REST API via POSTMAN and simply using Python/Requests functionality
What am I missing ?

A: I'd suggest that you try using version 2015.04.28 of certifi:
pip uninstall certifi
pip install certifi==2015.04.28


text:
Q: PHP variable in soap array I'm trying to consume a soap webservice with PHP.
At this moment it's working fine while I "hardcode" the parameters.
But now I need to use variables instead of using static values.
I've got this array:
$params = Array('transactionId' => '123');

This will return me this transaction id status.
But now whe I use this:
$params = Array('transactionId' => $id);

I get

'There is a parameter not valid'

Is there any way to use a PHP variable in this array?
Kind regards


text:
Q: How to integrate auth0 in vue using typescript? I am new to typescript. I am able to integrate auth0 using javascript because auth0 providing a sample for that but there is no sample app available for vue with typescript. please let me know any links or samples.

A: Here is a sample app provided from the official vue js docs, just choose your preferred backend tool for those listed in the link:
https://auth0.com/developers/hub/code-samples/full-stack/hello-world/basic-role-based-access-control/spa/vue-3-typescript


text:
Q: Ganglia without multicast I'm running Ganglia 3.1.2 on a network where there is no multicast (nor can I turn it on).  Does anyone have an elegant solution for getting ganglia to work correctly?  I found this:
http://code.google.com/p/ganglia-multicast-hack/
but it does not scale very well.
Right now, I have separate data_source lines for each host on my network in my gmetad.conf file, but that too does not scale well, and I can't get accurate summary statistics, because it keeps overwriting the rrds (although the host statistics work just fine).
Any pointers would be greatly appreciated (or confirmation that I have found the best solution already).
Thanks!

A: After further research, I found the answer.  On my clients, I added the following to gmond.conf:
udp_send_channel {
  host = monitoring-host
  port = 8666
  ttl = 1
}

udp_send_channel {
  host = monitoring-host-backup
  port = 8666
  ttl = 1
}

This sends the data via unicast UDP to the monitoring host and the backup every 1 second.
Then on the monitoring host, I added this:
udp_recv_channel {
  port = 8666
}

The key is to get rid of the multicast entry, which is there by default.

A: This works, but the problem is that all the nodes will end up in the same default datasource, so their Cluster information is lost, which is not so nice for multi-cluster environments.
I haven't tried yet, but a possible workaround for this would be to create a UDP channel for each cluster, which is not so nice if you have many of them.
Later Edit:
My current setup is using unicast at the cluster level due to networking limitations, and all the data is getting sent to a node from each cluster. Then I contact each of those using metad to get all the data regarding that cluster.
This way the clusters will be assigned to their own data sources, and their full information will be there.
The config would look like this:
# on each node in the cluster
udp_send_channel {
  host = 1.2.3.4 # this is a member of the cluster, not a metad server
  port = 8650
}

Then on the metad:
data_source "My Cluster" 1.2.3.4

For redundancy you can have multiple udp_send_channel entries and multiple IPs listed in the data_source. I personally use two for each cluster.
For federation I use something like this:
data_source "My Grid" 1.2.3.5:8651

This is valid only if you have a metad listening on port 8651 there.

A: Was facing the same problem with multicast mode while configuring Ganglia on Amazon EC2 cloud which prevents the use of multicast in its network. The possible solution is to switch to unicast mode which works fortunately.
To be very concise, below given simple steps are there to get rid of multicast mode.

*

*Make one of your nodes master running gmond (ganglia data collector) daemon.

Example: 10 Nodes are there which are running gmond daemon. Pick a node any one from 10 and make that Master which will be getting all the data from 10 Nodes even should also be the slave of itself.
# Define the cluster.
cluster {
  name = "Yellow"
  owner = "Your Company"
  latlong = "N34.02 W118.45"
  url = "http://yourcompany.com/"
}

# Disable multicast and define the host, the yellow master, where nodes in the cluster send data.

udp_send_channel {
  # mcast_join = 239.2.11.71  (No need to join as mcast is not being used)
  host = master.among10node.com  (put the IP/Hostname of server from any 10 nodes to ack as                  master)
  port = 8649
  ttl = 1
}

udp_recv_channel {
  # mcast_join = 239.2.11.71   (Disabled mcast as it is not being used)
  port = 8649
  # bind = 239.2.11.71  (No need to bind as mcast is not being used)
}

Note: Copy the same configuration on all 10 nodes running gmond daemon. Restart Master first then all others. Hope it will work and the Master Node will be having all the data from other nodes.
Now configure Ganglia data consolidator (gmetad) daemon to use your Master Node as a primary data source.
Example:
data_source "Yellow" master.among10node.com

# default port is 8649, define here if you are using non default

Now restart the gmetad daemon and let the magic begin.
Cheers
Mohd Mozammil Khan

A: See also:
https://github.com/ganglia/monitor-core/tree/feature/cloud
I installed it today and got it working on EC2 which doesn't allow multicast.


text:
Q: Iterative Convergence Formulation for Linear Fractional Transformation with Rational Coefficients All numbers discussed here are rational (we have not yet constructed the real numbers).
Let $S > 0$, $K > 0$ with $K^2 > S$
Set $$F(x) = \frac{S + Kx}{K + x}$$
Let $p > 0$ such that $p^2 < S$
Define $p_{k+1} = F(p_{k})$, with $p_{1} = F(p)$
Let $q > 0$ such that $q^2 > S$
Define $q_{k+1} = F(q_{k})$, with $q_{1} = F(q)$
Give a direct proof (no matrix theory, etc) of the following:
PROPOSITION:
$p_{k}$ < $q_{k}$ for all $k>0$
The intersection of the open intervals of rational numbers ($p_{k}$, $q_{k}$) for $k$ greater than $0$ is either empty or contains a single point.
The intersection contains a single point iff S has a rational square root, and the single point is then $\sqrt{S}$.
Bonus Problem: Describe what happens when $K > 0$ but $K^2 < S$.
For motivation/grounding see
How to prove that the set $A = \left\{ {p:{p^2} < 2,p \in {\Bbb Q^+}} \right\}$ has no greatest element?

A: To answer the question, I feel compelled to develop what I call Simple LFT Theory. As far as I know, this is original research.
You can skip this and proceed directly to subtitle "ANSWER" below if you wish.
For fixed $S > 0$, let
$\mathfrak S =$ $\{$ $F_R(x): \frac{S + Rx}{R + x}\; |\; R > 0 $ $\}$
Under functional composition, $\,\mathfrak S$ forms a commutative semigroup:
(1) $F_M \circ F_N = F_\frac{S + MN}{M + N}$
***Note that $F_{\sqrt S}$ is the 'zero' element. This is the constant function
sending all $x$ to $\sqrt S$. It 'absorbs' all elements in $\mathfrak S$, since the linear fractional transformations in this semigroup all have $\sqrt S$ as their one and only positive fixed point. So (1) is only true when
$M = \sqrt S$ implies $N = \sqrt S$
and
$N = \sqrt S$ implies $M = \sqrt S$.

In particular,
$F_K \circ F_K = F_\frac{S + K^2}{2K}$
Proposition 1: If M and N are two positive numbers and the square of neither one of them is equal to $S$ then
$(\frac{S + MN}{M + N})^2 > S$
when ($M^2 > S$ and $N^2 > S$) OR ($M^2 < S$ and $N^2 < S$)
otherwise
$(\frac{S + MN}{M + N})^2 < S$
Also, if, say $M^2 > S$, then $\frac{S + MN}{M + N}$ < M.
Proof: Expanding, we have to check
$S^2 + 2MNS + (MN)^2 > M^2S + 2MNS + N^2S$, or
$S^2 - (M^2 + N^2)S + (MN)^2 > 0$
Considering this as a quadratic equation in $S$ will be helpful here. You will get a pleasant surprise when you look at the discriminant, which is positive and equal to $(M^2 - N^2)^2$. The last statement is easy to see.
QED
The subset $\mathfrak K$ of $F_K(x)$ with $K^2 > S$ of $\mathfrak S$ is a subsemigroup, closed under functional composition.
Proposition 2: For $S > 0, K > 0$ with $K^2 > S$. Set $F^1 = F_K$.
The set (sequence) $\{F^1, F^2, F^3, ..., F^n, ...\}$ of LFTs form a subsemigroup of $\mathfrak K$. The corresponding sequence
$\{K, K_2, K_3, ..., K_n, ...\}$ is decreasing.
Proof:Just apply Proposition 1 by setting both $M$ and $N$ to $K$. QED
Proposition 3: The sequence $(K_n)^2$ converges to $S$.
Proof: The decreasing sequence $\{K, K_2, K_3, ..., K_n, ...\}$ is bounded below. Is is obvious that the gaps between two consecutive $K's$ must go to zero, otherwise the $K's$ would 'march' right past this lower bound.
Take an arbitrarily small number of the form
$\frac{\epsilon}{2K}$
We can find an $n$ where $K_n - K_{n+1} < \frac{\epsilon}{2K}$
But since $F^{n+1} = F F^n$ and using (1), we can write
$K_n - \frac{S + KK_n}{K + K_n} < \frac{\epsilon}{2K}$. Since $K + K_n < 2K$, when we multiply both sides by $K + K_n$, you can see that the inequality
${K_n}^2 - S < \epsilon$
holds. QED
We have two corresponding propositions when $K^2 < S$.
Proposition 2': For $S > 0, K > 0$ with $K^2 < S$. Set $F^1 = F_K$.
The sequence $(F^1, F^2, F^3, ..., F^n, ...)$ of LFTs naturally spits into odd and even subsequences with corresponding "K" subsequences.
Odd:
$\{K, K_3, K_5, ..., K_{2n+1}, ...\}$ is increasing.
The square of any number in this subsequence is less than $S$.
Even:
$\{K_2, K_4, K_6, ..., K_{2n}, ...\}$ is decreasing.
The square of any number in this subsequence is greater than $S$.
Proof: We leave the proof to the reader.
Proposition 3': The odd subssequence $({K_{2n+1}}^2)$  converges to $S$ and the even subssequence $({K_{2n}}^2)$ converges to $S$.
Proof: Utilizing Proposition 3 one can readily see that the even subsequence converges. Note that the odd subsequence (excluding the first number K) is obtained as follows,
$K_{2n} \to (\frac{S + KK_{2n}}{K + K_{2n}}) = K_{2n+1} $
You now want
$S - (\frac{S + KK_{2n}}{K + K_{2n}})^2 < \epsilon$ as $n \to \infty$.
But by squaring $K_{2n+1}$ and simplifying you can show convergence.
QED
ANSWER:
Using the techniques found in "finding a better $p$", you can show that
$p < p_1$ and $p_1^2 < S$
and
$q > q_1$ and $q_1^2 > S$
So we have
$p < p_1 < p_2 < ... < p_n < ... < ... < q_n < ... < q_3 < q_2 < q_1 < q$
We will now show that the square of the $p's$ converge to $S$.
Take an arbitrarily small number of the form
$\frac{\epsilon}{2K}$
Since there is an upper bound for this increasing sequence, it is obvious that the gaps between two consecutive $p's$ must go to zero, for otherwise the $p's$ would 'march' right past this upper bound. So, for some $n > 1$,
$F(p_n) - p_n < \frac{\epsilon}{2K}$
or
$S - {p_n}^2 < (K + p)\frac{\epsilon}{2K}$
and since $K + p < 2K$, we have
$S - {p_n}^2 < \epsilon$
We leave it to the reader to show that the square of the $q's$ converges to $S$.
We have proven the proposition posed in the question.


text:
Q: error: lvalue required as left operand of assignment (C) I see many different answers to this question and have looked at many of them yet I cannot find the answer to my problem.
The error im getting is
bitarray.c:27:19: error: lvalue required as left operand of assignment

(newArr << i) ^= 1;

Any ideas?
Thanks

A: You are trying to assign to a result from an operation another result. Try the following right way to do it:
newArr = (newArr << i) ^ 1;

The idea is that you have to have a valid lvvalue and the temporary result of the "<<" is not a valid one. You need a variable like newArr. The following answer on SO explains many terms related to this situation:
What are rvalues, lvalues, xvalues, glvalues, and prvalues?
Hope I shed some light on the problem!

A: "<<" is a binary operator just like "+" or a "-".
It needs to be assigned to a variable.
For Eg. you cannot just write this
               a+b;
Correct way is
               c = a+b;


text:
Q: How can i find django user from cached backend session I am getting some error emails every now and then and i am not able to find the user.
All info i can get is sessionid and csrf cookie.
These are same in many emails so i think the user is one but how can i find it as i am not using database session but cached session engine.

A: If your SESSION_ENGINE is set to:

*

*"django.contrib.sessions.backends.cached_db": Combining usage of cache and database, you can lookup that session from database.

*"django.contrib.sessions.backends.cache" : Cache only; No persistence, you will have to look up that session from cache but fast enough before cached data can be evicted if the cache fills up or if the cache server is restarted. Here you will have to lookup the session when the error occurs, e.g you will need to handle the exception caused by that error, at that point, you can lookup for the user using the session or from request and store the user in the log.
As you said "These are same in many emails so i think the user is one" so it possible when you get the e-mail that the session is still living in the cache ! So look for it in the cache, if for example the session is identified (key) with its "sessionid" in the cache try to get it using "sessionid" as the key.
from django.core.cache import cache
session = cache.get(sessionid)

Then get the user:
from django.contrib.auth.models import User
data = session.get_decoded()
uid = data.get('_auth_user_id', None)
user = User.objects.get(id = uid)

This is just a hint, I'm not sure if it will work coz I don't have the same settings as yours.


text:
Q: Code wont work in browser but works in snippet tool I can get my code to work in the snippet tool, but once I try to run this in my own browser when I click on the $12 button, no alert will show up. Also, how can I get the alert to grab the header name so it displays "You have selected 1 gram of Skywalker".
The only buttons I have working so far are 12 and 35.
When a user selects a button, I want to alert them of the corresponding weight  as well as the product name

$(".btn1").click(function () {
  var number = $(this).closest("tr").find(".weight1").text();
  var name =$(this).closest("h3").find(".itemName").text();
  alert("You have selected " + number + " of " + name);
});

<!DOCTYPE html>

 <title>Herb</title>
 <link rel="stylesheet" type="text/css" href="all.css">

 Show Menu
    <input type="checkbox" id="show-menu" role="button">

Home

Deals!

            Menu ↓

Herb

Concentrates

Edibles

            Login ↓

Login

Sign up

            Social Media ↓

Facebook

Snapchat

Instagram

Twitter

Skywalker

   1 gram
   <input id="button1" class="btn1" type="button" value="$12">

   1/8 ounce
    <input class="btn1" type="button" name="item1" value="$35">

   1/4 ounce
   <input class="btn" type="button" name="item1" value="$75">

   1/2 ounce
    <input class="btn" type="button" name="item1" value="$140">

   1 ounce
   <input class="btn" type="button" name="item1" value="$275">

Purple Urkle

   1 gram
    <input class="btn" type="button" name="item1" value="$10">

   1/8 ounce
   <input class="btn" type="button" name="item1" value="$30">

   1/4 ounce
   <input class="btn" type="button" name="item1" value="$70">

   1/2 ounce
   <input class="btn" type="button" name="item1" value="$130">

   1 ounce
   <input class="btn" type="button" name="item1" value="$250">

Blueberry

   1 gram
   <input class="btn" type="button" name="item1" value="$12">

   1/8 ounce
   <input class="btn" type="button" name="item1" value="$35">

   1/4 ounce
   <input class="btn" type="button" name="item1" value="$75">

   1/2 ounce
   <input class="btn" type="button" name="item1" value="$140">

   1 ounce
   <input class="btn" type="button" name="item1" value="$275">

Lucid Blue

   1 gram
   <input class="btn" type="button" name="item1" value="$12">

   1/8 ounce
   <input class="btn" type="button" name="item1" value="$35">

   1/4 ounce
   <input class="btn" type="button" name="item1" value="$75">

   1/2 ounce
   <input class="btn" type="button" name="item1" value="$140">

   1 ounce
   <input class="btn" type="button" name="item1" value="$275">

Strawberry Cough

   1 gram
   <input class="btn" type="button" name="item1" value="$12">

   1/8 ounce
   <input class="btn" type="button" name="item1" value="$35">

   1/4 ounce
   <input class="btn" type="button" name="item1" value="$75">

   1/2 ounce
   <input class="btn" type="button" name="item1" value="$140">

   1 ounce
   <input class="btn" type="button" name="item1" value="$275">

Cactus OG

   1 gram
   <input class="btn" type="button" name="item1" value="$12">

   1/8 ounce
   <input class="btn" type="button" name="item1" value="$35">

   1/4 ounce
   <input class="btn" type="button" name="item1" value="$75">

   1/2 ounce
   <input class="btn" type="button" name="item1" value="$140">

   1 ounce
   <input class="btn" type="button" name="item1" value="$275">

Critical Cure

   1 gram
   <input class="btn" type="button" name="item1" value="$12">

   1/8 ounce
   <input class="btn" type="button" name="item1" value="$35">

   1/4 ounce
   <input class="btn" type="button" name="item1" value="$75">

   1/2 ounce
   <input class="btn" type="button" name="item1" value="$140">

   1 ounce
   <input class="btn" type="button" name="item1" value="$275">

Green Crack

   1 gram
   <input class="btn" type="button" name="item1" value="$16">

   1/8 ounce
   <input class="btn" type="button" name="item1" value="$55">

   1/4 ounce
   <input class="btn" type="button" name="item1" value="$95">

   1/2 ounce
   <input class="btn" type="button" name="item1" value="$185">

   1 ounce
   <input class="btn" type="button" name="item1" value="$350">

A: It is because when your script executes, it doesnot find the element with .btn1 class, because that html element is not created yet.
Use $( document ).ready(), to execute the script, after the document is loaded and ready.
Replace your javascript with below code:
$(document).ready(function(){
    $(".btn1").click(function () {
      var number = $(this).closest("tr").find(".weight1").text();
      alert(number);
    });
});

A: Along with the answer from @jatinder-kumar, your jQuery script tag is not in the  tag.  It is completely outside of your HTML document.  If you want it in the head, you can use his code, if you move it to the bottom, before the close of the  tag, and your other scripts after it, you can avoid using the $(document).ready().


text:
Q: None required PathVariable not working I got the following code:
@GetMapping(value = "/user/{username}/{auth_key}", produces = MediaType.APPLICATION_JSON_VALUE)
public ProfileRequest getUser(final @PathVariable("username") String username,
                              final @PathVariable(value = "auth_key", required = false) UUID authKey) {

and I can't understand why /user/{username} does not handle my request.
Mfg.

A: /user/{username}/{auth_key} and /user/{username} are different URLs. Putting all these URLs to @GetMapping annotation will resolve your problem:
@GetMapping(value = {"/user/{username}/{auth_key}", "/user/{username}/"}, produces = MediaType.APPLICATION_JSON_VALUE)


text:
Q: java.lang.NullPointerException at impl.org.controlsfx.skin.PopOverSkin.lambda$new$68(PopOverSkin.java:255) This error occures when popover of ControlFx is moved. Google doesn't return any result when it is searched.
Anyone knows what is the reason.
Here is the full stack trace of error.
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
    at impl.org.controlsfx.skin.PopOverSkin.lambda$new$68(PopOverSkin.java:255)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$353(GlassViewEventHandler.java:432)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at com.sun.glass.ui.gtk.GtkApplication.lambda$null$48(GtkApplication.java:139)
    at java.lang.Thread.run(Thread.java:748)


text:
Q: Showing $-\int_0^1 {(1-x+\ln x)^2\ln x\over 3(1-x)^3} \, dx=\zeta(3)$
$$I=-\int_0^1 {(1-x+\ln x)^2\ln x \over 3(1-x)^3}\,dx=\zeta(3)\tag1$$

$${1\over 3(1-x)^3}=\sum_{n=0}^\infty {(n+1)(n+2)x^n\over 6}\tag2$$
$$(1-x+\ln x)^2\ln x=\ln x-2x\ln x+x^2\ln x+2\ln^2 x-2x\ln^2 x+\ln^3 x\tag3$$
Sub $(2)$ and $(3)$ into $(1)$ $\rightarrow (5)$
Let $$S=\sum_{n=0}^\infty {(n+1)(n+2)\over 6}\tag4$$
$$I=S\int_0^1 \left(x^n\ln x-2x^{n+1}\ln x+x^{n+2}\ln x+2x^n\ln^2 x -2x^{n+1} \ln x+x^n\ln^3 x\right)\tag5$$
$$\int_0^1 x^n\ln^m x \, dx={(-1)^m m!\over (n+1)^{m+1}}\tag6$$
Using $(6)$ to evaluate $(5)$ $\rightarrow (7)$
$$I=S\left[{-1\over (n+1)^2}+{2\over (n+2)^2}-{2\over (n+3)^2}+{4\over (n+1)^3}-{4\over (n+2)^3}-{6\over (n+1)^4}\right]\tag7$$
(7) seem to be wrong when I checked it with numerical calculation. Anyway this method it is tedious, but that is the only way I know how to solve this integral.
I check quite a numbers of time and can't spotted where I went wrong. Can you help please? Also show us another short approach to tackle integral I.

A: We may compute first
$$ J(k) = \int_{0}^{1}\left(\frac{\log(1-x)}{x}\right)^k\,dx \tag{1}$$
for $k=1,2,3$ by integration by parts and get:
$$ J(1)=-\zeta(2),\qquad J(2)=2\zeta(2),\qquad J(3)=-3\zeta(2)-3\zeta(3) \tag{2}$$
then recognize that the original integral is just

$$ -\frac{J(1) + 2\, J(2) + J(3)}{3}=\color{red}{\zeta(3)}\tag{3}$$

through the substitution $x=1-z$ and the binomial theorem.


text:
Q: Conversion between String and Stanford NLP Word I am trying to do stemming using the Stanford Core NLP's Stemmer class (https://github.com/stanfordnlp/CoreNLP/blob/master/src/edu/stanford/nlp/process/Stemmer.java).
I am trying to call the stemmer method(which I edited a little) from another class as shown below, note that term is a string :
String stemmedterm=CoreNLPKeyPhraseStemmer.keystemming(term);

The main work of stemming in the CoreNLPKeyPhraseStemmer's keystemming method is done by the following line:
String s1= s.stem(token.word());

However, my problem is that the type of token must be Word i.e.edu.stanford.nlp.ling.Word (https://nlp.stanford.edu/nlp/javadoc/javanlp/index.html?edu/stanford/nlp/ling/Word.html) while I am supplying String while calling keystemming from the other class. Is there any way to convert the supplied String to Word?

A: Reading the code for the Word class, it seems to support String in its constructor so I believe you just have to do
Word(token.stem())

To get a word object for the stemmed token.


text:
Q: Batch extract zip to directory This is what I have so far (it is supposed to extract the zip %1 to folder on desktop %2):
@echo off
set from=%1
set to=%2
set tem=C:\Users\%username%\temp_tempExtract
rd /s /q %tem%
mkdir %tem%
xcopy %from% %tem%
rd /s /q %from%
FOR %%F IN (%test_firmware_dir%\*.zip) DO (
 set zip=%%F
 goto cont
)
:cont
jar xf %zip%
del /q %zip%
mkdir C:\Users\%username%\Desktop\%to%
xcopy %temp% C:\Users\%username%\Desktop\%to%
rd /s /q %tem%
cls
cd C:\Users\%username%\Desktop\%to%
dir
@echo on

Any thoughts as to how to make it do what I want? For this I thought I could move the .zip to a temp folder (i.e. create another one there), delete the old.zip, extract the new.zip in the temp folder, delete the new.zip, move all the contents of the temp folder to a folder that the user specifies (on the desktop) and, finally, delete the temp folder and cls/cd to folder-on-desktop/display contents.
It will create the temp file, delete the old.zip and presumable move and delete the new.zip, but it never copies the files to the folder on the desktop, nor does it clear the screen (cls). Though I do believe it displays the contents (dir). It also doesn't delete the temp folder.

A: Here is a commented batch code for what I think you want to do:
Extract a ZIP file specified as first parameter on start of the batch file into a folder on the user's desktop specified as second parameter using jar for extraction.
@echo off
rem Get first parameter - name of ZIP file - without double quotes.
set ZipFileFull=%~1
rem Exit batch file if no parameter was specified at all on running batch file.
if "%ZipFileFull%"=="" goto :EOF
rem Exit batch file if ZIP file does not exist.
if not exist "%ZipFileFull%" goto :EOF
set ZipFileName=%~nx1

rem Get second parameter - name of target folder on desktop - without double quotes.
set TargetFolder=%~2
if "%TargetFolder%"=="" goto :EOF

rem Test if target folder on user's desktop already exists.
if exist "%USERPROFILE%\Desktop\%TargetFolder%" (
   rem Yes, it exists. Delete it with all subfolders.
   rd /s /q "%USERPROFILE%\Desktop\%TargetFolder%"
   if errorlevel 1 goto :EOF
)

rem Create the target folder on user's desktop.
mkdir "%USERPROFILE%\Desktop\%TargetFolder%"

rem Move the ZIP file to the target folder.
move "%ZipFileFull%" "%USERPROFILE%\Desktop\%TargetFolder%"
if errorlevel 1 goto :EOF

rem Set target folder as working directory.
cd /D "%USERPROFILE%\Desktop\%TargetFolder%"

rem Extract the files and folders in the ZIP file to target folder.
rem It would be better to specify jar.exe with full path in double quotes.
jar.exe xf "%ZipFileName%"

rem Delete the ZIP file.
del "%ZipFileName%"


text:
Q: Why are polynomials easier to handle with than integers? This may seems to be an elementary question, but I found no answers on MO nor google.
I have always heard "polynomials are easier to handle with than integers". For example:

*

*When $n$ is quite large, maybe 200 or more, it's relatively easier to factorize a polynomial $f$ of degeree $n$ than to factorize an integer with $n$ bytes.

*When multiplying large integers, we see them as polynomials,use techniques such as FFT,intepolations to multiply polynomials,and then back to integers.
3.The zeta functions of $F[x]$ and $\mathbb{Z}$, and the former are easier to study than the latter.
Of course there are other examples, but because of my shortage of knowledge, I can only lise these above.
So my question is (as in the titile): Why are polynomials easier to handle with than integers? I ask this because contrary to our intuitives, polynomials are "more complex" objects than integers.

A: In the Euclidean division of polynomials, quotient and remainder are uniquely defined, and compatible with addition. This fails for integers.
There is no integer analogue of constant polynomials. I guess that the search for the "field with one element" is in a sense motivated by this.

A: Divisibility of polynomials is a much more rigid property than in integers. Given an integer $n$, another $N$ has a non-zero probability $\frac1n$ to be a multiple of $n$. On the contrary, the probability (no rigour here) that a ``random'' polynomial $P\in{\mathbb C}[X]$ be a multiple of a given one $q$ is zero. For instance, $P$ is a multiple of $X$ iff $P(0)=0$, an event of probability $0$.
If you increase the structure, by either considering multi-variate polynomials, or polynomials with coefficients in $\mathbb Z$, you ``simplify'' even more, in the sense that you have additional criteria for divisibility of primality (Newton's polygon, Eisenstein's criterion, ...), and you have a huge theory (Galois' theory) which you can use and abuse.
Edit. An example of the powerness of polynomials that I like a lot is the following.

Theorem. Let $k$ be a field and $A_0,A_1,B_0,B_1\in M_n(k)$ be given, with $A_0,A_1$ invertible. Let $X$ be an indeterminate. If $XA_0+B_0$ and $XA_1+B_1$ are equivalent in $M_n(k[X])$, the there exist $G,H\in GL_n(k)$ such that $GA_0=A_1H$ and $GB_0=B_1H$.

The case where $A_0=A_1=I_n$ is at the basis of the theory of similarity invariants.

A: How Halloweeny can you get with your questions? The norm on $Z$ is Archimedean and the norm on $F[X]$ is non-Archimedean, and, in general, non-Archimedean maths is easier than Archimedean...

A: Following the commentary by Amri, I think that his idea can be explained in terms of graduations: The natural graduation of $F[X]$ over $F$, generated by the degree, allows us to compute simultaneously a lot of $F$-sums without mixing information. Maybe the rest of facts can be also described by graduation properties? (I'm not taking into account trivial graduations for $Z$).


text:
Q: Drupal 7, Domain Access, and SSO (Single Sign-On) Has anyone made any headway with coming up with a single sign on solution
with Domain access to date for Drupal 7? I've been looking closely at two old
modules, one no longer maintained (SSO for D6) and one still maintained (CAS). I've also read that SAML might be a key to unlocking this, but am uncertain.
Facebook's FBConnect might be another option too or another way could be integrating OpenID from what I've read, and experienced on StackOverflow's sub sites.
I know that OpenID can do this since we are logged into all of *Overflows sub sites at the same time using one login. The question is how does it cross DNS servers? Does it handshake with one half of a matching hash? I cannot find any documentation on this, so am at a loss.
So, are there any solutions that are known to date, or information on what to start
looking into? I think I've made a  good point at the possibilities. I read this thread, Domain Access SSO but am uncertain to what version it pertains to (Drupal. DA, SSO or otherwise). It looks like the "Solution" is to create a master table set with users and permissions, then share those across the domains? How might this work if there are already multiple sites created under Domain Access? Would you clone and rebuild the entire installation, or would you need to start from scratch? It really raises more questions than answers. I contacted the author with no response, so the questions still stand.
Any opinions out there on the who what or why would be greatly appreciated, I just need a start point to get the ball rolling. Thanks everyone.

A: SAML is a good option.  Check this module to integrate  it with drupal:
http://drupal.org/project/simplesamlphp_auth
If you need a demo with this plugin working check this.

A: I'm the author of the Domain Access SSO article mentioned in the original question.  I don't recall being contacted about it, but then again I recently learned that my "contact" page on bleen.net hasn't been working in a while... but anyway, here is a bit of info:
That post referred to Drupal 6, SSO Module 6.x-1.0-rc1, and Domain Access module 6.x-2.0 (I think). That solution basically revolves around creating two separate drupal installs, one the master and one the client (there can be multiple clients). Basically, what happens is the necessary user tables for all teh clients are pointed instead to the master. In doing so, the master becomes (essentially) a shell site that does nothing but hold and verify user data.
Hope that makes sense and/or helps... to be honest i havent looked at that code in a long while now.


text:
Q: How can I add a custom button to Add and Edit posts / pages? What function / hook do I need to use in order to insert a button here, on the Add and Edit post pages?
Thank you very much!

A: the hook you are looking for is media_buttons_context. You could do something like the following:
add_action('media_buttons_context',  'add_my_custom_button');

function add_my_custom_button($context) {

  //path to my icon
  $img = 'penguin.png';

  //our popup's title
  $title = 'An Inline Popup!';

  //append the icon
  $context .= "
      ";

  return $context;
}

Source Here!


text:
Q: Symfony add foreign key object in database I want to upload an Incidencia to the database and when I try to upload it I get the following error:
Notice: Undefined index: $servicioIdservicio

This field is a foreign key that I take from user that in turn is taking it from services is an id so it is an integer field.
Class Incidencia:
use App\Entity\Usuario;
use App\Entity\Servicio;

/**
 * Incidencia
 *
 * @ORM\Table(name="incidencia", indexes={@ORM\Index(name="Usuario_Servicio_idServicio", columns={"Usuario_Servicio_idServicio"}), @ORM\Index(name="IDX_DF7F4B4C95440347", columns={"Usuario_idUsuario"})})
 * @ORM\Entity(repositoryClass="App\Repository\IncidenciaRepository")
 */
class Incidencia
{
    /**
     * @var int
     *
     * @ORM\Column(name="idIncidencia", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $idincidencia;

    /**
     * @var string|null
     *
     * @ORM\Column(name="nombre", type="string", length=128, nullable=true)
     */
    private $nombre;

    /**
     * @var \DateTime|null
     *
     * @ORM\Column(name="fInicio", type="datetime", nullable=true)
     */
    private $finicio;

     /**
     * @var \DateTime|null
     *
     * @ORM\Column(name="fFin", type="datetime", nullable=true)
     */
    private $ffin;

     /**
     * @var string|null
     *
     * @ORM\Column(name="observacion", type="string", length=255, nullable=true)
     */
    private $observacion;

     /**
     * @var string|null
     *
     * @ORM\Column(name="archivo", type="string", length=255, nullable=true)
     */
    private $archivo;

    /**
     * @var \Usuario
     *
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\OneToOne(targetEntity="Usuario")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="Usuario_idUsuario", referencedColumnName="idUsuario")
     * })
     */
    private $usuarioIdusuario;

    /**
     * @var \Usuario
     *
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\OneToOne(targetEntity="Usuario")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="Usuario_Servicio_idServicio", referencedColumnName="Servicio_idServicio")
     * })
     */
    private $usuarioServicioIdservicio;
}

I have also tried to change $userServiceServiceIdservice from Usuario to Servicio and the same error comes up
$inc = new Incidencia();
            $inc->setNombre($data['incidencia']);
            $inc->setFinicio($data['finicio']);
            $inc->setFfin($data['ffin']);
            $inc->setObservacion($data['observacion']);
            if($data['archivo']=!""){
                $inc->setArchivo($data['archivo']);
            }

            $entityManager = $doctrine->getManager();
            $user = $entityManager->getRepository(Usuario::class)->find(5);

            $inc->setUsuarioIdusuario($user);

            $entityManager = $doctrine->getManager();
            $serv = $entityManager->getRepository(Servicio::class)->find(2);

            $inc->setUsuarioServicioIdservicio($user);

            $doctrine->getRepository(Incidencia::class)->addIncidencia($inc);

Method
 /**
 * @throws ORMException
 * @throws OptimisticLockException
 */
public function addIncidencia(Incidencia $entity, bool $flush = true): void
{
    $this->_em->persist($entity);
    if ($flush) {
        $this->_em->flush();
    }
}

How can I fix it?
Thank you very much.


text:
Q: NTLM with Spring OAuth2.0 to access a resource server (REST) I am trying to access some resources (Rest Services) secured with OAuth2.0 from some Java code. We use the Client Credentials OAuth2.0 grant type. The Authorization Server and the Resource Server run inside a Microsoft IIS Server. The access to any resource within the Microsoft IIS Server is extra secured with NTLM authentication/ authorization.
We do the needed steps to obtain the OAuth2.0 token. For this we use the Spring OAuth framework. When Spring makes a request to the authorization server to get a access token (sending the client secret and client id) it cannot go pass the NTLM authorization layer of the IIS. For our request to the authorization server we receive a 401 (unauthorized) response.
Flow:

This is my class:
public class RestTest {

private String tokenUrl = "some.url";

private String clientId = "some.clientId";

private String clientSecret = "some.clientSecret";

public OAuth2RestOperations restTemplate() {
    AccessTokenRequest atr = new DefaultAccessTokenRequest();
    DefaultOAuth2ClientContext defaultOAuth2ClientContext = new DefaultOAuth2ClientContext(atr);
    OAuth2RestTemplate template = new OAuth2RestTemplate(resource(), defaultOAuth2ClientContext);

    return template;
}

protected OAuth2ProtectedResourceDetails resource() {
    ClientCredentialsResourceDetails resource = new ClientCredentialsResourceDetails();
    resource.setAccessTokenUri(tokenUrl);
    resource.setClientId(clientId);
    resource.setClientSecret(clientSecret);
    resource.setClientAuthenticationScheme(AuthenticationScheme.header);
    return resource;
}

public User getUser() {
    ResponseEntity<User> userResponseEntity = restTemplate().getForEntity(baseUrl + "/user", User.class);
    return userResponseEntity.getBody();
}}

Do you have any ideas how should the code look in order to manage to get through NTLM and reach the authorization and then the resource server?


text:
Q: Photo taken from my app, saved in the right folder but can't see in the gallery My photo is saved when i take it but i can't see it in the gallery! I see it with a file manager in the right folder but not in the gallery.
Intent intent = new Intent();
           // Picture from camera
           intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

           Date date = new Date();
           DateFormat df = new SimpleDateFormat("-mm-ss");

           String newPicFile = "Photo"+ df.format(date) + ".jpg";
           String outPath = Environment.getExternalStorageDirectory() + "/DCIM/" + newPicFile;
           File outFile = new File(outPath);

           mCameraFileName = outFile.toString();
           Uri outuri = Uri.fromFile(outFile);
           intent.putExtra(MediaStore.EXTRA_OUTPUT, outuri);

           startActivityForResult(intent, CAPTURE_IMAGE );

I tried everything but nothing works fine!

A: Check that the gallery is refreshed; it doesn't refresh often. You can call a request to refresh using something like this:
((BaseAdapter) yourGalleryView.getAdapter()).notifyDataSetChanged()


text:
Q: How will you deal with "don't know" and "missing data" in survey data? As title, I am thinking of merging both into "missing data", which is to name it as NA in R. Since I don't see it will make much sense (or even any sense), to separate the "don't know" row out and to compare the information with other rows.
Is it OK for me to do so?

A: It depends on the type of question/response in your survey. If they are like "I like", "I dislike", "Don't know", chl answers partially to your question.
The first solution is chl's answer. You have to check if "Don't know" doesn't hide anything. You have to analyse separately these values to see if it highlights a specific profile of respondents.
I'm not about imputation but... "Frenchy" software do it for MCA, ... often considering MAR assumption. It supposes that these answers are randomly distributed (you pick randomly another modality of response).
You can also use a more sophisticated approach : if "Like" is at 30% and "Dislike" at 70% you pick an uniform random number distributed on (0,1) and choose "Like" if your number is at or below 0.3. If you pick a number between 0.3 and 1 you choose "Dislike".
A more modern approach is Multiplie imputation (see MI PROC in SAS and mice package in R). Imputation is very efficient... But it can't recreate atypic profiles...
If you're working in educational testing or if you need to compute a score, let me know I will complete this answer about scores estimation.
Ref:
Multiple Imputation for Nonreponse in survey, Rubin (1987). Wiley.
mice package: http://cran.r-project.org/web/packages/mice/index.html
Survey Methodology, Robert M. Groves, Floyd J. Fowler & al. Wiley.

A: Well, you should also considered that "don't know" is at least some kind of answer, whereas non-response is a purely missing value. Now, we often allow for "don't know" response in survey just to avoid forcing people to provide a response anyway (which might bias the results). For example, in the National Health and Nutrition Examination Survey, they are coded differently but subsequently discarded from the analysis.
You could try analyzing the data both ways: (1) treating "don't know response" as specific response category and handling all responses set with some kind of multivariate data analysis (e.g. multiple correspondence analysis or multiple factor analysis for mixed data, see the FactoMineR package), and (2) if it doesn't bring any evidence of distortion on items distribution, just merge it with missing values.
For (2), I would also suggest you to check that "don't know" and MV are at least missing at random (MAR), or that they are not specific of one respondents group (e.g. male/female, age class, SES, etc.).