text:
Q: start more than one async task on android I want to start 2 async task's, but only one get executed. The output of LogCat should be something like:
firstAsync started
secondAsync started
secondAsync ends
firstAsync ends
end

but the output of LogCat is
firstAsync started
end

it shows that the secondAsync were never been executed.
Here is the java code:
package com.example.async;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.app.Activity;

public class MainActivity extends Activity {

    public boolean stopAsync=false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new firstAsync().execute();
        new secondAsync().execute();
        Log.e("end","end");
    }

    class firstAsync extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            Log.e("firstAsync started","firstAsync started");
            while(!stopAsync)
            {

            }
            Log.e("firstAsync ends","firstAsync ends");
            return null;
        }
    }

    class secondAsync extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            Log.e("secondAsync started","secondAsync started");
            stopAsync = true;
            Log.e("secondAsync ends","secondAsync ends");
            return null;
        }
    }

}

so, the question is, how can I start multiple async task's, hope you can help me.
regards
chris

A: AsyncTasks always execute one at a time, unless you use executeOnExecutor():

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework.
Starting with HONEYCOMB, tasks are executed on a single thread to
  avoid common application errors caused by parallel execution. If you
  truly want parallel execution, you can invoke
  executeOnExecutor(java.util.concurrent.Executor, Object[]) with
  THREAD_POOL_EXECUTOR.

A: This is interesting
In this I put a second async within the first to start on preexecute. The logcat and code shows it best:
My log cat:
12-29 21:53:35.661: E/Async1: being executed
12-29 21:53:35.661: E/Async1: executing
12-29 21:53:35.661: E/Async2: being started
12-29 21:53:35.669: E/Async2: backgrounding
12-29 21:53:35.669: E/Async1: backgrounding
12-29 21:53:35.676: E/Async2: finishing
12-29 21:53:35.676: E/Async1: finishing

For the following code:
@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.e("Async1", "being executed");
    new Async1().execute();
}

public class Async1 extends AsyncTask {

    @Override
    protected void onPreExecute() {
        Log.e("Async1", "executing");
        Log.e("Async2", "being started");
        new Async2().execute();
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Object result) {
        // TODO Auto-generated method stub
        Log.e("Async1", "finishing");
        super.onPostExecute(result);
    }

    @Override
    protected Object doInBackground(Object... arg0) {
        Log.e("Async1", "backgrounding");
        return null;
    }

    public class Async2 extends AsyncTask {

        @Override
        protected void onPostExecute(Object result) {
            Log.e("Async2", "finishing");
            super.onPostExecute(result);
        }

        @Override
        protected Object doInBackground(Object... params) {
            Log.e("Async2", "backgrounding");
            return null;
        }
    }
}

A: on the onPostExecute() method of the first AsyncTask, start the second AsyncTask
protected void onPostExecute(String result) {
    if (result!=null)
    //start the Second asyncTask
    new secondAsync().execute();
}


text:
Q: Should HTTP Verbs Be Used Semantically? If I'm making a web application which integrates with a server-side backend, would it be considered best practice to use HTTP methods semantically? That is, for example, if I'm fetching data (e.g., to populate a menu, etc.), I would use GET, but to update data (e.g., save a record), I would use POST. (I realise there are other methods that may be even more appropriate, but we need to consider browser support.)
I can see the benefits of this in the sense that it's effectively a RESTful API, but at a slightly increased development cost. In my previous projects, I've POST'd everything: Is it worth switching to a RESTful mindset simply for the sake of best practice?

A: My answer is simply: yes.
There are cool advantages also, like you can get stuff directly by accessing URLs from different parts of you application. Than when you post things you are covered and you don't expose stuff.
If you respect the verbs in you classes in whatever programming language you use, it will also help to better structure your code. Classes that are sending data will more naturally separate from those which are receiving or searching for information.

A: Another advantage: Using GET (instead of POST for retrieval style requests) means caching is possible.
Also, a down side that might cause problems: Some proxies have patchy DELETE and PUT method support.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can we show that $\sigma(M_\phi) = \text{ess range} \phi$? Consider $[0,1] $ with $\mu$ Lebsgue measure on $[0,1]$.
Assume  $H = L^2([0,1], \mu)$. Then for $\phi \in L^\infty([0,1],\mu)$, define $M_\phi \in B(L^2([0,1], \mu))$ by $$M_\phi(f) = \phi f, \ f\in L^2([0,1], \mu).$$
How can we show that  $\sigma(M_\phi) = \text{ess range} \  \phi$?

A: A point $z\in\mathbb{C}$ is in the essential range of $\phi$ if, for every $\epsilon > 0$, one has
$$
     \mu \{ x \in [0,1] : |\phi(x)-z| < \epsilon \} > 0.
$$
To show that such a $z$ is in the spectrum of $M_{\phi}$, let
$$
           f_{z,\epsilon} = \chi_{\{ x \in [0,1] : |\phi(x)-z| < \epsilon \}}.
$$
Then, $\|f_{z,\epsilon}\| \ne 0$, and
$$
         \|(M_\phi-zI)f_{z,\epsilon}\|^2 = \int_{\{ x\in [0,1] : |\phi(x)-z|<\epsilon \}}|\phi(x)-z|^2dx \le \epsilon^2\|f_{z,\epsilon}\|^2.
$$
That's enough to show that $M_{\phi}-zI$ cannot have a bounded inverse. So $z\in\sigma(M_{\phi})$ whenever $z$ is in the essential range of $\phi$. If $z$ is not in the essential range, then $M_{\phi}-zI$ does have a bounded inverse given as multiplication by $\frac{1}{\phi(x)-z}$.


text:
Q: Collect list of property of an Array of objects i need a list o string like String PersonName from class Person class. i want to Export List<Person> to List<String> that contains PersonName But i can't use Stream and Collector because my min Api is 21. How can i do this?

A: You don't even need streams for this, a simple imperative approach would be:
List<String> namesAccumulator = new ArrayList<>();
for(Person person : myPeopleList)
     namesAccumulator.add(person.getName());


text:
Q: Node with mongo: findByIdAndUpdate not updating document I am trying to update doc in mongo with node. I am doing that:
var id = data[0]._id;

            var updated = {
                level: mod.level,
                levelName: mod.levelName,
                levelType: mod.levelType,
                map: mod.map,
                waves: mod.waves
            };

            model.findByIdAndUpdate(id, updated, function(err, data){
                if(err){
                    console.log('error');
                    console.log(err);
                    res.send(err);
                } else {
                    console.log('update');
                    console.log(data);
                    res.send({ data: 'Record has been updated' });
                }
            });

The process is going to else clause, i can see 'update' log, then there is a null in next console.log and the change is not reflected in db. Is there any obvious error here? I've read documentations and it seems to be valid but somehow it just don't want to work.
This is my schema:
var Schema = mongo.Schema;

var LevelSchema = new Schema({
    level: { type: String },
    levelName: { type: String },
    levelType: { type: String },
    map: { type: Object },
    waves: { type: Object }
}, { versionKey: false });


text:
Q: What is the JavaScript equivalent of python's .text? Element.text returns the text content of an element.
In a different thread on SO, the python script scrapes data from the followers modal on an Instagram account. The following part returns the text inside the lists and stores them in an array.
 xpath = "//div[@style='position: relative; z-index: 1;']//ul/li/div/div/div/div/a"
 followers_elems = driver.find_elements_by_xpath(xpath)
 return [e.text for e in followers_elems]

I'm trying to achieve a similar result in JavaScript (I'm using WebDriverJS) :
 const XPATH = "/html/body/div[3]/div/div[2]/div/div[2]/ul/div/li";
 var followers_elems = await driver.findElements(By.xpath(XPATH));
 var followers_temp = [];
 for (var e in followers_elems) {
  followers_temp.push(e.textContent); }
 console.log(followers_temp);

I'm not sure if textContent is the right property for .text .
I've tried a million different alternatives but all I'm getting is undefined values in the array :

I'm not very proficient with JS yet, but I'm sure e is reading from followers_elems and if I push just e inside the array it can log the total follower numbers just fine. It is getting the text value from xpath that I'm not understanding. Python does this so elegantly but despite the verbose JavaScript is failing me.
Thank you.

A: WebElement.getText() is the javascript equivalent of getting text element in python when using WebdriverJS.
This should work for you. I have created an async function and easy to understand for loop. Also, since getText() return a promise so i am using async - await to get the text and push it to the followers_temp array.
async function pushTextIn() {
  for (let i = 0; i < followers_elems.length; i++) {
    let text = await followers_elems[i].getText();
    console.log('pushing text: ', text);
    followers_temp.push(text);
  }
  return followers_temp;
}


text:
Q: Submit só executa uma vez $(document).ready(function(){
    //Função que ao clicar no botão, irá fazer.
    $("#logarsist").click(function(){
        var usuario = $("#usera").val();
        var password = $("#pass").val();

        if(usuario == ''){
            $("#formulariousuario").html("Campo Obrigatório*");
            setTimeout(function(){$("#formulariousuario").hide();}, 6000);};

        if(password == ''){
            $("#formulariopassword").html("Campo Obrigatório*");
            setTimeout(function(){$("#formulariopassword").hide();}, 6000);};

        return false;
    });
});

A: Pela descrição que me deu em sua pergunta, o código está sendo executado, porém você esqueceu de exibir novamente as divs que ocultou.
Acredito que isso resolve o seu problema:
$(document).ready(function()
{
    $("#logarsist").click(function()
    {
        var usuario = $("#usera").val();
        var password = $("#pass").val();

        if(usuario == '')
        {
            $("#formulariousuario").html("Campo Obrigatório*");
            $("#formulariousuario").show(); // também pode usar o fadeIn()
            setTimeout(function()
            {
                $("#formulariousuario").hide(); // também pode usar o fadeOut()
            }, 6000);
        };

        if(password == '')
        {
            $("#formulariopassword").html("Campo Obrigatório*");
            $("#formulariopassword").show();

            setTimeout(function()
            {
                $("#formulariopassword").hide();
            }, 6000);
        };

        return false;
    });
});

Com um pouco mais de adaptação no seu código você consegue alguns resultados melhores. Veja:
$(document).ready(function()
{
    var timeout = null;

    $("#logarsist").click(function()
    {
        var usuario = $("#usera").val();
        var password = $("#pass").val();

        if(usuario == '')
        {
            $("#formulariousuario").html("Campo Obrigatório*").show();
        };

        if(password == '')
        {
            $("#formulariopassword").html("Campo Obrigatório*").show();
        };

        // Cancele o timeout para evitar que ele oculte suas divs em momentos inesperados
        clearTimeout(timeout);
        timeout = setTimeout(function()
        {
            // Acrescente a classe "error" nas divs que deseja exibir as mensagens de erro.
            $('.error').hide();

        }, 6000);

        // Você só deve retornar false se o form tiver erros ou for chamar outra função para realizar o envio do formulário.
        return false;
    });
});

Usando um seletor de classes e acrescentando a classe em seu HTML, você evita código desnecessário, e pode ter um tratamento mais unificado.
O JQuery também permite que você combine vários métodos em um único seletor, reduzindo o processamento de buscar novamente o elemento e reduzindo seu código.


text:
Q: PHP email form with attachments not working I'm trying to use a PHP email form I found online that supports attachments, with a bit of extra code, but it's not working, I get a message saying "Sent", but no emails (I checked spam already).
Here is the php file:
function multi_attach_mail($to, $subject, $message, $senderMail, $senderName, $files){

    $from = $senderName." <".$senderMail.">";
    $headers = "From: $from";

    // boundary
    $semi_rand = md5(time());
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

    // headers for attachment
    $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";

    // multipart boundary
    $message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
    "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";

    // preparing attachments
    if(count($files) > 0){
        for($i=0;$i<count($files);$i++){
            if(is_file($files[$i])){
                $message .= "--{$mime_boundary}\n";
                $fp =    @fopen($files[$i],"rb");
                $data =  @fread($fp,filesize($files[$i]));
                @fclose($fp);
                $data = chunk_split(base64_encode($data));
                $message .= "Content-Type: application/octet-stream; name=\"".basename($files[$i])."\"\n" .
                "Content-Description: ".basename($files[$i])."\n" .
                "Content-Disposition: attachment;\n" . " filename=\"".basename($files[$i])."\"; size=".filesize($files[$i]).";\n" .
                "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
            }
        }
    }

    $message .= "--{$mime_boundary}--";
    $returnpath = "-f" . $senderMail;

    //send email
    $mail = @mail($to, $subject, $message, $headers, $returnpath);

    //function return true, if email sent, otherwise return fasle
    if($mail){ return TRUE; } else { return FALSE; }

}

$message = "Customer Contact"
. "\n" . "Name: " . $_POST['fullName']
. "\n" . "Email: " . $_POST['email']
. "\n" . "Phone: " . $_POST['phone']
. "\n" . "Current Phone: " . $_POST['currentPhone']
. "\n" . "Address: " . $_POST['address']
. "\n" . "Retailer: " . $_POST['retailer']
. "\n" . "Product Type: " . $_POST['productType']
. "\n" . "Specific Item: " . $_POST['item']
. "\n" . "Purchase Date: " . $_POST['purchaseDate']
. "\n" . "Invoice Number: " . $_POST['invoiceNumber']
. "\n" . "Issue: " . $_POST['issue']
. "\n" . "How did the issue happen?: " . $_POST['how']
. "\n" . "When did the issue occur?: " . $_POST['when']
. "\n" . "Have you done anything to try correcting the issue?: " . $_POST['customerTry'];

$to = 'someEmail@gmail.com';
$from = $_POST['email'];
$from_name = $_POST['fullName'];

//attachment files path array
$files = $_FILES['files'];
$subject = 'Customer Contact From Service Form';
$html_content = $message;

//call multi_attach_mail() function and pass the required arguments
$send_email = multi_attach_mail($to,$subject,$html_content,$from,$from_name,$files);

//print message after email sent
echo $send_email?"
 Mail Sent

".$message:"
 Mail not SEND
";

My form looks like this:
<form NOVALIDATE action="processContact.php" enctype="multipart/form-data" id="claimsForm" method="post" name="claimsForm">
  ..lots of fields...

    Photos:
    <input type="file" id="files[]" name="files[]" multiple="multiple" />

    <input class="green-btn" id="ss-submit" name="submit" type="submit" value="Submit">
</form>

The function came with the form I downloaded, so I don't think there is a problem with it. I've been playing around with the code and trying different things, but no luck (I'm not a PHP guy).
EDIT:
Based on the suggestion below, I tried using phpMailer, following the example they have, here is my php file now:
/**
 * PHPMailer simple file upload and send example
 */
$msg = '';

$message = "Customer Contact"
. "\n" . "Name: " . $_POST['fullName']
. "\n" . "Email: " . $_POST['email']
. "\n" . "Phone: " . $_POST['phone']
. "\n" . "Current Phone: " . $_POST['currentPhone']
. "\n" . "Address: " . $_POST['address']
. "\n" . "Retailer: " . $_POST['retailer']
. "\n" . "Product Type: " . $_POST['productType']
. "\n" . "Specific Item: " . $_POST['item']
. "\n" . "Purchase Date: " . $_POST['purchaseDate']
. "\n" . "Invoice Number: " . $_POST['invoiceNumber']
. "\n" . "Issue: " . $_POST['issue']
. "\n" . "How did the issue happen?: " . $_POST['how']
. "\n" . "When did the issue occur?: " . $_POST['when']
. "\n" . "Have you done anything to try correcting the issue?: " . $_POST['customerTry'];

$to = 'murtorius@gmail.com';
$from = $_POST['email'];
$from_name = $_POST['fullName'];

//attachment files path array
$files = $_FILES['userfile'];
$subject = 'Customer Contact From Service Form';

if (array_key_exists('userfile', $_FILES)) {
    // First handle the upload
    // Don't trust provided filename - same goes for MIME types
    // See http://php.net/manual/en/features.file-upload.php#114004 for more thorough upload validation
    $uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['userfile']['name']));
    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
        // Upload handled successfully
        // Now create a message
        // This should be somewhere in your include_path
        require 'php-mailer/PHPMailerAutoload.php';
        $mail = new PHPMailer;
        $mail->setFrom($from, $from_name);
        $mail->addAddress($to, 'TEST');
        $mail->Subject = $subject;
        $mail->msgHTML($message);
        // Attach the uploaded file
        $mail->addAttachment($uploadfile, 'Photos');
        if (!$mail->send()) {
            $msg .= "Mailer Error: " . $mail->ErrorInfo;
        } else {
            $msg .= "Message sent!";
        }
    } else {
        $msg .= 'Failed to move file to ' . $uploadfile;
    }
}

I changed the input file field name to 'userfile[]', but I get this:
Warning: sha1() expects parameter 1 to be string, array given in /home/zucora/service.zucora.com/processContact.php on line 35

Warning: move_uploaded_file() expects parameter 1 to be string, array given in /home/zucora/service.zucora.com/processContact.php on line 36

If I change the name to 'userfile' (without []) I get a blank screen and no email.


text:
Q: Canon Pixma MG8200 Printer Drivers on 18.04 I have a Canon Pixma MG8200 printer- are there drivers for 18.04 LTS? There were drivers for older versions of Ubuntu ~12 or so. The usual "Add Printer" route can't find drivers.

A: I don't know where to find the Linux drivers for Canon printers. The official Canon site doesn't even have a Linux driver for my printer. Luckily, the Gutenprint driver works well for Canon printers. You can install it as follows:
sudo apt install printer-driver-gutenprint

Then, connect your printer via USB to the computer, and go to Settings > Printers (Pic 1). If you don't see your printer there, add it. If you see the printer, click on the gear icon next to it, and select printer details. On the new window that opens up (Pic 2), select Select from database..., and fin your printer model under the Canon drivers (Pic 3). Once you save that, your printer should work :)
I tested this solution both in Ubuntu 18.04 and 20.04 using a Canon PIXMA MP470 series printer, and I could see an entry for the Canon PIXMA MG8200 series printer too (see Pic 3).

A: use the Canon drivers; so go here https://www.canon-europe.com/support/consumer_products/products/fax__multifunctionals/inkjet/pixma_mg_series/pixma_mg8240.aspx?type=drivers&driverdetailid=tcm:13-866172&os=Linux%20(64-bit)&language=EN and click to download the debian package there; it will come down as cnijfilter-mg8200series-3.60-1-deb.tar.gz. Your printer has lasted well: 7yrs old
open a terminal; copy each line of command below; paste it into the terminal; hit the ENTER key after each paste
cd Downloads

tar -zxvf cnijfilter-mg8200series-3.60-1-deb.tar.gz

cd cnijfilter-mg8200series-3.60-1-deb

sudo ./install.sh

the last command is the install script; watch as it runs as it will ask you questions; we hope all goes well


text:
Q: Theory of integration of Kernel in çinlar probability and stochastic I'm reading the probabilistic book write by çinlar, but I don't understand the Kernel theory, in details:
$ (E,\mathcal{E}),(F,\mathcal{F})$ are two measurable space
$$K:E \times \mathcal{F} \rightarrow R_{+}$$
with these proprieties: they are measurable on $E$ fixed $B\in\mathcal{F}$, and they are a measure on $F$ fixed $x\in E$. After this definitio the book present the following operation between Kernels and functions:
$$Kf(x)=\int_{F}K(x,dy)f(y)$$
But what does $K(x,dy)$ mean? in the theory of measure i haven't see nothing simalar, how one can calculate this integrals with the strange $dy$ (that I think means lebesgue measure)?

A: I've resolved! since the kernel is a measure fixed $x$ I can integrate the function $f$ respect to this measure (notation $\nu(dx)$ means integrate respet to measure $\nu$ and variables $x$)!


text:
Q: Integration in R giving "non-finite function value" integral <- function(x) {2.393794315*((3320)*(x/2.24581)^5+(-1613880/11)*(x/2.24581)^4+(171163181/66)*(x/2.24581)^3+(-7563546913/330)*(x/2.24581)^2+(835541173981/8250)*(x/2.24581)+(-2953570085669/16500))*(((483793.161846485)*x^8+(-76823340.9717028)*x^7+(5337025908.822)*x^6+(-211866341077.587)*x^5+(5256530719898.47)*x^4+(-83466263852549.1)*x^3+(828318375700455)*x^2+(-4697211251008830)*x+(11653475160809900))^0.5)}

integrate(integral, lower=19.538547, upper=20.3245805)

This gave me

Error in integrate(integral, lower = 19.538547, upper = 20.3245805) :
    non-finite function value

I am not sure what to do. It'd be great if somebody could input the integral into a software like Maple to see if it works - or, giving an answer to how to get around this error would be great, too :P
Thanks in advance!
EDIT:
The function that I am trying to revolve around the x-axis is:
y=2.393794315*((3320)(x/2.24581)^5+(-1613880/11)(x/2.24581)^4+(171163181/66)(x/2.24581)^3+(-7563546913/330)(x/2.24581)^2+(835541173981/8250)*(x/2.24581)+(-2953570085669/16500))
When plotted with limits {19.538547 < x < 20.3245805}:

As in the link provided by @StephenWade (in the comments), to find the surface area, I needed (f'(x))^2 + 1. Using Wolfram, Alpha, I computed this to be:
(f'(x))^2 + 1 = (483793.161846485)*x^8+(-76823340.9717028)*x^7+(5337025908.822)*x^6+(-211866341077.587)*x^5+(5256530719898.47)*x^4+(-83466263852549.1)*x^3+(828318375700455)*x^2+(-4697211251008830)*x+(11653475160809900)
Plotting this, without limits, gives:

However, computing this on R, I got an error:

My input into R was the following:
2.393794315*((3320)(x/2.24581)^5+(-1613880/11)(x/2.24581)^4+(171163181/66)(x/2.24581)^3+(-7563546913/330)(x/2.24581)^2+(835541173981/8250)(x/2.24581)+(-2953570085669/16500))(((483793.161846485)*x^8+(-76823340.9717028)*x^7+(5337025908.822)*x^6+(-211866341077.587)*x^5+(5256530719898.47)*x^4+(-83466263852549.1)*x^3+(828318375700455)*x^2+(-4697211251008830)*x+(11653475160809900))^0.5)
I just need a reasonable estimate of the surface area...Any ideas?

A: I would approach it using the polynom package, which can calculate the derivative for us, and then apply the formula from Wolfram.
revol_coef <- 2.393794315 * c(-2953570085669 / 16500,
                              835541173981 / (8250 * 2.24581),
                              -7563546913/ (330 * 2.24581^2),
                              171163181 / (66 * 2.24581^3),
                              -1613880 / (11 * 2.24581^4),
                              3320 / 2.24581^5)
y <- polynomial(revol_coef)
y_d <- deriv(y)

f <- function(x) {
    2 * pi * predict(y, x) * sqrt(1 + predict(y_d, x)^2)
}

integrate(f, lower = 19.538547, upper = 20.3245805)

The output I get is
-45.71118 with absolute error < 0.0017

The answer is negative, due to the surface being specified in the lower-right quadrant of the x-y plane (as per your plot). To fix this, take the negative of the number supplied to get a surface area.
Translating formulas from Wolfram Alpha, manipulating them, and then putting them into R can easily involve making a mistake.
In this case, I would recommend doing as much of the work within R, as the tools/functions to do the necessary calculations and simplifications are readily available.


text:
Q: Issue with PnP PowerShell code syntax error I have a function that iterates through a document library and creates a report that lists the metadata associated with each item.
It won't compile.  At the function declaration at the first bracket, I'm getting an error:
Missing closing '}' in statement block or type definition

I have identified the lines of code that seem to be the source of the error.  When I cut the code on the lines between # the error goes away.
I can't figure where the syntax is incorrect.  I'm using:

SharePointPnPPowerShell2013   3.11.1907.0

function PopulateData($web, $incldeFileSize) {
        Write-Host "Current Site " $web.url -ForegroundColor Cyan
                  $libs = Get-PnPList -Web $web | Where{($_.BaseType -eq "DocumentLibrary") -or ($_.Title -eq "Pages") }

                  foreach($lib in $libs){
                     $libitems = (Get-PnPListItem -Web $web -List $lib -Fields "FileLeafRef","Name","Title","Author","Modified","Created","KBAbstract","KBContentAuthor","KBCategory","Publish","KBPublishDate").FieldValues

                       foreach($libitem in $libitems)
                         {
                             if($libitem.FSObjType -eq "0"){
                              $data = @{
                                          "Web Name" = $web.Title
                                          "Library Name" = $lib.Title
                                          "File Name" = $libitem.FileLeafRef
                                          "Abstract" = $libitem.KBAbstract
                                          "Content Author" = $libitem.KBContentAuthor.Email

                                          ############The Problem is somewhere in these Lines of code###########
                                          [Microsoft.SharePoint.Taxonomy.TaxonomyFieldValueCollection]$MMSFieldValueColl = $libitem.KBCategory
                                            $MMSFieldTerms = ""
                                            Foreach($MMSFieldValue in $MMSFieldValueColl)
                                            {
                                                if($MMSFieldValue.label -ne $null)
                                                {
                                                    $MMSFieldTerms+=$MMSFieldValue.label+"; "
                                                }
                                            }
                                            write-host $MMSFieldTerms
                                            ##########The Problem ends here############

                                          "Knowledge Area" = $libitem.KBCategory
                                          "Publish" = $libitem.Publish
                                          "Published Date" = $libitem.KBPublishedDate.LookupValue
                                          "File URL" = $libitem.FileRef
                                          "Modified Date" = $libitem.Modified
                                          "Created By" = $libitem.Author.LookupValue
                                          "Created Date" = $libitem.Created
                                          "Modified By" = $libitem.Editor.LookupValue
                                          "File Size (KB)" = $null
                                     }
                             if($incldeFileSize -eq $true){
                                    $file = Get-PnPFile -Url $libitem.FileRef
                                    $data["File Size (KB)"] = $file.Length / 1KB
                              }
                              New-Object PSObject -Property $data
                            }
                         }
                  }
}

A: You should move the whole block
############The Problem is somewhere in these Lines of code###########
[Microsoft.SharePoint.Taxonomy.TaxonomyFieldValueCollection]$MMSFieldValueColl = $libitem.KBCategory
$MMSFieldTerms = ""
Foreach($MMSFieldValue in $MMSFieldValueColl) {
    if($MMSFieldValue.label -ne $null) {
        $MMSFieldTerms+=$MMSFieldValue.label+"; "
    }
}
write-host $MMSFieldTerms
##########The Problem ends here############

outside of the hashtable definition of $data. In there, only name-value pairs are expected.
I'd move if higher up, just below if($libitem.FSObjType -eq "0"){ and before $data = @{, so you could add it to the hashtable if you want as property
"Field Terms" = $MMSFieldTerms -join ';'

Sidenote 1: instead of using string concatenation, why not build the $MMSFieldTerms as array and join the elements with ';' afterwards like:
[Microsoft.SharePoint.Taxonomy.TaxonomyFieldValueCollection]$MMSFieldValueColl = $libitem.KBCategory
$MMSFieldTerms = foreach($MMSFieldValue in $MMSFieldValueColl) {
    if($MMSFieldValue.label) {
        $MMSFieldValue.label
    }
}

write-host ($MMSFieldTerms -join ';')

Sidenote 2: it is best to replace all curly 'smart-quotes' by straight ones: "DocumentLibrary" --> "DocumentLibrary"

A: I don't have SharePoint to execute the code and test. The only thing I can spot is your Foreach is not being set to a property. Since you are using $data to try and build an hashtable the collection you are joining needs to be set into a key/value pair.
So this:
                    ############The Problem is somewhere in these Lines of code###########
                    [Microsoft.SharePoint.Taxonomy.TaxonomyFieldValueCollection]$MMSFieldValueColl = $libitem.KBCategory
                    $MMSFieldTerms = ""
                    Foreach($MMSFieldValue in $MMSFieldValueColl) {
                        if($MMSFieldValue.label -ne $null) {
                            $MMSFieldTerms+=$MMSFieldValue.label+"; "
                        }
                    }
                    write-host $MMSFieldTerms
                    ##########The Problem ends here############

Should be something like this: (added **** around it to show the difference only)
            ############The Problem is somewhere in these Lines of code###########
            [Microsoft.SharePoint.Taxonomy.TaxonomyFieldValueCollection]$MMSFieldValueColl = $libitem.KBCategory
            $MMSFieldTerms = ""
            "****Some Property****" = Foreach($MMSFieldValue in $MMSFieldValueColl) {
                if($MMSFieldValue.label -ne $null) {
                    $MMSFieldTerms+=$MMSFieldValue.label+"; "
                }
            }
            write-host $MMSFieldTerms
            ##########The Problem ends here############


text:
Q: How can I draw a single svg path with variable width stroking? How can I draw this shape using a single svg path?

A: You can do it with a single path, but currently there's no such thing as variable width stroke. Instead, such a shape can be drawn using fill on a path criss-crossing itself:

#hide-stroke:checked ~ svg path {
  stroke: none;
}

svg {
  display: block;
}
<input id="hide-stroke" type="checkbox" />
<label for="hide-stroke">Hide stroke</label>

<svg xmlns="http://www.w3.org/2000/svg" width="600" height="300" viewBox="0,0 200,100" >
   <path d="M20,80  q26,-100 53,-25  q26,75 53,0  q26,-90 53,0  q-26,-70 -45,-10  q-26,80 -70,0  q-25,-40 -37,0"
         fill="black" stroke-width="1" stroke="limegreen" />
</svg>


text:
Q: SQL create a computed column from another column I'm trying to create a computed column where the value comes from another table. The table must be stored in the database.
Existing Table named TABLE 1
ID  GROUP ITEM_NO COST_A COST_B
1   1     1001    20.00  30.00
2   1     1002    10.00  25.00
3   2     1005    15.00  25.00

In the new table named Table 2, I wish to have the following.
Essentially the GROUP_TOTALCOST is the COST_A plus COST_B for each group
Code GROUP(FK) GROUP_TOTALCOST
001  1         85.00
002  2         40.00

Is this something I can achieve in an ALTER TABLE ADD COLUMN or CREATE TABLE statement?
Thanks

A: Create a View to get values calculated on the fly:
CREATE VIEW <NAME> AS
SELECT [GROUP],SUM(COST_A + COST_B) FROM TABLE1 GROUP BY [GROUP]

Alternatively persist the result in a table - but you will have to re-create it if your original table changes:
CREATE TABLE <NAME> AS
SELECT [GROUP],SUM(COST_A+COST_B) FROM TABLE1 GROUP BY [GROUP]

In both cases you will use SELECT * FROM <NAME> to get your data.

A: you cannot have a computed column based on another table, you can make a view and whenever you select from view It's up to date
here is the syntax you might want to consider if you are using sql server
create view yourviewname
as
select
ROW_NUMBER() over (order by GROUP) as rownumber ,  GROUP, sum(Cost_A) + sum( COst_B) as GROUP_TOTALCOST
from testx
group by GROUP


text:
Q: Size of the Set in vueJs I have a set and I want to get the size of this set in VueJS and I am going to use it for the page navigation.My problem is I cannot use size to find the size of the object.
export default {
    data() {
        return {
            numberOfPages: this.weeks.size,
            weeks: new Set(),
            tickets: [
                {
                    id: 0,
                    time: "09:45",
                    date: new Date(),
                    name: "Swimming in the hillside pond",
                },
                {
                    id: 1,
                    time: "09:45",
                    date: new Date(),
                    name: "Swimming in the hillside pond",
                },
            ],
        };
    },
    methods: {
        currentNumberOfWeek(tickets) {
            tickets.forEach(ticket => {
                let result = this.getWeekNumber(ticket.date);
                this.weeks.add(result)
            });
            this.sortSet(this.weeks);
            console.log(this.weeks);
        },
        getWeekNumber(date) {
            const oneJan = new Date(date.getFullYear(), 0, 1);
            const numberOfDays = Math.floor((date - oneJan) / (24 * 60 * 60 * 1000));
            let weekNumber = Math.ceil((date.getDay() + 1 + numberOfDays) / 7);
            return weekNumber;
        },
        sortSet(set) {
            const entries = [];
            for (const member of set) {
                entries.push(member);
            }
            set.clear();
            for (const entry of entries.sort()) {
                set.add(entry);
            }
            return set;
        },
    },
};

I am getting "TypeError: Cannot read property 'size' of undefined" and I dont know why I am getting it.

A: I think the best way to handle this is to use a computed property.
var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!',
        weeks: new Set()
    },
    computed: {
        weeksSize(){
            return this.weeks.size
        }
    }
});

Then you can use your "weeksSize" also in your methods with "this.weeksSize".
Check the documentation for computed property for more informations.

A: You need a computed property in this case.
{
  data(){return {weeks: new Set()}},
  computed:{numberOfPages:()=>this.weeks.size}
}

https://v3.vuejs.org/guide/computed.html#computed-properties


text:
Q: How to skip the column header in the output csv file when using CSVWRITE in h2? I am migrating to h2.
And I have a problem when exporting data to csv files.
Due to all the csv files should be without column header.
But h2 CSVWrite function will add the column header in the csv file.
Is that possible to add one csvoption to skip outputting the column header?
It seems it doesn't have it now.

A: Unfortunately, this feature is currently not supported in the CSVWRITE function. It will be supported in the next release (support is already committed in the H2 trunk, but will have to be go though the regular test and release cycle first; this will take about one or two weeks).


text:
Q: GoLang : Passing buildFlags with double quotes in launch.json of visual studio code I would like to pass something with quotes as buildFlags in My launch.json.
currently this is what I am trying to do
"buildFlags": "-ldflags \"-w -X xxxxxxx\"",

However using the escape character gives me the error
invalid value "\"-w" for flag -ldflags: missing =<value> in <pattern>=<value>
usage: go build [-o output] [build flags] [packages]
Run 'go help build' for details. (exit status 2)

Any suggestions on how I can resolve this issue ?

A: Per this issue launch.json buildFlags for multiple tags, the following config should work
"buildFlags": "-ldflags '-w -X'"

For more information, please refer to this doc VS Code debugging


text:
Q: Not hitting with Web API two different GET methods Implemented webapi routing and having two different route methods for for retrieving values but it is differentiated by supplying parameter type.
Api methods are getting hit for the corresponding action methods if we simply specify "apiurl/api/contact/search/sri" and "apiurl/api/contact/get/2" in direct browser url.
But when comes to communicate with angular to webapi, api is not getting hit.

//angular service

contact.search = function (inputName) {
            return $http({
                method: 'GET',
                url: url + 'api/contact/search',
                //params: { name: inputName }
                data: { name: inputName }
            });
            //return $http.get(url + 'api/contact/search', name);
        }

//WebAPI

        [HttpGet]
        [Route("search/{name:alpha}")]
        public IHttpActionResult GetContacts([FromBody]string name)
        {
            repository = new ContactRepository();
            if (string.IsNullOrEmpty(name))
            {
                var message = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent("Search Name can not be empty")
                };
                throw new HttpResponseException(message);
            }
            return Ok(repository.GetContact(name));
        }

        // GET api/contact/5
        [HttpGet]
        [Route("get/{id:int}")]
        public IHttpActionResult Get(int id)
        {
            repository = new ContactRepository();
            if (id == 0)
            {
                var message = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent("Issue with Passed Id Parameter.") };
                throw new HttpResponseException(message);
            }
            return Ok(repository.GetContact(id));
        }

A: When you use data: { name: inputName }, it is appended to the url in the following way:
...api/contact/search?name=inputName

but what you want is this:
...api/contact/search/inputName

So, you have two options.
Either change your angular code:
return $http({
     method: 'GET',
     url: url + 'api/contact/search/' + inputName,
});

or change your API to accept QUERY params.
Hope it helps


text:
Q: non-static method compute(int) cannot be referenced from a static context The code given below is giving the following error:- non-static method compute(int) cannot be referenced from a static context
If i cannot create a method inside main(), what should i do.
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
    Scanner key = new Scanner(System.in);
    int t = key.nextInt();
    for(int i=0;i<t;i++){
        int a = key.nextInt();
        int b = key.nextInt();
        a=compute(a);
        b=compute(b);
        System.out.println(a+b);
    }
}
int compute(int a){
    int basea=0, digit;
    int temp=a;
    while(temp>0){
        digit = temp%10;
        temp/=10;
        if(digit>(basea-1))basea=digit+1;
    }
    temp=a;
    a=0;
    int count=0;
    while(temp>0){
        digit = temp%10;
        temp/=10;
        a+=digit*Math.pow(basea,count);
        count++;
    }
    return a;
}

A: You have two options:

*

*Declare compute() static:
static int compute(int a){

*Create an instance of IdeOne and call compute() via that reference:
IdeOne ideOne = new IdeOne();
a = ideOne.compute(a);

I think it would be a good idea to read through the Java tutorials on classes and objects.

A: You're trying to call a non-static method (which is compute) from a static method (the main).
Change int compute(int a){ with static int compute(int a){

A: In your case make method compute static. Otherwise create an Ideone object and call your method on it.

A: You can not access non-static method from static method.
Method you are trying access is instance level method, you can not access instance method/variable without class instance.
You can't access something that doesn't exist. By default non-static method doesn't exist yet, until you create object of that class in which method exist. A static method always exists.
You can access your method by following way :
1. Make your compute() method static
 int compute(int a){
  ///rest of your code
 }

2. Create instance of your class Ideone and access method by class object.
IdeOne obj = new IdeOne();
obj.compute(a);
obj.compute(b);

A: The answers given here are mainly to make the method static, which is fine for a program this size. However, as projects get bigger not everything will be in your main anymore, and thus you get this static/non-static issue on a larger scale as your other classes won't be static.
The solution then becomes to make a class for your Main, as such:
public class Main {

public static void main( String[] args ) {

Ideone ideone = new Ideone();

Then another file which houses your class Ideone:
public class Ideone {

 Scanner key;

 public Ideone() {

    key = new Scanner(System.in);
    int t = key.nextInt();
    for(int i=0;i<t;i++){
        int a = key.nextInt();
        int b = key.nextInt();
        a=compute(a);
        b=compute(b);
        System.out.println(a+b);

   } // end constructor

    int compute(int a){
       int basea=0, digit;
       int temp=a;
       while(temp>0){
         digit = temp%10;
         temp/=10;
         if(digit>(basea-1))basea=digit+1;
    }
    temp=a;
    a=0;
    int count=0;
    while(temp>0){
        digit = temp%10;
        temp/=10;
        a+=digit*Math.pow(basea,count);
        count++;
    }
    return a;
   } // end compute

} // end class

As for your main file. What I do will work, but better practice is to follow the code example given here:
http://docs.oracle.com/javase/tutorial/uiswing/painting/step1.html
Applying this practice will ensure that you do not have static/non-static issues anywhere in your project, as the only thing that is static is the initialization of your actual code, which then handles all codes / further initilization of other classes (which is all non-static)


text:
Q: Download queue in Android What's the best way to implement a download queue in Android?
I suspect there might be some platform classes that might do most of the work.

A: I would suggest looking at the java.util.concurrent package and more specifically read up on Executors
You can create an ExecutorService which would only run 'n' number of Runnable objects at a time and would automatically queue up the rest of the tasks. Once one of the threads being executed finishes execution it picks up the next Runnable object in queue for execution.

A: Using an IntentService will make it quite difficult to support cancellation. It's just something you need to be aware of. If you can, it's API Level 9, you will be better of using http://developer.android.com/reference/android/app/DownloadManager.html

A:
What's the best way to implement a download queue in Android?

Use an IntentService. It supplies the queue and the background thread for you, so all you have to do is put your download logic in onHandleIntent(). See here for a sample project demonstrating this.

A: From API 11 up, a good approach is to use a FixedThreadPool with async tasks. Do once:
ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(3);

Where 3 is the number of downloads you want to run at the same time. It will queueu the task if there are already 3 downloads running, and automatically handle the task later.
Launch your async tasks with:
yourAsynTask.executeOnExecutor(threadPoolExecutor, params);

Params is probably the url you wish to connect to. You can read it out in the onPostExecute of your asynctask, and connect to the server using a HttpURLConnection.
Make sure you call down this on shutdown:
threadPoolExecutor.shutdown()


text:
Q: github1s access request provides public access to private repos? Apologies if this is the wrong place to post this question? I want to visualize my private repo on browser with github1s. When I add the corresponding 1s to the https address to view it asks me for authentication token:

then I'm'asked to provide conwnet access to my private and public repos. If I do does that give everyone access to the private repos?

Expanding Repositories Public and private says:
This application will be able to read and write all public and private repository data. This includes the following:
Code
Issues
Pull requests
Wikis
Settings
Webhooks and services
Deploy keys
Collaboration invites
Learn More


text:
Q: sub query in laravel where clause I want to get write sub query in where clause as in mysql.Is it possible to use sub query in where clause in laravel
SELECT
    p.*, d.name, d2.name, d2.head, u.id, u.aceid, u.firstname
FROM project as p
left join department as d
    on p.department_string_id = d.string_id
left join department as d2
    on d.parent_department_string_id = d2.string_id
LEFT join users as u
    on d2.head_aceid = u.aceid
where p.code in
(select ar.project_code from asset_request as ar
 where ar.request_id= '1718AM0010')

In laravel I have tried as
DB::table('project as p')
                ->leftJoin('department as d','p.department_string_id','=','d.string_id')
                ->leftJoin('department as d2','d.parent_department_string_id','=','d2.string_id')
                ->leftJoin('users as u','d2.head_aceid','=','u.aceid')
                ->where('p.code','=','USA_0057_07')  //instead of code need to use subquery
                ->select('u.id')
                ->first();

A: DB::table('project as p')
    ->leftJoin('department as d','p.department_string_id','=','d.string_id')
    ->leftJoin('department as d2','d.parent_department_string_id','=','d2.string_id')
    ->leftJoin('users as u','d2.head_aceid','=','u.aceid')
    ->whereRaw("p.code in (select ar.project_code from asset_request as ar where ar.request_id= '1718AM0010')")
    ->select('u.id')
    ->first();

A: I think you can refactor your query to replace the subquery in the WHERE clause with another join:
SELECT
    p.*, d.name, d2.name, d2.head, u.id, u.aceid, u.firstname
FROM project as p
LEFT JOIN department as d
    ON p.department_string_id = d.string_id
LEFT JOIN department as d2
    ON d.parent_department_string_id = d2.string_id
LEFT JOIN users as u
    ON d2.head_aceid = u.aceid
INNER JOIN asset_request ar
    ON p.code = ar.project_code
WHERE
    ar.request_id = '1718AM0010'

Laravel code:
DB::table('project as p')
            ->leftJoin('department as d','p.department_string_id', '=', 'd.string_id')
            ->leftJoin('department as d2', 'd.parent_department_string_id', '=', 'd2.string_id')
            ->leftJoin('users as u', 'd2.head_aceid', '=', 'u.aceid')
            ->join('asset_request as ar', 'ar.project_code', '=', 'p.code')
            ->where('ar.request_id', '=', '1718AM0010')
            ->select('u.id')
            ->first();


text:
Q: asp.net extending IPrincipal I would like to extend IPrincipal in asp.net to allow me to get the usertype that I will define. I would like to make it possible to do this in a controller
string type = User.UserType

then in my extension method i will have a method like
public string UserType()
{
  // do some database access
  return userType

}

how can I do this? is it possible?
Thanks!

A: Sure. Make your class implements IPrincipal:
public class MyPrinciple : IPrincipal {
    // do whatever
}

Extension method:
public static string UserType(this MyPrinciple principle) {
    // do something
}

A: Here is an example custom class that implements IPrincipal.  This class includes a few extra methods to check for role affiliation but shows a property named UserType per your requirements.
  public class UserPrincipal : IPrincipal
  {
    private IIdentity _identity;
    private string[] _roles;

    private string _usertype = string.Empty;

    public UserPrincipal(IIdentity identity, string[] roles)
    {
      _identity = identity;
      _roles = new string[roles.Length];
      roles.CopyTo(_roles, 0);
      Array.Sort(_roles);
    }

    public IIdentity Identity
    {
      get
      {
        return _identity;
      }
    }

    public bool IsInRole(string role)
    {
      return Array.BinarySearch(_roles, role) >= 0 ? true : false;
    }

    public bool IsInAllRoles(params string[] roles)
    {
      foreach (string searchrole in roles)
      {
        if (Array.BinarySearch(_roles, searchrole) < 0)
        {
          return false;
        }
      }
      return true;
    }

    public bool IsInAnyRoles(params string[] roles)
    {
      foreach (string searchrole in roles)
      {
        if (Array.BinarySearch(_roles, searchrole) > 0)
        {
          return true;
        }
      }
      return false;
    }

    public string UserType
    {
      get
      {
        return _usertype;
      }
      set
      {
        _usertype = value;
      }
    }

  }

Enjoy!

A: Basically, no.  You can implement IPrincipal with a class such as MyPrincipal, and that class can have a UserType property, but you'd have to access the instance through a reference of its own type in order to reach it, not through the interface reference.
edit
An extension method could work, but only if you're absolutely certain you'll never call it on something that implements IPrincipal but isn't an instance of your own class.

A: You can make an extension method:
public static string UserType(this IPrincipal principal) {
    // do some database access
    return something;
}


text:
Q: Extrema of multivalued function with constraint This is not supposed to be a 'how-to-do' question, but rather a 'why' question. I came across the following problem:
$Let\ f: R^2 \rightarrow R;\ \ f(x,y)=x^3+y^3.\ Find\  the\ extrema\  points\ of\ f\ so\ that\ x^2+y^2=1$
The solution for the minimum works in the same way as that for finding the maximum, so I'll just consider the maximum when explaining my approach. I took the Lagrange function, made its partial derivatives equal to $0,\ $ found $\ \lambda\ $ so that $g(x,y)=x^2+y^2-1=0\ $ which resulted in some possible solutions. What I find strange is when checking the solution of this problem $(\frac{\sqrt{2}}{2},\frac{\sqrt{2}}{2})\ $ I found given as a maximum point, whereas $(1,0)$ (and, of course, $(0,1))\ $ clearly yields a greater $\ f$ while also verifying $g(x,y)=0$ and all the partial differential tests for $\ \lambda=-\frac{3}{2}$. Still, $(\frac{\sqrt{2}}{2},\frac{\sqrt{2}}{2})\ $ passes the Hessian test while $(1,0)$ doesn't, but this just leaves the Hessian inconclusive for $(1,0)$, which shouldn't be a problem.
So which is the maximum of $\ f$ on $\ x^2+y^2=1?$ $$(1,0)\ and\ (0,1)\ or\
 (\frac{\sqrt{2}}{2},\frac{\sqrt{2}}{2})?$$

A: with $$y=\pm\sqrt{1-x^2}$$ you will get
$$f(x,\pm\sqrt{1-x^2})=x^3+(\pm\sqrt{1-x^2})^3$$ and you Problem is reduced to a Problem in only one variable.


text:
Q: How to say correctly "My age was smaller?" I was preparing for IELTS speaking and tried to say that I was younger than my classmates using the phrase "My age was smaller". But it seems unnatural, isn't it? How say it correctly, "My age was [the missing word]"?
Thanks a million!

A: You are right that "My age is smaller than ___" is not standard usage, but "I am younger than ___." is fine.


text:
Q: Euclidean Norm of a vector function not working well due to change in data type N.b. The below code is not using  intentionally
In the below code I am successfully calculating the Euclidean Norm of a vector.
#include <stdio.h>

int scanning_vector(int *vector);
int printing_vector(int *vector);
float euclidean_norm(int *vector);

int main()
{

    int vector1[5], vector2[5];
    float solution;

    printf("Please enter the first vector:\n");

    scanning_vector(vector1);
    printing_vector(vector1);
    solution=euclidean_norm(vector1);
    printf("%f",solution);

    printf("\nPlease enter the second vector:\n");

    scanning_vector(vector2);
    printing_vector(vector2);

    return 0;
}

int scanning_vector(int *vector)
{
    int i;
    for (i = 0; i < 5; ++i)
    {
        scanf("%d", &vector[i]);
    }
    return 0;
}

int printing_vector(int *vector)
{
    int i;
    for (i = 0; i < 5; ++i)
    {
        printf(" %d ", vector[i]);
    }
    return 0;
}

float euclidean_norm(int *vector)
{
    int i;
    float temp, sqrt, euclidean_norm;
    temp = 0;

    for (i = 0; i < 5; ++i)
    {
        euclidean_norm=euclidean_norm+vector[i]*vector[i];
    }
    /* The below code is to calculate the square root without using math.h */
    sqrt = euclidean_norm / 2;

    while(sqrt != temp)
    {
        temp = sqrt;
        sqrt = (euclidean_norm/temp + temp) / 2;
    }
    return sqrt;
}

However, I fail to understand why the below code doesn't work. I have only changed in the euclidean_norm function the data type of the parameter euclidean_norm from float to integer. Could you give me a quick explanation as to why this is not working? Thank you!
#include <stdio.h>

int scanning_vector(int *vector);
int printing_vector(int *vector);
float euclidean_norm(int *vector);

int main()
{

    int vector1[5], vector2[5];
    float solution;

    printf("Please enter the first vector:\n");

    scanning_vector(vector1);
    printing_vector(vector1);
    solution=euclidean_norm(vector1);
    printf("%f",solution);

    printf("\nPlease enter the second vector:\n");

    scanning_vector(vector2);
    printing_vector(vector2);

    return 0;
}

int scanning_vector(int *vector)
{
    int i;
    for (i = 0; i < 5; ++i)
    {
        scanf("%d", &vector[i]);
    }
    return 0;
}

int printing_vector(int *vector)
{
    int i;
    for (i = 0; i < 5; ++i)
    {
        printf(" %d ", vector[i]);
    }
    return 0;
}

float euclidean_norm(int *vector)
{
    int i, euclidean_norm;
    float temp, sqrt;
    temp = 0;

    for (i = 0; i < 5; ++i)
    {
        euclidean_norm=euclidean_norm+vector[i]*vector[i];
    }
    /* The below code is to calculate the square root without using math.h */
    sqrt = euclidean_norm / 2;

    while(sqrt != temp)
    {
        temp = sqrt;
        sqrt = (euclidean_norm/temp + temp) / 2;
    }
    return sqrt;
}

A: You invoked undefined behavior by using value of uninitialized variable having automatic storage duration euclidean_norm, which is indeterminate. Initialize that before entering the loop.
After that, the line sqrt = euclidean_norm / 2; should be sqrt = euclidean_norm / 2.0f; to avoid the result truncated to integer.

A: Thank you @MikeCAT for the quick answer! Just leaving here the code that works when using the data type of the parameter euclidean_norm as integer. Thank you!
#include <stdio.h>

int scanning_vector(int *vector);
int printing_vector(int *vector);
float euclidean_norm(int *vector);

int main()
{

    int vector1[5], vector2[5];
    float solution;

    printf("Please enter the first vector:\n");

    scanning_vector(vector1);
    printing_vector(vector1);
    solution=euclidean_norm(vector1);
    printf("%f",solution);

    printf("\nPlease enter the second vector:\n");

    scanning_vector(vector2);
    printing_vector(vector2);

    return 0;
}

int scanning_vector(int *vector)
{
    int i;
    for (i = 0; i < 5; ++i)
    {
        scanf("%d", &vector[i]);
    }
    return 0;
}

int printing_vector(int *vector)
{
    int i;
    for (i = 0; i < 5; ++i)
    {
        printf(" %d ", vector[i]);
    }
    return 0;
}

float euclidean_norm(int *vector)
{
    int i, euclidean_norm=0;
    float temp, sqrt;
    temp = 0;

    for (i = 0; i < 5; ++i)
    {
        euclidean_norm=euclidean_norm+vector[i]*vector[i];
    }
    /* The below code is to calculate the square root without using math.h */
    sqrt = euclidean_norm / 2;

    while(sqrt != temp)
    {
        temp = sqrt;
        sqrt = (euclidean_norm/temp + temp) / 2;
    }
    return sqrt;
}


text:
Q: Publish on Xbap to IIS on Windows Server 2003 Ive programmed an Xbap Application and published it to Windows XP computer without any problem. Now I want to publish the Xbap application to a Computer running Windows Server 2003. I do'nt get any failure when I´m publish the application, but when I try to browse the application I got failure and I cant browse the application.
When i try to run http://localhost/MyApp/setup.exe, It says that the file could not be found...
I there someting else I have to do when publish to a Windows Server 2003 Computer compared to Windows XP

A: Its seems like the problem here was the MIME Types in IIS. By register the followign MIME Types in IIS solved my problem:

*

*.manifest  application/manifest

*.xaml  application/xaml+xml

*.application  application/x-ms-application

*.xbap  application/x-ms-xbap

*.deploy  application/octet-stream

*.xps  application/vnd.ms-xpsdocument

For more information how to do this, see:
http://msdn.microsoft.com/en-us/library/ms752346.aspx#content_expiration

*

*List item


text:
Q: Finding the maximum elements whose sum is less than a given value in PyTorch Given any PyTorch 2D tensor, what will be the most efficient way to compute the number of top-K values for each row whose sum is less than a given value?
Input:
tensor([[0.6607, 0.1165, 0.0278, 0.1950],
        [0.0529, 0.4607, 0.2729, 0.2135],
        [0.3267, 0.0902, 0.4578, 0.1253]])

Required Output for the given value 0.8:
tensor([[1], #as 0.6607+0.1950 > 0.8
        [2], #as 0.4607+0.2729+0.2135 > 0.8
        [2]]) #as 0.4578+0.3267+0.1253 > 0.8

A: You can manage such operation by using a combination of sorting, cumulative sum, and max pooling.
First sort the values by row with torch.Tensor.sort
>>> v = x.sort(dim=1, descending=True).values
tensor([[0.6607, 0.1950, 0.1165, 0.0278],
        [0.4607, 0.2729, 0.2135, 0.0529],
        [0.4578, 0.3267, 0.1253, 0.0902]])

Then construct a mask on the cumulative sorted values that you get from applying torch.cumsum:
>>> torch.cumsum(v, dim=1) > .8
tensor([[False,  True,  True,  True],
        [False, False,  True,  True],
        [False, False,  True,  True]])

Applying a torch.Tensor.max on that mask will return the index of the first occurring True value, i.e. the location of the cumulative element which is above the threshold value 0.8:
>>> mask.max(1, True).indices
tensor([[1],
        [2],
        [2]])


text:
Q: Dynamically attach a function to grant access to private variables I'm trying to assign a callback dynamically to an Object of mine, I can't seem to figure out a way to do this while granting this function access to private variables.  I've listed the relavant code below with comments where I ran into walls.
Object Factory
function makeObj ( o ) {
                function F() {}
                F.prototype = o;
                return new F();
            }

Module
var MODULE = (function(){
   var myMod = {},
       privateVar = "I'm private";
   return myMod;
})();

Various Attempts

myMod.someDynamicFunc = function someDynamicFunc(){
    //privateVar === undefined;
    alert( privateVar );
}
myMod.someDynamicFunc();

myMod.prototype.someDynamicFunc = function someDynamicFunc(){
    //ERROR: Cannot set property 'someDynamicFunc' of undefined
    alert(privateVar);
}
myMod.someDynamicFunc();

In this attempt I tried making a setter in the module object... to no avail.
var MODULE = (function(){
       var myMod = {},
           privateVar = "I'm private";

           myMod.setDynamicFunction = function ( func ){
              if(func !== undefined && typeof func === "function"){
                //Uncaught TypeError:
                //         Cannot read property 'dynamicFunction' of undefined
                myMod.prototype.dynamicFunction = func;
                //also tried myMod.dynamicFunction = func;
              }
           }
       return myMod;
    })();

var myModule = makeObject( MODULE );

myModule.setDynamicFunction(function(){
   alert(privateVar);
});

myModule.dynamicFunction();

Am I just using JavaScript wrong? I'd really like to be able to assign callbacks after the object is initiated.  Is this possible?

A: You can't access the private variable via a callback function set dynamically (since it can't be a closure if it's attached later), but you can set up a system by which you would be able to access the variable:
var MODULE = (function(){
   var myMod = {},
       privateVar = "I'm private";

   myMod.callback = function(fn) {fn(privateVar);};

   return myMod;
})();

var someDynamicFunc = function(param) {alert(param);};
myMod.callback(someDynamicFunc);

Of course, this makes it not really private, since anyone could do this. I don't see how it would be possible at all for you to have a "private" variable that you access via dynamically attached functions, without allowing anyone else's dynamically attached functions to have the same privilege (thus making it not really private).

A: I guess you did not really understand exactly how closures work.
Closures mean that scopes always have access to the outer scope they were defined in.
function Counter(start) {
    var count = start;

    return {
        increment: function() { // has access to the outer scope
            count++;
        },

        get: function() {
            return count;
        }
    }
}

var foo = new Counter(4);
foo.increment();
foo.get(); // 5

The above example  returns two closures, both the function increment as well as get keep a reference to the count variable defined in the constructor.
One cannot access count from the outside, the only way to interact with it is via the two "closured" functions.
Remember, closures work by keeping a reference to their outer scopes, so the following does not work:
var foo = new Counter(4);
foo.hack = function() { // is not getting defined in the same scope that the original count was
    count = 1337;
};

This will not change the variable count that's inside of Counter since  foo.hack was not defined in that scope, instead, it will create or override the global variable count.


text:
Q: Angular 6 - Animation does not transition. It just jumps directly to state I am trying to get two animations to activate at the same time.
It's a big project, so I will only display the Component's HTML and Typescript files in question.
The first animation is to fade in an opaque black overlay. That works perfectly fine. The problem is with the second animation. I would like the pane to slide in from the right, simultaneously. Only after the animation for the overlay is finished does the pane show, but it doesn't transition like I want it to, it just jumps straight to the state.
I'm not too sure what the problem is, but I am hoping that I could get some help with this.
Thanks.
HTML

        <app-project-note-pane></app-project-note-pane>

TypeScript
import { Component, OnInit } from '@angular/core';
import {RightPaneService} from '../services/right-pane-service';
import {animate, state, style, transition, trigger} from '@angular/animations';

@Component({
  selector: 'app-right-pane',
  templateUrl: './right-pane.component.html',
  styleUrls: ['./right-pane.component.css'],
  animations: [
    trigger('rightPaneState', [
      state('collapsed', style({
        transform: 'translateX(650px)'
      })),
      state('expanded', style({
        transform: 'translateX(0)'
      })),
      transition('collapsed => expanded', [
        animate('1s', style({ transform: 'translateX(650px)' }))
      ])
    ]),

    trigger('rightPaneOverlayState', [
      state('hidden', style({
        backgroundColor: 'rgba(0, 0, 0, 0.0)'
      })),
      state('visible', style({
        backgroundColor: 'rgba(0, 0, 0, 0.7)'
      })),
      transition('hidden => visible', [
        animate('1s')
      ]),
      transition('visible => hidden', [
        animate('1s')
      ]),
    ])
  ]
})
export class RightPaneComponent implements OnInit {

  paneState = 'collapsed';
  paneOverlayState = 'hidden';

  paneExpanded = false;

  private paneCollapsing = false;

  constructor(private rightPaneService: RightPaneService) { }

  ngOnInit() {
  }

  // [ngStyle]="{'height': paneStatus ? '100vh' : '0'}"

  get paneStatus(): boolean {
    if (this.rightPaneService.paneExpanded && !this.paneCollapsing) {
      this.paneState = 'expanded';
        this.paneOverlayState = 'visible';
    } else {
      this.paneOverlayState = 'hidden';
      this.paneState = 'collapsed';
    }

    return this.rightPaneService.paneExpanded;
  }

  public hidePane() {
    this.paneCollapsing = true;
    this.paneOverlayState = 'hidden';
    this.paneState = 'collapsed';
    setTimeout(() => {
      this.rightPaneService.paneExpanded = false;
      this.paneCollapsing = false;
    }, 1000);
  }
}


text:
Q: Apple Lightning to Micro USB I am in the process of wiring up some iPad carts but they bought keyboards for the iPads that need to be charged by Micro USB.
The cart is already wired for Apple's Lightning and was wondering, is there anything aside from re-wiring the cart to go from the male Lightning connector to Micro USB or maybe the male Lightning to female USB so I can plug in the Micro USB cable?

A: The only official Lightning / Micro USB adapter sold by Apple is the Lightning to Micro USB adapter as shown below:

There doesn't seem to be an adapter for the reverse of this.


text:
Q: How do I prevent .git directory from getting copied to bin directory during rebuild? A .git directory keeps reappearing in my project, inside a directory that I think should be ignored. It reappears each time I clean the project or refresh it in Eclipse. The duplicated .git directory results in redundant files that prevent the project from building.
I have an Android project in Eclipse that links source from a Java project, which is the way LibGDX handles a project. The .git directory that I don't want contains a file that causes a conflict, so I have to delete it every time I want to build to device.
It is creating the directory MyProject/bin/classes/.git.  But I have bin/ in my .gitignore file. My repository is in MyProject.
The conflicting file is \bin\classes.git\COMMIT_EDITMSG. This conflicts with a file in my linked source Java project: \gen.git\COMMIT_EDITMSG. Also the same issue, because I have \gen in the .gitignore of that project.
I am pretty sure either Eclipse or ADT that is copying the .git directory over to the bin directory when it rebuilds or cleans the project.
So my question now is, how do I get Eclipse and/or ADT to stop doing that?
(If you want to see my old .gitignore, which I think is irrelevant because it was set up correctly to ignore the bin directory, you can click the "Edited" link to see it in this post's history.)

A: If what you want is to exclude *.git file to be copied during the build in eclipse, you can set this under Java Build Path menu for that specific project, and then add *.git into the exclusion patterns. It is quite tricky here because you can either specify inclusion patterns, or exclusion patterns, but not both of them. So, maybe you want to try to exclude *.git so that it does not copy during build.
See screenshot below for example:

A: You need to edit the .classpath file for your project and add patterns to ignore these directories.
Look for the lines:
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>

and change them into:
<classpathentry excluding="**/.git/**" kind="src" path="src"/>
<classpathentry excluding="**/.git/**" kind="src" path="gen"/>

The double asterisks are important, since they mean "any number of folders" (in this case "no matter what parent(s)" and "no matter what child(ren)" respectively).
Take a look at Inclusion and Exclusion Patterns in the Eclipse documentation.

A:

Are you using submodules? –  torek Jul 23 '13 at 20:27

I don't know what that is, so I don't think so

You should check it anyway, by going to the parent folder of that .git directory, and doing a git ls-files, looking for a special entry (a gitlink) mode 160000.
cd MyProject
git ls-tree HEAD bin
160000 commit c0f065504bb0e8cfa2b107e975bb9dc5a34b0398  bin

As jthill suggests in the comments:
git ls-files -s|grep ^16

See also if you have a MyProject/.gitmodules file.
If that is the case:
git submodule deinit bin
git rm bin
git commit -m "remove bin submodule"
git push

A: Adding a file to .gitignore does not remove it if it's already in the tree:
$ git init
Initialized empty Git repository in <path>/.git
$ mkdir gen; echo created > gen/file
$ git add gen; git commit -m initial
[master (root-commit) 14c2756] initial
 1 file changed, 1 insertion(+)
 create mode 100644 gen/file
$ echo gen > .gitignore; git add .gitignore; git commit -m 'oops, ignore gen'
[master dc55e75] oops, ignore gen
 1 file changed, 1 insertion(+)
 create mode 100644 .gitignore
$ rm gen/file
$ git reset --hard HEAD
HEAD is now at dc55e75 oops, ignore gen
$ cat gen/file
created
$ git ls-files
.gitignore
gen/file

So, how do you fix it?
$ git rm gen/file; git commit -m 'remove gen that we ignore'
rm 'gen/file'
[master 97de6f9] remove gen that we ignore
 1 file changed, 1 deletion(-)
 delete mode 100644 gen/file
$ mkdir gen ; echo created > gen/file
$ git status
# On branch master
nothing to commit, working directory clean

Basically you have to commit a change that removes the to-be-ignored files, so that they're not in the tree.  After that, the combination of the .gitignore and the lack of in-tree files will set you up the way you wanted in the first place.


text:
Q: How to check the which activity is currently running while debugging the app I am stuck with a project developed by someone else. Its a very big app. So for the purpose of understanding the code I want to know the flow, basically the name of the activity(the java file in the code) which is currently running in on my phone. I can put break-points in all activities, but is there any other way?

A: You can use adb for it.
In your terminal run adb shell dumpsys activity top.

A: Using ActivityLifecycleCallbacks, you don't need to add handling for all the activities. Do the registration once, it works for ALL activities, and that is it!
public class MyApplication extends Application implements
   ActivityLifecycleCallbacks{

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public void onActivityStopped(Activity activity) {
    Log.i("Tracking Activity Stopped", activity.getLocalClassName());

}

@Override
public void onActivityStarted(Activity activity) {
    Log.i("Tracking Activity Started", activity.getLocalClassName());

}

@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
    Log.i("Tracking Activity SaveInstanceState", activity.getLocalClassName());
}

@Override
public void onActivityResumed(Activity activity) {
    Log.i("Tracking Activity Resumed", activity.getLocalClassName());
}

@Override
public void onActivityPaused(Activity activity) {
    Log.i("Tracking Activity Paused", activity.getLocalClassName());
}

@Override
public void onActivityDestroyed(Activity activity) {
    Log.i("Tracking Activity Destroyed", activity.getLocalClassName());
}

@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
    Log.i("Tracking Activity Created", activity.getLocalClassName());
    }
}

Note that you can identify which activity via activity.getLocalClassName().

A: Simple -
In each activity override onStart() method and print log like this -
    @Override
    protected void onStart() {
        super.onStart();
        Log.d("TAG -> ", "YOUR_ACTIVITY_NAME");
    }

When activity start in your device, it will print log in logcat. Hope it will help!

A: From manifest figure out Launching activity and to find out methods and variables used.. u can use "Find Usages" ( Ctrl+G ).

A: If your application extends  MultiDexApplication class here is a working solution.
In onCreate() method of your application class that extends MultiDexApplication add the following line to register the callbacks.
@Override
public void onCreate() {
    super.onCreate();
    registerActivityLifecycleCallbacks(new MyActivityLifecycleCallbacks());
}

Now make an inner class that implements ActivityLifecycleCallbacks as follow
private static final class MyActivityLifecycleCallbacks implements ActivityLifecycleCallbacks {
        public void onActivityCreated(Activity activity, Bundle bundle) {
            Log.v("Application","Created");
        }
        public void onActivityDestroyed(Activity activity) {
            Log.v("Application","Destroyed");
        }
        public void onActivityPaused(Activity activity) {
            Log.v("Application","Paused");

        }
        public void onActivityResumed(Activity activity) {
            Log.v("Application","Resumed");

        }
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            Log.v("Application","onActivitySaveInstanceState");
        }
        public void onActivityStarted(Activity activity) {
            Log.v("Application","Started");
        }
        public void onActivityStopped(Activity activity) {
            Log.v("Application","Stopped");
        }
    }

Now you may use  activity.getLocalClassName() in any overridden method you need.
This would be all you need. Happy Debugging :)


text:
Q: In Angular 2 im getting response from backend...an im looping it in *ngFor in the html file In Angular 2 after deleting of an item in *ngFor (The item is deleted in the back-End) the item is still visible in the view... DOM is not updating... After the page refresh, the item is not visible in the view...

A: After deleting the item from the backend, either you need to do any of the below two.
1. Call the API to fetch the items from the backend.
2. If you really don't want the backend call to fetch the new list after deletion, atleast splice / slice the item from the list, so that *ngFor will not have the item on the list.
Otherwise you will have the item in the list till the list is refreshed.

A: Try something like this:
this._service.delete(item)
    .subscribe(
        (result) => { this.something = result },
        error => { this.errorMessage = <any>error; },
        () => {
            this.refreshView();
});

   refreshView() {
    this._service.getItems()
        .subscribe(
            (result) => { this.myItems = result },
            error => { this.errorMessage = <any>error; },
            () => {});
}


text:
Q: Show that for every positive integer $ f_n=\frac{\left ( \frac{1+\sqrt5}{2} \right )^n-\left ( \frac{1-\sqrt5}{2} \right )^n}{\sqrt5}$ Define the Fibonacci sequence via $f_1 = f_2 = 1$, and if $n > 2$, then $f_n =
f_{n−1} + f_{n−2}$ and show that for every positive integer $ f_n=\frac{\left ( \frac{1+\sqrt5}{2} \right )^n-\left ( \frac{1-\sqrt5}{2} \right )^n}{\sqrt5}$
I have been solving this problem using strong induction. This is my attemp.
For $n=1$.
$f_1=1$ and,
$\displaystyle \frac{\left ( \frac{1+\sqrt5}{2} \right )-\left ( \frac{1-\sqrt5}{2} \right )}{\sqrt5}=1$
For $n=2$
$f_1=2$ and,
$\displaystyle \frac{\left ( \frac{1+\sqrt5}{2} \right )^2-\left ( \frac{1-\sqrt5}{2} \right )^2}{\sqrt5}=1$ as well.
the statement is also true for $n = 3$
Now, assume that the statement is true for some $n-1$ and $n-2$. We get
$\displaystyle f_n =f_{n-1}+f_{n-2}=\frac{\left ( \frac{1+\sqrt5}{2} \right )^{n-1}-\left ( \frac{1-\sqrt5}{2} \right )^{n-1}}{\sqrt5}+\frac{\left ( \frac{1+\sqrt5}{2} \right )^{n-2}-\left ( \frac{1-\sqrt5}{2} \right )^{n-2}}{\sqrt5}$
From here, my intention is to show that the statement for $f_n$ is true. But I couldn't move on.

A: Don't work so hard.  Define some notation to simplify the algebra.
Let $$\varphi = \frac{1 + \sqrt{5}}{2}, \quad \bar \varphi = \frac{1 - \sqrt{5}}{2}.$$  Then we can easily see that $$\varphi  + \bar \varphi = 1, \quad \varphi \bar \varphi = \frac{1^2 - (\sqrt{5})^2}{2^2} = -1, \quad \varphi - \bar \varphi = \sqrt{5}.$$  Consequently,
$$\varphi = \varphi(\varphi + \bar \varphi) = \varphi^2 - 1, \quad \bar \varphi = \bar \varphi (\varphi + \bar \varphi) = -1 + \bar \varphi^2,$$ or $$\varphi^2 = 1 + \varphi, \quad \bar \varphi^2 = 1 + \bar \varphi.$$
Now we have $$f_n = \frac{\varphi^n - \bar \varphi^n}{\varphi - \bar \varphi},$$ and $$\begin{align}
f_{n-1} + f_{n-2}
&= \frac{\varphi^{n-1} - \bar \varphi^{n-1} + \varphi^{n-2} - \bar \varphi^{n-2}}{\varphi - \bar \varphi} \\
&= \frac{\varphi^{n-2}(1 + \varphi) - \bar \varphi^{n-2}(1 + \bar \varphi)}{\varphi - \bar \varphi} \\
&= \frac{\varphi^{n-2} \varphi^2 - \bar \varphi^{n-2} \bar \varphi^2}{\varphi - \bar \varphi} \\
&= \frac{\varphi^n - \bar \varphi^n}{\varphi - \bar \varphi} \\
&= f_n.
\end{align}$$
This concludes the proof.

A: For homogeneous second order linear difference equations there is a shortcut. I wonder why it is not well known and almost everybody is using the "standard way" of solving a linear equation system. BTW it just so happened somebody else applied it earlier today in this post: https://math.stackexchange.com/a/3898819/843178
This technique can be used in higher order equations (along with a treatment of duplicate roots) but it gets messy. So for higher order LDEs it's best to use the "standard solution".
The characteristic equation $^2−−1=0$ has two roots $\varphi=\frac{1+\sqrt 5}{2}, \psi=\frac{1-\sqrt 5}{2}$.
Vieta's formulas give $\varphi+\psi=1, \varphi \psi = -1$.
Therefore $$f_{+2}−(\varphi+\psi)f_{n+1}+\varphi \psi f_=0.$$
Rearranging the terms, we get
$$f_{n+2}−\psi f_{+1}=\varphi(f_{+1}−\psi f_) $$
$$f_{n+2}−\varphi f_{+1}=\psi (f_{+1}−\varphi f_) $$
Both are geometric sequences, so
$$f_{+1}−\psi f_=\varphi^ (f_1−\psi f_0 )=\varphi^ \tag 1$$
$$f_{+1}−\varphi f_=\psi^ (f_1− \varphi f_0 )=\psi^ \tag 2$$
(1)-(2), $$(−) f_=\varphi^−\psi^⇒ f_=(\varphi^−\psi^)/(\varphi−\psi).\blacksquare$$

A: $\displaystyle f_n =f_{n-1}+f_{n-2}=\frac{\left ( \frac{1+\sqrt5}{2} \right )^{n-1}-\left ( \frac{1-\sqrt5}{2} \right )^{n-1}}{\sqrt5}+\frac{\left ( \frac{1+\sqrt5}{2} \right )^{n-2}-\left ( \frac{1-\sqrt5}{2} \right )^{n-2}}{\sqrt5}$
Hint: Consider only the numerator part:
$$\left ( \frac{1+\sqrt5}{2} \right )^{n-1}-\left ( \frac{1-\sqrt5}{2} \right )^{n-1} + \left ( \frac{1+\sqrt5}{2} \right )^{n-2}-\left ( \frac{1-\sqrt5}{2} \right )^{n-2}$$
$$= \left ( \frac{1+\sqrt5}{2} \right )^{n-2} \left( \frac{1+\sqrt5}{2} +1\right) - \left ( \frac{1-\sqrt5}{2} \right )^{n-2} \left( \frac{1-\sqrt5}{2} +1\right)$$
$$= \left ( \frac{1+\sqrt5}{2} \right )^{n-2} \left( \frac{3+\sqrt5}{2} \right) - \left ( \frac{1-\sqrt5}{2} \right )^{n-2} \left( \frac{3-\sqrt5}{2} \right)$$

A: $f_n=f_{n-1}+f_{n-2}$ is a difference equation whiose solution is found by putting
$f_n=t^n$, then $t_{1,2}=\frac{1\pm \sqrt{5}}{2}$. The solution is
$$f_n=A t_1^n+ B t_2^n$$. By putting $f_1=f_2=1$, we get $$A=-B=\frac{1}{\sqrt{5}}.$$


text:
Q: Sharing functionality for an rss feed article My rss app is almost complete but I need to have a "share" button on the top right corner of the web view for the articles. I have the code setup so far to show the "action" button right next to the title of the article but since there is no real code implemented it doesn't do anything :

I implemented that by basing it on code that was used for the table view cells where there is a "refresh" option implemented and I just changed the icon. I used a free open source project to put this app together and i'm having a little bit of trouble figuring out how to make that button show the share sheet that pulls up from the bottom of the app, like this:

(image from google)
I tried to implement a button dirtectly into the nav bar but I can't since the web view covers the whole screen:

So, since I couldn't put a button directly into the controller I had to encode it in like so:
In my RSSDetail.m class inside the   " -(void)viewDidLoad { " :
self.navigationItem.rightBarButton = [[UIBarButtonItem = [[UIBarButtonItem
alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemAction target:self
action@selector(shareButton)];

and I also have this inside the same class file :
-(void) shareButton {

  self.webView.userInteractionEnabled = YES;
  self.webView.aplha = 0.3;

  }

So as you can see, this little bit of code in that class puts the icon where I want it. But my question is, is there code i can implement into my " -(void) shareButton " method that will implement the sharing functionality?
Also, I need for the button to actually say "Share" as opposed to the icon, is there anyway I can change the code for the "Action" rightBarButton method to allow me to input the word instead of an icon?
Thanks in advance

A: As I understand you want to implement iOS native sharing functionality. Here is an example of implementation:
- (void)shareButtonPressed {
    // 1
    // If you want to use UIImage, make sure you have image with that name, otherwise it will crash.
    NSArray *activityItems = @[@"Message to share", [UIImage imageNamed:@"imageToShare"]];

    // 2
    UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];

    // 3
    activityViewController.excludedActivityTypes = @[UIActivityTypeCopyToPasteboard, UIActivityTypeAirDrop, UIActivityTypeAssignToContact, UIActivityTypeAddToReadingList, UIActivityTypePrint, UIActivityTypeSaveToCameraRoll, UIActivityTypeMessage, UIActivityTypeMail];

    // 4
    [activityViewController setCompletionHandler:^(__unused NSString *activityType, __unused BOOL completed){
        // Custom completion implementation
    }];
    [self presentViewController:activityViewController animated:YES completion:NULL];
}

Description:

*

*Prepare activity items which you want to share such string, image, URL.

*Initialize activity view controller with the items you want to share + custom activities (only if needed). Custom activities means that you will create your own buttons using UIActivity with own actions, images, titles (more info here). For example, implement sharing to a third party app which does not have share extension.

*Here you can specify excluded activity types. In this example I have removed everything such as copy, airdrop and etc.

*In completion block you can see which activityType was selected and whether user cancelled or not.

More information on UIActivityViewController can be found here.
Regarding second part of your question about UIBarButtonItem. UIBarButtonItem can be initialised with custom title using this:
UIBarButtonItem *shareButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Share" style:UIBarButtonItemStylePlain target:self action:@selector(shareButtonPressed)];
self.navigationItem.rightBarButtonItem = shareButtonItem;

Be aware that UIBarButtonItem has UIBarButtonItemStyle which you can change. UIBarButtonItemStylePlain (will create a button with a regular font) and UIBarButtonItemStyleDone (will create a button with a bold font).


text:
Q: Why is this WebGL shader type invalid? Disclaimer: I just started using WebGL today.
I am attempting to draw some basic things on an HTML5 canvas using WebGL context in lieu of the "standard" 2d context.
I am using the developer.Mozilla.org WebGL documentation as reference, and have begun messing around with some code.
I have figured out that a vertex shader is necessary for rendering "clipspace" coordinates, and a fragment shader is necessary for rendering color for pixels being rendered. Per the WebGL wikipedia page, it seems shaders are coded directly in GLSL, which is a high-level dialect of C. On the Mozilla documentation, these code is stringified in JavaScript, but there are many ways to do it...
Here is the code I have so far, but the error I am running into has to do with the VERTEX_SHADER enum of the canvas' WebGL context is not recognized, and seeing that the context's documentation and prototype have such an enum, I want to know what is causing this error or why I am seeing this error.
The code is below, and thanks for any help.
<html>
<head>
    <title>webgl try</title>
</head>
<body>
<canvas width="600" height="400" id="canvas" style="border: 1px dotted;"> </canvas>

<script>
    var canvas = document.getElementById("canvas");
    var gl = canvas.getContext("webgl");

    function createShader (gl, sourceCode, type) {
      var shader = gl.createShader(type);
      gl.shaderSource(shader, sourceCode);
      gl.compileShader(shader);

      if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
        var info = gl.getShaderInfoLog(shader);
        throw "could not compile web gl shader. \n\n" + info;
      }
    }

    var vertexShaderSource =
      "attribute vec4 position;\n"
      "void main() {\n"+
      "  gl_Position = position;\n"+
      "}\n";

    var fragmentShaderSource =
      "void main() {\n"+
      "  gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n"+
      "}\n";

    /*
     * create program
     */

    var program = gl.createProgram();

    // ERROR COMES ON THIS LINE WHEN ATTEMPTING TO ACCESS THE VERTEX_SHADER ENUM: WebGL:
    // **INVALID_ENUM: createShader: invalid shader type**
    var vertexShader = gl.createShader(gl, vertexShaderSource, gl.VERTEX_SHADER);
    var fragmentShader = gl.createShader(gl, fragmentShaderSource, gl.FRAGMENT_SHADER);

    // Attach pre-existing shaders
    gl.attachShader(program, vertexShader);
    gl.attachShader(program, fragmentShader);

    gl.linkProgram(program);

    if ( !gl.getProgramParameter( program, gl.LINK_STATUS) ) {
       var info = gl.getProgramInfoLog(program);
       throw "Could not compile WebGL program. \n\n" + info;
    }
</script>
</body>
</html>

A: Your code contains semantic errors.
It should be
var vertexShader = createShader(gl, vertexShaderSource, gl.VERTEX_SHADER);
var fragmentShader = createShader(gl, fragmentShaderSource, gl.FRAGMENT_SHADER);

Because you are calling the createShader function above and not a method of webgl-context.
Your createShader should return the shader it created:
function createShader (gl, sourceCode, type) {
    var shader = gl.createShader(type);
    gl.shaderSource(shader, sourceCode);
    gl.compileShader(shader);

    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
        var info = gl.getShaderInfoLog(shader);
        throw "could not compile web gl shader. \n\n" + info;
    }

    return shader;
}

You also missed a + in vertexShaderSrc.


text:
Q: I cannot print the array that I am sending to the database - Laravel I have the following function, but when I run it in Postman to see the result, it doesn't print any value to me, it doesn't even give me an error. The var_dump set if it detects them, but the array does not... I think there is something wrong in the method updateOrCreate , because when I print this variable with var_dump, I can't see anything in the console.
This is the function:
 public function createBidRival(Request $request)
    {

        $response = array('code' => 400, 'error_msg' => []);
        if (!$request->id_karatekas) array_push($response['error_msg'], 'id_karateka is required');
        if (!$request->id_participant_bid_send  ) array_push($response['error_msg'], 'id_participant_bid_send is required');
        if (!$request->id_participant_bid_receive) array_push($response['error_msg'], ' id_participant_bid_receive is required');
        if (!$request->bid_rival) array_push($response['error_msg'], 'bid rival is required');
        if (!count($response['error_msg']) > 0) {
            try {

                var_dump($request->id_karatekas);
                var_dump($request->id_participant_bid_send);
                var_dump($request->id_participant_bid_receive);
                var_dump($request->bid_rival);

                $bidRival = new BidBetweenRivals();
                $bidRival = BidBetweenRivals::updateOrCreate(
                    [
                        'id_participant_bid_send' => $request->id_participant_bid_send,
                        'id_participant_bid_receive' => $request->id_participant_bid_receive,
                        'id_karatekas' => $request->id_karatekas
                        ],

                    [
                        'id_participant_bid_send' => $request->id_participant_bid_send,
                        'id_participant_bid_receive' => $request->id_participant_bid_receive,
                        'id_karatekas' => $request->id_karatekas,
                        'bid_rival' => $request->bid_rival
                        ]
                );
                  $bidBetweenRivals->save;
                $response = array('code' => 200, 'bidBetweenRivals' => $bidRival, 'msg' => 'Bid created');

            }catch(\Exception $exception) {
                $response = array('code' => 500, 'error_msg' => $exception->getMessage());
            }
        }
    }

A: Dump to see whether if (!count($response['error_msg']) > 0) true or not and also dump something in the catch block to see if exception  is occurring or not.
You can also test by commenting out the updateOrCreate part to see if it is interfering.


text:
Q: Extract total occurance of billing date within subscription period MySQL Trying to find the number of time the billing date occurs inside the entire subscription period.
For example, if subscription period is 26-01-2015 and 24-09-2016 so the billing date is 27th of each month. Hence the query should return 20 as the number of bill cycles completed.

A: You need to make use of a MySQL number generator to generate the dates series.
Query
SELECT
 COUNT(*) AS 'number of days'
FROM (

  SELECT
   '2015-01-26' + INTERVAL generator.number DAY AS date
  FROM (

    SELECT
     (@number  := @number + 1) AS number
    FROM (
      SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
    ) AS record_1
    CROSS JOIN (
      SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
    ) AS record_2
    CROSS JOIN (
      SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
    ) AS record_3
    CROSS JOIN (
      SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
    ) AS record_4
    CROSS JOIN ( SELECT @number := 0 ) AS init_user_param
  ) AS generator
) AS dates
WHERE
   dates.date BETWEEN '2015-01-26' AND '2016-09-24'
 AND
   DAY(dates.date) = 27

Result
| number of days |
|----------------|
|             20 |

see demo http://sqlfiddle.com/#!9/c61cdb/9


text:
Q: Best way to make nested custom objects parcelable in Android There is a lot of information out there concerning Parcelable in Android. After looking around, I couldn't find a nice solution for my problem.
So, I need to create a class (let's call it "MyClass") which extends a custom class someone else wrote ("HisClass"). There are many instance variables in HisClass, some of which are objects of custom classes, themselves. I want to pass a MyClass object from one activity to another and I realize, I need to make it Parcelable. But what about the instance variables which are custom objects?
Reading this, I think I need to make every single custom object implement Parcelable. Since, there are many custom objects in MyClass and HisClass which again have custom objects for instance variables, doing that seems like a bad solution to me.
Is there a better way? Maybe, I am just being totally blind here. Hope someone can help me.

A: Well, you can make use of Serializer, but it would result in a slow performance. AFAIK, implementing Parcelable is the best way to passing data. Additionally, don't try to complicate yourself by creating so much complex data structure to pass using Intent.
Either use Parcelable for something cheap/light-weight/less-in-amount or something else like output to files...and passing its paths.


text:
Q: Why do I get "undefined is not an object(evaluating "inputRef.current.incFont"? It doesnt do what I want.
I have two textArea, I use them as they were button. One will increase FontSize, other will decrease it.
When I click on decreaseFont text, i get that error.
Here is the code I added,
const MyInput = React.forwardRef((props,ref) => {

  const [fontSize, setFontSize] = useState(12);

  React.useImperativeHandle(ref,() => {
    incFont: () => {setFontSize(fontSize+2)}
    decFont: () => {setFontSize(fontSize-2)}
  })

  return(
    <TextInput style={{fontSize, borderColor:"red",borderWidth:1}} />
  )

})

inside my main function:
 const inputRef = useRef();
<View>
 <MyInput ref={inputRef}/>
          <Text onPress={()=>inputRef.current.incFont()}>IncreaseFont</Text>
          <Text onPress={() => inputRef.current.decFont()}>DecreaseFont</Text>

        </View>

A: Change useImperativeHandle like below,
React.useImperativeHandle(ref, () => ({
    incFont: () => {
      setFontSize(fontSize + 2);
    },
    decFont: () => {
      setFontSize(fontSize - 2);
    }
  }));

working code - https://codesandbox.io/s/distracted-burnell-0h70g?file=/src/App.js