text:
Q: is VB.NET SmtpClient API limited compared to Java SendMail? I created a method to send email in VB.NET:
Imports System.Threading
Imports System.Net.Mail
Imports System.ComponentModel

Module Module1
    Dim smtpList As New ArrayList

    Dim counter = 0

    Private Sub smtpClient_SendCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
        System.Diagnostics.Debug.WriteLine("completed!")
        System.Console.WriteLine("completed!")
    End Sub

    Public Function createSmtp() As SmtpClient
        Dim smtp = New SmtpClient()
        Dim user = "AKAKAKAKAKAKAKAK"
        Dim host = "smtp.mailgun.org"
        Dim pass = "akakakakakakakakakakakakakakakakakakakak"

        smtp.Host = host
        smtp.Port = 587
        smtp.Credentials = New System.Net.NetworkCredential(user, pass)
        smtp.EnableSsl = True

        Return smtp
    End Function

    Public Sub SendEmail(email As String, bodystuff As String, smtp As SmtpClient)

        Dim from As New MailAddress("contat@testsitetetete.com", "Info", System.Text.Encoding.UTF8)
        Dim [to] As New MailAddress(email)
        Dim message As New MailMessage(from, [to])
        message.Body = String.Format("The message I want to send is to this <b>contact: {0}{1}</b>", vbCrLf, bodystuff)
        message.IsBodyHtml = True
        message.BodyEncoding = System.Text.Encoding.UTF8
        message.Subject = "Test email subject"
        message.SubjectEncoding = System.Text.Encoding.UTF8
        message.Priority = MailPriority.High

        ' Set the method that is called back when the send operation ends.
        AddHandler smtp.SendCompleted, AddressOf smtpClient_SendCompleted

        smtp.Send(message)
        'smtp.SendMailAsync(message)

        counter = counter + 1 ' I know its not thread safe, just to get a counter

        System.Console.WriteLine("Counter -> " & counter)

    End Sub

    Public Sub StartEmailRun()
        System.Diagnostics.Debug.WriteLine("StartEmailRun")

        'Dim smtp = createSmtp()

        Try
            For i = 0 To 8

                Dim thread As New Thread(
                  Sub()
                      Dim smtp = createSmtp()
                      SendEmail("someamail@testemail.com", "email test", createSmtp())
                  End Sub
                )
                thread.Start()
            Next

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

    Sub Main()
        System.Diagnostics.Debug.WriteLine("Starting the email sending...")

        ThreadPool.SetMinThreads(100, 100) ' just to make sure no thread pool issue or limitation

        createSmtp()

        StartEmailRun()

        Thread.Sleep(300000) ' make the program alive
    End Sub

End Module

and I created this same method in java:
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class TestMail
{

    public static void main(String[] args) throws AddressException, MessagingException, InterruptedException
    {

        Properties prop = new Properties();
        prop.put("mail.smtp.auth", true);
        prop.put("mail.smtp.starttls.enable", "true");
        prop.put("mail.smtp.host", "smtp.mailgun.org");
        prop.put("mail.smtp.port", "587");
        prop.put("mail.smtp.ssl.trust", "smtp.mailgun.org");

        Session session = Session.getInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                String username = "akakakakakakakakakak";
                String password = "kajdfkjasfkjasdfksjdfksdajfksdfjsdkfjdskfjkW";
                return new PasswordAuthentication(username, password);
            }
        });

        final Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("testacount@test.com"));
        message.setRecipients(
          Message.RecipientType.TO, InternetAddress.parse("atest@test.com"));
        message.setSubject("Mail Subject");

        String msg = "This is my first email using JavaMailer";

        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setContent(msg, "text/html");

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(mimeBodyPart);

        message.setContent(multipart);
        for (int i = 0; i < 8; i++)
        {
            new Thread(new Runnable() {

                public void run() {
                    try {
                        Transport.send(message);
                    } catch (MessagingException e) {
                        e.printStackTrace();
                    }
                    System.out.println("sent...");
                }
            }).start();
        }

        while(true)
        {
            Thread.sleep(1000);
        }
    }
}

I expected the VB.NET code to sent the emails simultanteously, like the java one does.
But the email sent appears to be sequencial. In the java all the emails are sent simultaneosly.
I think there is some limitation on send multiple emails in the VB.Net code.
Is there a way to send multiple emails at the same time in VB.NET???
p.s. not talking about bbc, because every email is different from another.


text:
Q: 502 Bad Gateway Foreach loop hope for some help, basically i have a script that gets the latest posts from facebook users, and basically i check if there is any new post that is not available on my database, in case that this post is new, than i save it in my database along with the post id (this way i check if exist on DB).
But i have a issue with it, in my case i need to check a number of users, and this users keeps growing, in my case i have 400 users. If i go more thatn 100 users i get the 500 error of course, it is many requests.
So does someone have a ideia of how could i handle it?
My code: FarcebookParcer.php
public function facebook($id, $num) {
    //Set your App ID and App Secret.
    $appID       = 'xxxxxxxxxx';
    $appSecret   = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx';
    //Create an access token using the APP ID and APP Secret.
    $accessToken = $appID . '|' . $appSecret;
    //Tie it all together to construct the URL
    $url         = "https://graph.facebook.com/$id/posts?fields=attachments,created_time&limit=$num&access_token=$accessToken";
    if (Helper::get_http_response_code($url) != 200) {
        return false;
    }
    //Make the API call
    $opts    = array(
        'http' => array(
            'method' => 'GET',
            'timeout' => 120
        )
    );
    $context = stream_context_create($opts);
    $result  = file_get_contents($url, false, $context);
    //Decode the JSON result.
    $dt      = json_decode($result, true);
    $posts   = $dt;
    return $posts;
}

CronController.php
public function socialfacebook() {
    $facebook     = SocialSnap::all();
    $socialparser = new FacebookParser();
    $appID        = 'xxxxxxxxxxx';
    $appSecret    = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
    $accessToken  = $appID . '|' . $appSecret;
    set_time_limit(0);
    foreach ($facebook as $key => $value) {
        if ($value->facebook != NULL) {
            $facebook_user  = $socialparser->facebook_user(substr($value->facebook, 1));
            $facebook_posts = $socialparser->facebook(substr($value->facebook, 1), 1);
            //Check if valid url
            if ($facebook_posts == false || $facebook_user == false) {
                continue;
            }
            if (isset($facebook_posts['data'][0]['attachments']['data'][0]['target']['url']) && isset($facebook_posts['data'][0]['attachments']['data'][0]['description'])) {
                SnapChat::where('facebook', $value->facebook)->update(['facebook_photo' => 'https://graph.facebook.com/'. substr($value->facebook, 1) . '/picture/?type=normal']);
                $post_current = SocialSnap::where('id_social', $facebook_posts['data'][0]['id'])->first();
                //return $post_current;
                if ($post_current == NULL) {
                    $post               = new SocialSnap;
                    $post->id_social    = $facebook_posts['data'][0]['id'];
                    $post->id_snapchats = $value->id;
                    $post->date_social  = isset($facebook_posts['data'][0]['created_time']) ? date("Y-m-d H:m:s", strtotime($facebook_posts['data'][0]['created_time'])) : "";
                    $post->type         = 'facebook';
                    $post->url          = $facebook_posts['data'][0]['attachments']['data'][0]['target']['url'];
                    $post->message      = $facebook_posts['data'][0]['attachments']['data'][0]['description'];
                    if (isset($facebook_posts['data'][0]['attachments']['data'][0]['media']['image']['src'])) {
                        $post->image = $facebook_posts['data'][0]['attachments']['data'][0]['media']['image']['src'];
                    }
                    $post->save();
                }
            }
        }
    }
    echo 'DONE';
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why won't my WiFi work with a Belkin USB dongle and WPA2? I am using a Belkin usb dongle to connect to my wifi  network with a wpa2 key. Most of the times Ubuntu is not able to connect to the network automatically and keeps on asking for the key, even though the correct key has already been entered.
It connects after restarting networking multiple times.
I am on 11.04 with the latest updates.

A: Try using wicd instead of native network-manager. I had similar issues, mostly related to bizarre unexpected wifi disconnections - after upgrading to 11.04. I never had this problem on earlier versions of ubuntu to be honest.

A: I once had to use an Acer Aspire TimelineX that had an unsupported wireless card. I downloaded wicd via wired and it worked perfectly, although it doesn't show up in your panel.


text:
Q: Permitir certo ID logado apenas O meu site salva no banco de dados o ID do usuário, daí ele quando logado, fica com o ID. Queria conseguir algum tipo de código que fizesse a seguinte tarefa:
Quando usuário logado com ID "x" no site e estiver passando por páginas, daí em certa página fazer com que ele não tenha permissão de acessar essa certa página, e quando acessar ser redirecionado para outra, informando que ele não tem permissão. Somente usuários que conter por exemplo no arquivo permitido.txt (ou PHP), ter essas permissões...
Eu até tenho algo parecido mais ele só funciona ao contrário que quero, ou seja, ao invés dele permitir o ID ele o bloqueia, queria algo ao contrário.. Abaixo está oque eu tenho:
}
    }else{
        header('Location: ?type=status');
    }
}

if($user->id =="1000012034731" || $user->id =="4"){
    echo "Tenha um bom dia! Você está bloqueado...!!";
    echo "<br>";
    echo " Nossa equipe detectou algo errado em sua conta.";
    exit;
}

if(isset($_POST['logout'])) {
    session_destroy();
    header('Location: index.php?i=Logout Success..!! ');
}
?>

Obs.: Já tentei mudar os sinais de "==" para diferente, mais mesmo assim não deu..


text:
Q: Mapping value selected in Spinner to other values I got a spinner of items, e.g. {Apples, Oranges, Eggs, Bread}. When user selects "Eggs" it's value/cost ($2) would be used in a computation of total cost later. How can I map a value(cost of item) with the item selected by the user in the spinner? I'm a little confused whether it's possible. It seems like it is having 2 values.
Something like:
double totalExpenses = $23 + (cost of the item user selected)
strings.xml
<string-array name="spinner_array">
<item>Apples</item>
<item>Oranges</item>
<item>Eggs</item>
<item>Bread</item>
</string-array>

A: If you want to avoid creating your own adapter (sometimes you want this to keep it simple)
Have another array of same size, which has the prices:
<string-array name="spinner_array">
   <item>Apples</item>
   <item>Oranges</item>
   <item>Eggs</item>
   <item>Bread</item>
</string-array>

<string-array name="spinner_array_values">
   <item>5.99</item>
   <item>6.99</item>
   <item>2.99</item>
   <item>12.99</item>
</string-array>

Then, on your event handler, get the selected index of the spinner. Use that index to get the price from the second array.
double totalExpenses = $23 + Double.parseDouble(value of spinner_array_values index at the spinner selected index);

=== EDIT (code sample) ====
int selectedIndex = spinner.getSelectedItemPosition();
String[] price_array = getResources().getStringArray(R.array.spinner_array_values);
double totalExpenses = 23 + Double.parseDouble(price_array[selectedIndex]);

OR
double totalExpenses = 23 + Double.parseDouble(getResources().getStringArray(R.array.spinner_array_values)[spinner.getSelectedItemPosition()]);

A: Personally, I would create a custom ArrayAdapter. That would let you use your own class (class Food, for example) as the item in the list.
That way you can do all of your calculations abstracted.
This video may get you started on the right foot.


text:
Q: Reverse for ''contact'' with arguments '()' and keyword arguments '{}' not found Not sure why i'm getting this error when the site has been working fine on runserver. Anyway, i'm getting the above error and i'm not sure why.
Here is my code and hopefully you can shed some light:
views.py
def contact(request):
    if request.method == 'POST':
        form = forms.ContactUsForm(request.POST)

        if form.is_valid():
            form.save()
        return HttpResponseRedirect('/thanks/')

    else:
        form = forms.ContactUsForm()

        return render(request, 'contact.html', {
                  'contact_form' : form,
        })

urls.py
 url('^thanks/$', 'contact_enquiries.views.contact', name="contact"),

Context processor as the form is included on everypage:
def contact(request):
        form = forms.ContactUsForm()

        return {
                  'contact_form' : form,
        }

HTML:
 <form action="{% url 'contact' %}" method="post">

Any help would be much appreciated. The idea is the form will redirect to the contact view. As the context processor can't render the form on every page.
Any help would be much appreciated.
Thanks.


text:
Q: regexp - first and last name javaScript I'm trying to make a JavaScript regexp such as the facebook uses for real names:

*Names can't include:

*Symbols

*numbers

*unusual capitalization

*repeating characters or punctuation

source: Facebook help center
Here is my regexp:
 /^[a-z \,\.\'\-]+$/i

The problem with this regexp is that it doesn't check for repeated characters or punctuation:
then I found this :
/(.)\1/

so I'm now checking it like this:
$('input [type=text]).keyup(function(){
var name = $(this).val();
var myregex = /^[a-z\,\.\'\-]+$/i
var duplicate =  /(.)\1/
if(name != myregex.exec(name) ||  name == /(.)\1/)
{// the name entered is wrong
}
else
//the name is ok

but the problem I'm facing is with inputs like:

*

* Moore

* Callie

* Maggie

what can I do to get the problem solved?

A: You should stop trying to solve this problem:

*

*It is very complicated

*Names are very personal

For instance your system will never be able to validate names from China
or Japan.... (For instance: Børre Ørevål ,汉/漢 )
So just leave the whole idea, and let people freely enter their names with no restrictions.
Related: Regular expression for validating names and surnames?


text:
Q: Replace strings in file concurently in golang I've a huge text file containing some strings to be replaced and i want to do that in a concurrent way so that i'll be able to replace more than one string , here's my current code :
        import (
        "fmt"
        "io/ioutil"
        "os"
        "path/filepath"
        "strings"
        "sync"
    )

    var fileMutex sync.Mutex

   var (
    oldHelloWorld = "hel world"
    newHelloWorld = "hello world"
    oldJohnDoe    = "joh doe"
    newJohnDoe    = "John Doe"
    oldJaneDoe    = "jane doeee"
    newJaneDoe    = "Jane Doe"
    )

    var (
        changesHolder = map[string]string{
          oldHelloWorld: newHelloWorld,
          oldJohnDoe: newJohnDoe,
          oldJaneDoe: newJaneDoe,
        }
    )

    func doReplace(fileName,newContent string, wg *sync.WaitGroup)  {

        fileMutex.Lock()
        defer fileMutex.Unlock()
        defer wg.Done()
        err := ioutil.WriteFile(fileName, []byte(newContent), 0)
        if err != nil {
            panic(err)
        }
    }

    func replace(fileName string){

        var wg *sync.WaitGroup = new(sync.WaitGroup)
        read, err := ioutil.ReadFile(fileName)
        if err != nil {
            panic(err)
        }

        var newContent = ""
        for key, value := range changesHolder {
            wg.Add(1)
            newContent = strings.Replace(string(read), key, value, -1)

            go doReplace(fileName,newContent, wg)
        }

        wg.Wait()
    }

    func main() {
       replace("myText.txt")
    }

But the result is only the last changesHolder element (oldJaneDoe) which gets replaced although my text file contains all other occurrences.
Any help is appreciated!

A: strings.Replace use StringBuilder, so  it can't concurrent
you can write a byte replace function youself
follow is a example:
package main

import (
    "fmt"
    "sync"
)

var wg sync.WaitGroup

var (
    changesHolder = map[byte]byte{
        'a': '1',
        'b': '2',
        'c': '3',
    }
)

func Replace(bs []byte, old byte, new byte) {
    for i, b := range bs {
        if b == old {
            bs[i] = new
        }
    }
    wg.Done()
}

func main() {
    b := []byte("aa bb cc")
    for old, new := range changesHolder {
        wg.Add(1)
        go Replace(b, old, new)
    }
    wg.Wait()
    fmt.Printf("%s\n", b)
}


text:
Q: Sum involving the set of all possible combinations with at most two repetitions I am having problems with a combinatorial argument and I need some help. I do not do combinatorics so I am not sure what is the best notation for this problem (any suggestion is very welcome). Consider $n\in\mathbb{N}$ with $n\geq 2$. I would like to compute the following quantity: First consider the list of numbers $$
L_n:=\{\tfrac{1}{2},\tfrac{3}{2},...,\tfrac{2n-1}{2}\}.
$$
Now let's call $P_{3}$ the set of all possible selection of $3$ elements of $L_n$ where it is possible to repeat an element at most two times where we don't allow permutations. The sense of "allowing to repeat two times an element" has to be understood as having "objects" with repeated labels, and hence having two times each "object" (number). So, for example, if $n=2$, we have $$
P_3=\{\{\tfrac{1}{2},\tfrac{1}{2},\tfrac{3}{2}\},\{\tfrac{1}{2},\tfrac{1}{2},\tfrac{3}{2}\},\{\tfrac{1}{2},\tfrac{3}{2},\tfrac{3}{2}\}\{\tfrac{1}{2},\tfrac{3}{2},\tfrac{3}{2}\}\},
$$
where $\{\tfrac{1}{2},\tfrac{1}{2},\tfrac{3}{2}\}$ appears two times in $P_3$ because we can pick both repetitions of $\tfrac{1}{2}$ and then we can choose any of the two differents objects with the label $\tfrac{3}{2}$. On the other hand, if we consider for instance, $P_2$ (the same definition of $P_3$ but with all possible selections of $2$ elements instead of three, and repeating at most two times each element (exactly as before)), then the pair $$
\{\tfrac{1}{2},\tfrac{3}{2}\}
$$
appears four times in $P_2$ (see the "PS2" below for more details). In this sense, the pair $\{\tfrac{1}{2},\tfrac{1}{2}\}$ also belongs to $P_2$ and appears only one time. I would like to compute the quantity $$
\mathcal{Q}_3=\sum_{P\in P_{3}}\prod_{k\in P}k^2.
$$
The previous quantity must to be understood in the following way: in the case $n=3$, if $P$ is for example $\{\tfrac{1}{2},\tfrac{1}{2},\tfrac{5}{2}\}$, then $$
\prod_{k\in P}k^2=(\tfrac{1}{2})^2(\tfrac{1}{2})^2(\tfrac{5}{2})^2.
$$
More generally I would like to understand the growth of the previous quantity once we fix $n$ and we increase the number of elements we can choose. In other words, consider $m\in\{1,...,n\}$ and denote by $P_{m}$ the set of all possible selections of $m$-elements (from our fixed list $L_n$) where we are allowed to repeat an element at most two times (exactly as before). Would it be possible to prove something like (for example) $$
\mathcal{Q}_{2m-2}\leq 4\mathcal{Q}_{2m-1}?
$$
Here, by convention lets say that $\mathcal{Q}_0:=1$.
PS: Just as an example, if $n=2$ and $m=2$, then $$
\sum_{P\in P_3}\prod_{k\in P}k^2=\tfrac{45}{16} \quad \hbox{and}\quad \sum_{P\in P_2}\prod_{k\in P}k^2=\tfrac{59}{8},
$$
and hence $\tfrac{59}{8}=\mathcal{Q}_2<4\mathcal{Q}_3=\tfrac{90}{8}$. Moreover, if $m=1$ in the previous example, then $\mathcal{Q}_1=5$ and $\mathcal{Q}_0=1$, so $\mathcal{Q}_0<4\mathcal{Q}_1$.
PS2: To fix ideas (I am emphasising just because I am worried that the problem might not be sufficiently clear), if $n=2$ then $P_1$ would be $ P_1=\{\tfrac{1}{2},\tfrac{1}{2},\tfrac{3}{2},\tfrac{3}{2}\}$, and $$
P_2=\{\{\tfrac{1}{2},\tfrac{1}{2}\},\{\tfrac{1}{2},\tfrac{3}{2}\},\{\tfrac{1}{2},\tfrac{3}{2}\},\{\tfrac{1}{2},\tfrac{3}{2}\},\{\tfrac{1}{2},\tfrac{3}{2}\},\{\tfrac{3}{2},\tfrac{3}{2}\}\},
$$
where $\{\tfrac{1}{2},\tfrac{3}{2}\}$ appears four times because we can choose the first appearance of $\tfrac{1}{2}$ with both, the first and the second appearance of $\tfrac{3}{2}$; and then we can do the same with the second appearance of $\tfrac{1}{2}$. (There probably is a much better way to write this with proper combinatorial notation). So for example I think that the fact that this pair $\{\tfrac{1}{2},\tfrac{3}{2}\}$ appears four times in the set has to be related to considering the permutations of $\{\tfrac{1}{2},\tfrac{3}{2}\}$ (which are two), with an extra factor of $2$ due to the fact we are allowing to consider two times each element (but I am not sure how to write that, mainly because the pair $\{\tfrac{1}{2},\tfrac{1}{2}\}$ appears only one time in the set). I hope the problem is clear enough.

A: The number of subsets  can be found by pretending that there are two "copies" of each element in $P_1$, and then using standard combinatorics arguments. For example, if you are choosing subsets of $m$ elements from $L_n$, allowing the selection to be repeated no more than twice, there are ${2n \choose m}$ possible subsets.
To calculate the $\mathcal{Q}_n$ quantities, we can use generating functions.  It's easiest to proceed by looking at the example $m = 2$.  Consider the polynomial
$$
f_2(x) = \left[ 1 + \left(\frac{1}{2}\right)^2 x \right] \left[ 1 + \left(\frac{1}{2}\right)^2 x \right] \left[ 1 + \left(\frac{3}{2}\right)^2 x \right] \left[ 1 + \left(\frac{3}{2}\right)^2 x \right].
$$
This will be some polynomial in $x$, with terms up to $x^4$.  If we were to multiply this out, what would the coefficient of $x^3$ be?  It would result from all of the terms where we "pick" three of the $x$ terms from three of the monomials, and "pick" 1 from the remaining monomial.  In other words, the coefficient of $x^3$ would be
$$
\left(\frac{1}{2}\right)^2 \left(\frac{1}{2}\right)^2 \left(\frac{3}{2}\right)^2 + \left(\frac{1}{2}\right)^2 \left(\frac{1}{2}\right)^2 \left(\frac{3}{2}\right)^2 + \left(\frac{1}{2}\right)^2 \left(\frac{3}{2}\right)^2 \left(\frac{3}{2}\right)^2 + \left(\frac{1}{2}\right)^2 \left(\frac{3}{2}\right)^2 \left(\frac{3}{2}\right)^2 = \mathcal{Q}_3.
$$
In fact, it is not hard to see that by similar logic,
$$
f_2(x) = \mathcal{Q}_0 + \mathcal{Q}_1 x + \mathcal{Q}_2 x^2 + \mathcal{Q}_3 x^3 + \mathcal{Q}_4 x^4.
$$
While this technique doesn't yield a closed-form expression* for $\mathcal{Q}_m$, it does allow for relatively easy exact calculation via computer algebra systems (Mathematica or equivalent.)  In addition, it may be possible to use the generating function to make exact statements about the relative values of coefficients in the polynomial $f_n(x)$, and thus relating $\mathcal{Q}_{2m-2}$ to $\mathcal{Q}_{2m-1}$ as you hope to do.
My Mathematica code is below, if you are interested.  It returns a list of the values of $\mathcal{Q}_m$ for a given value of $n$.
n = 2;
poly[x_, a_] = (1 + a^2 x)^2;
f[n_, x_] := Expand[Product[poly[x, (2 i - 1)/2], {i, 1, n}]]
CoefficientList[f[n, x], x]

* Mathematica does actually return an exact result for general $n$ in terms of Pochhammer symbols involving $1/\sqrt{-x}$ and $x/(-x)^{3/2}$. But that's hardly useful.

A: Elaborating on Michael's answer, it's easy to get a closed-form expression for $\mathcal{Q}_3$ (and $\mathcal{Q}_m$) for general $n$. In terms of elementary symmetric polynomials, we have
$$\mathcal{Q}_m = e_m(\left(\frac{1}{2}\right)^2,\left(\frac{1}{2}\right)^2,\left(\frac{3}{2}\right)^2,\dots,\left(\frac{2n-1}{2}\right)^2,\left(\frac{2n-1}{2}\right)^2).$$
While it may be tricky to compute $e_3$ from scratch, we can easily get initial values of power sum symmetric polynomials:
$$p_k(\left(\frac{1}{2}\right)^2,\left(\frac{1}{2}\right)^2,\left(\frac{3}{2}\right)^2,\dots,\left(\frac{2n-1}{2}\right)^2,\left(\frac{2n-1}{2}\right)^2)=\frac{1}{2^{2k-1}}\cdot p_{2k}(1,3,\dots,2n-1).$$
For $k=1,2,3$, they are
$$\frac{n(2n-1)(2n+1)}{6},\ \frac{n(2n-1)(2n+1)(12n^2-7)}{120},\ \frac{n(2n-1)(2n+1)(48n^4-72n^2+31)}{672}.$$
Using Newton's identities, we get
$$\mathcal{Q}_1 = \frac{n(2n-1)(2n+1)}{6},$$
$$\mathcal{Q}_2 = \frac{n(2n-1)(2n+1)(40n^3-36n^2-10n+21)}{720},$$
$$\mathcal{Q}_3 = {\frac {n \left( 2\,n-1 \right)  \left( 2\,n+1 \right)  \left( n-1 \right)  \left( 2\,n-3 \right)  \left( 560\,{n}^{4}-112\,{n}^{3}-320\,{n}^{2}+628\,n+465 \right) }{90720}}.$$

For a fixed $m$, $\mathcal{Q}_m$ is expressed as a polynomial in $n$  as follows:
$$\mathcal{Q}_m = \frac{(-1)^m}{m!} \mathcal{B}_m(t_1, t_2, \ldots, t_m ),$$
where $\mathcal{B}_m$ is the complete exponential Bell polynomial and
$$t_k := -\frac{(k-1)!}{2^{2k-1}}p_{2k}(1,3,\dots,2n-1).$$
The latter is expressed as a polynomial in $n$ with Faulhaber's formula:
$$p_{2k}(1,3,\dots,2n-1) = p_{2k}(1,2,\dots,2n-1) - 2^{2k}p_{2k}(1,2,\dots,n-1)$$
$$ = \frac{1}{2k+1}\sum_{j=0}^{2k}(-1)^j\binom{2k+1}j B_j ((2n-1)^{2k+1-j} - 2^{2k}(n-1)^{2k+1-j}),$$
where $B_j$ are Bernoulli numbers.


text:
Q: Angular - Delaying forEach I have a problem. I am trying to create an animation, changing the color of several layers with a timeout between painted.
$scope.StartMovementsAnimation = function()
{
      angular.forEach($scope.GameMovements, function(movement){
       if (movement == "Green")
       {
          $scope.Green = true;
       }
       else (movement == "Orange")
       {
          $scope.Orange = true;
       }
  });
}

The problem I have is that I do not know how to stop or delay the flow loop. I'm pretty lost. I tried with $ timeout, sleep etc but does not work.
Any solution?
thanks

A: Don't use forEach. Use $timeout to repeat as many as the number of items in your GameMovements array.
Take a look at the following example. It is going to change className field from orange to green and vice versa till the variable left's value reaches 0.
$scope.className = "orange";
$scope.count = 0;
$scope.startAnimation = function() {
  var left = 10
  var ticker = function() {
    if (left % 2 === 0)
      $scope.className = 'orange'
    else
      $scope.className = 'green'
    left -= 1
    if (left > 0) {
      $timeout(ticker, 1000)
    }
  }

  $timeout(ticker, 1000)
}


text:
Q: Execute helper script inside of phar Is it possible to add a script like a bash script or Python script to a phar and have the phar application execute that script.
A practical example running PHP < 5.4 you cannot join a multicast group using just PHP. So I have PHP exec a Python script that joins the mcast group then I listen using PHP.

A: The only way to do this is to extract that file from the .phar into a temporary file and execute this file.


text:
Q: ignore file parser deploy there any way to ignore files or file paths when you have multiple folders deploy parse that I should not raise such node_modules folder and others can?
I found these links which have the same question but the answer is not very clear
https://www.parse.com/questions/ignore-files-on-deploy
https://www.parse.com/questions/ignore-files-on-deploy--2
Many thanks for your time.

A: I haven't been able to find documentation for it but it looks like parse have added support for a .parseignore file as evidenced by the code here https://github.com/ParsePlatform/parse-cli/blob/master/parsecmd/deploy.go#L29.
It looks like supports most of the .gitignore syntax except ** using the github.com/facebookgo/parseignore library.
While it appears to work for a small number of files, it is choking on my node_modules directory with a 'too many open files' error.


text:
Q: `meteor create` "Errors prevented isopacket load" Whenever I use meteor create x I get this same error. Uninstalled, reinstalled, still get the same error and I can't quite find someone else who is having the same issue. Mete
PS C:\Users\x\source\Meteor> meteor create todos
Errors prevented isopacket load:

While loading isopacket `combined`:

C:\Users\x\AppData\Local\.meteor\packages\meteor-tool\1.10.2\mt-os.windows.x86_64\tools\fs\tools\fs\files.ts:1170:25:
sourcemapConsumer.destroy is not a function
at
C:\Users\x\AppData\Local\.meteor\packages\meteor-tool\1.10.2\mt-os.windows.x86_64\tools\fs\tools\fs\files.ts:1170:25
at Function.time
<snip>

C:\Users\x\AppData\Local\.meteor\packages\meteor-tool\1.10.2\mt-os.windows.x86_64\dev_bundle\lib\node_modules\meteor-promise\promise_server.js:218
      throw error;
      ^

Error: isopacket load failed?
    at loadIsopacketFromDisk (C:\tools\tool-env\isopackets.js:320:11)
    at C:\tools\tool-env\isopackets.js:113:9
    at loadIsopackage (C:\tools\tool-env\isopackets.js:104:21)
    at ProjectContext._buildResolver (C:\tools\project-context.js:817:34)
    <snip>

Full error message, SO won't let me post it all here
Inside C:\Users\x\AppData\Local\.meteor\packages\meteor-tool\1.10.2\mt-os.windows.x86_64\tools\fs\ there is no folder tools\fs\ and no files.ts - there is files.js. But I don't get why there's a line specified in a file that doesn't exist
Showing missing directories


text:
Q: How to change all lines consisting of one "0" character to something else? I have a file with lines similar to the below:
0
0.1
0.0002
0
0.30

I want to replace the lines with a single 0 to something else like 0.0001. For the lines with a decimal and digits after, I don't want to alter them.
I've tried the below variations of sed, but it either does nothing, or it changes all the zeros, even ones after the decimals:
sed 's/0/x/g' file
sed 's/^0/x/g' file
sed 's/0^/x/g' file
sed 's/^0^/x/g' file
sed 's/"0"/x/g' file
sed 's/[0]/x/g' file

It seems sed cannot handle a single 0 character. Also, I do not have the replace command on my system. What else can I do?

A: Using Awk:
awk '{gsub(/^0$/,0.0001)};1' file

A: To replace a single 0 on a line:
sed 's/^0$/x/'

^ matches the beginning of the line
$ matches the end of a line
So the above command matches the beginning of a line, followed by 0, followed by the end of the line.


text:
Q: How much does supply and demand affect global market prices? I heard exporting large volumes of a good will lower prices over time. I think I've seen prices change, but haven't paid much attention to them. My city exports a lot of TVs and I was wondering how low the price can go.

A: The global market will be server wide[1]; with prices coming to some sort of equilibrium (I believe there will still be price caps and floors[2]). As such I expect the price of TVs to drop a bit -- however they are used in the construction of the Arcology great work so maybe it won't be that bad. But TVs won't be the money making machine that it is now...
[1] currently disabled.
[2] their existence is covered in SimCity preview articles from ~December but these, of course, are short on details and long on fluff.
SimCity will have a global market that sets shared prices for commodities. How malleable or open to manipulation or catastrophe will the world market be? Can the price of oil crash and create a shortage?
Librande: Yes and no. We didn't want to make an EVE system or a World of Warcraft auction system where the players have control of the prices in that way. Those economies tend to spiral out of control over time, since money is an infinite resource. You just start a new city and start making new money. The way the global market is set up, we have bounds on the high and low prices. We won't allow the price to go outside those bounds. There's a little bit of price-fixing on that side to keep the game playable. Then we tuned a lot of the commodities so if the price maxes out, you probably don't want to be working with those resources.
Here's a specific example: I'm drilling oil out of the ground and converting it into fuel. The more fuel I sell, it's going to start to lower the price on the global market. But my single contribution to that lowering is a fraction of a percent. If everybody on the server starts dumping fuel and nobody's selling oil, then you'll start to see the price of fuel drop down and the price of oil rises up. The idea is that encourages people to say, "Well, I'll just start selling the oil and get out of fuel now." Then that causes the opposite thing to happen. From a design point of view, the idea is that we didn't just want someone to write a guide, like, "Here's the FAQ. You should always make this and sell that." If anybody thinks they've found a flaw like that in the game and says, "You should do this!" and everyone starts following them, that actually changes the whole price structure. That invalidates that technique while something gets boosted on the other end.


text:
Q: RxJava : fromIterable is not emitting all the items I was trying out a simple code with fromIterable and flatMap operators. I'm just mapping a stream of long values to a stream of Result in my code. Nothing else
Here's my code.
I have an empty class
    class Result {
        @Override
        public String toString() {
            return "result";
        }
    }

And a function
    public Observable<Result> getResults(List<Long> requests) {
        return Observable.fromIterable(requests)
                .flatMap( aLong -> {
                    Result[] items = {new Result(), new Result()};
                    return Observable.fromIterable(Arrays.asList(items));
                });
    }

And I subscribe to this as follows
     List<Long> ids = new ArrayList<>(Arrays.asList(1L, 2L, 3L));

     getResults(ids)
    .subscribe(new DisposableObserver<Result>() {
        @Override
        public void onNext(Result item) {
            Log.d(TAG, "onNext: " + item);
        }

        @Override
        public void onComplete() {
            Log.d(TAG, "onCompleted: ");
        }

        @Override
        public void onError(Throwable e) {
            Log.e(TAG, "onError: " + e.getMessage());
        }
    });

My expected output is
    LOG: onNext: result
    LOG: onNext: result
    LOG: onNext: result
    LOG: onNext: result
    LOG: onNext: result
    LOG: onNext: result
    LOG: onCompleted:

For each emission of fromIterable , the flatMap expected to return a stream with 2 values, so total 6 times onNext and then onComplete
But what I'm getting is
    LOG: onNext: result
    LOG: onNext: result
    LOG: onCompleted:

Only 2 times onNext is triggering and then it completes. Where did the remaining 4 values go?
But the strange thing is , I added a Log to the doOnNext of fromIterable in my getResults function  as follows
    public Observable<Result> getResults(List<Long> requests) {
        return Observable.fromIterable(requests)
                .doOnNext(i -> Log.d(TAG, "fromIterable emitted " + i))
                .flatMap(aLong -> {
                    Result[] items = {new Result(), new Result()};
                    return Observable.fromIterable(Arrays.asList(items));
                });
    }

Now it is emitting all the values!!!!  Here's the output
    LOG: fromIterable emitted 1
    LOG: onNext: result
    LOG: onNext: result
    LOG: fromIterable emitted 2
    LOG: onNext: result
    LOG: onNext: result
    LOG: fromIterable emitted 3
    LOG: onNext: result
    LOG: onNext: result
    LOG: onCompleted:

Whats happenning here? What change did the onNext make to the chain to emit all the values?

A: as explained by @akarnokd, you are logging similar text within very short amount. Logging should be unique in your case,
List<Long> ids = new ArrayList<>(Arrays.asList(1L, 2L, 3L));

    getResults(ids)
            .subscribe(new DisposableObserver<Result>() {
                @Override
                public void onNext(Object item) {
                    Log.d(TAG, "onNext: called at " + System.currentTimeMillis());
                }

                @Override
                public void onComplete() {
                    Log.d(TAG, "onCompleted: ");
                }

                @Override
                public void onError(Throwable e) {
                    Log.e(TAG, "onError: " + e.getMessage());
                }
            });

or mention in your observable similarly
  ...
  .doOnNext(i -> Log.d(TAG, "fromIterable emitted " + i))
  ...


text:
Q: How to handle third party functions or threads that has hung in Delphi? I use a lot of components in my Delphi 7 Service application, Indy, Synapse, Zeolibs, etc.
My application is generally stable, I use Eurekalog 6 to capture exceptions, but in rare situations, some threads hang because a 3rd party function it calls has hung, e.g. Indy gets stuck when trying to send email.
In many cases, the application that hung are my customer place, I've no access to their computer, so it is not possible for me to do a live debug. My application requires high availability so even if it hangs once a year, that is not acceptable to my users.
I am now looking for the best way to deal with such a situation where debugging is not feasible but I will still need the application recover by itself.  Is it possible for a thread to terminate if a function it calls hangs?  Alternatively, I can also restart the entire service when that happens.  How about a Watchdog and what is the best way to implement it?  Thanks.

A: Your question is rather too vague. If you don't know which of the various components you're using you wish to blame, then you have zero hope of fixing it.  The most likely thing is you're doing something wrong, or that you don't understand how these components work.  I very much doubt that it's purely a bug in the components themselves, but hey, either way it's all on you to find what's having a problem, and your job to fix it.
A deadlock that you've created, or a deep process corruption issue, that is happening, may prevent MadExcept from giving you any information, but it's worth trying.
To find out which one is freezing, if any at all, then the madexcept comment is the best suggestion yet. It will time-out (after a configurable # of seconds) and raise an artificial exception for you, interrupting your hung process. This works for user code, and for places where the thread is blocked in a Win32 or kernel function.   For example, it's possible that you've set up Indy for infinite timeouts, as that's the default these days in Indy 10, and that what you're experiencing is a timeout related freeze, where network activity that you expected to complete but which never will complete, is causing your program to "hang".   The cure here is to change your timeouts.
However, until you figure out WHERE the problem is, I doubt you'll be able to fix it. And so, for that, again, Marcus is right, you should be looking into madExcept.  I can't live without it.
Secondly, you should really be adding trace logic to your program, so you know where it's going and what it was doing just before it had a problem.  If you really need help doing that, you could try CodeSite, from Raize. Personally I find that OutputDebugString combined with the free Microsoft DebugView utility (formerly from SysInternals) tool is more than enough to debug such problems on a client computer.
Any program with background threads that does not have trace logging, is a badly designed program. Heck, any non-trivial single threaded application that might ever fail or have problems, needs trace logging.
Logging is always going to help, even when MadExcept or other exception tools don't.  Trace-Logging is usually a roll-your-own solution, although CodeSite is also quite popular.

A: I think you are being rather defeatist. Find and fix the bugs. It might be tricky, but it's the right solution.
Killing threads whose behviour you don't understand is never the solution. If you start killing threads you'll likely make things worse. That can lead to other runtime errors, deadlock and so on. Once you start killing threads you've lost control.
Now, it would be safe to kill the process (rather than a specific thread) and rely on a watchdog service to restart the process. But that's a really dire solution.
You should certainly use a tool like madExcept, EurekaLog etc. to debug unexpected exceptions. I see you are already using EurekaLog - that's good.
Deadlocks (it sounds like you have deadlock) can be more tricky to chase down. One good way to debug a deadlock is to get your client to produce a crash dump (e.g. from Process Explorer). Then debug it in WinDbg using map2dbg to produce symbolic stack traces. That will tell you which threads are blocking and that reveals the deadlock. And then fix the bugs.
For more details on this deadlock debugging technique see here: http://capnbry.net/blog/?p=18
I'm not familiar with EurekaLog since I use madExcept, but I would expect EurekaLog has a facility to allow generation of thread stack traces for a hung process. If so then that would most likely be the best approach for you.


text:
Q: I am running out of SMTP Relays thrice in a week on my VPS running CentOS 6.6 I have a VPS purchased from godaddy runs CentOS 6.6 and I have more than 150 Joomla websites hosted onto this. I have maximum smtp relays alloted from godaddy that is 2000 for now. I am running out of SMTP relays due to some php scripts sending out emails alot and my email queue has lacks of emails to be sent. Earlier, I was also receiving many emails to the address like abc@xyz.com where xyz.com is hosted on my server but abc is not a user/email. In this case my server was sending bounce backs which was utilizing my relays. I have resolved this issue by rejecting such emails for which user is not availabel at the time of smtp check. This solved the problem a bit. But now, everyday a new php file send lot of emails out and utilizes all of my smtp relays. I delete such files everytime I detect this issue but there is not any permanant solution I got yet. Anybody please help me stop this at server level, not for particular website.

A: You can resolve this issues by disabling php mail function on your server and For the site mail, you will have to use SMTP authentication for your all site so that no one can send mail using any scripts.


text:
Q: Parametric Volume, volume analogue of parametric surface? Is it possible to have a parametric volume? Is it possible to have a parametric volume in $\mathbb{R}^3$, $V:\mathbb{R}^3\rightarrow\mathbb{R}^3$, where $V$ is some function $V(x,y,z) = A(x,y,z)\hat{i}  + B(x,y,z)\hat{j} + C(x,y,z)\hat{k}$ ? In a parametric curve a curve is traced using the end point of the vector starting from the origin. In a parametric surface, there are two parameters which trace out the surface, so why not there be a parametric volume, where three parameters trace out the volume. I know it looks exactly like a vector field where every point in space gives you a unique vector, are the two perhaps somehow analogous, or is my entire thinking wrong and you cannot parametise a volume in this manor.

A: Sure. And if the mapping is regular in the sense that the Jacobian determinant of $A,B,C$ is non-zero, what you have is an alternative coordinate system in your region. You can also have a three-dimensional manifold in a space of higher dimension.


text:
Q: Javascript AJAX call, no server side? I have Javascript file where I m trying to make a AJAX call and supposed to get JSON data.
  $.ajax({
        type: "POST",
        url: "er.js", // this is the same file
        data: {
            action: 'analyzePost',
            c: c,
            title: title,
            content: content,
            audience: audience
        },
        dataType: "json",
  "success": function(result) {
     console.log("OK: ", result);
     r = result;
   },
   "error": function(result) {
     console.error("!!!!!!ERROR!!!!!!!!!:", result);
   },
   "async": false
    });

I have a function in same file that look like this.
function showAnalyzePost(c, title, content, audience){
    return analyzePost(c, $("#oauth_token").val(), $("#oauth_token_secret").val(), title, content, audience);
}

I did worked with AJAX before but that involved PHP as well. In this case there is no server side script. Maybe I have to create .json file or maybe use getJson but I am not sure how to do that.
Problem: AJAX is not even being triggered. It does not throw error nor return good result.
Please ask question if I did not explain this properly.
Can someone guide me here... Thanks

A: AJAX is for client-server interaction. If you are staying on the client side, just call your js function with the appropriate values for parameters.
var r = analyzePost(c, title, content, audience);


text:
Q: c++ 11 Trailing return type with decltype does not work as expected Why this works "as expected"?
My understanding is that this should not work:
template <class T, class U>
auto x(T a, U b) -> decltype(a<b ? a:b) {
    return a > b ? a : b;
}

int main() {
    cout << x<long, double>(1, 2.01) << endl;
    cout << x<long, double>(5, 2.01) << endl;

}

I have tried some other combinations such as:
template <class T, class U>
auto x(T a, U b) -> decltype(a<b ? a:a) {
    return a > b ? a : b;
}

This way it does not compile with error Actually the second combination fails with
compile time error:  Error C2440 'return': cannot convert from 'U' to 'T &'

which is expected. My understanding is that the first function also should fail with the same error, while it works fine.

A: It doesn't matter what the condition with the ?: operator is. The result type is calculated as a common type of the second and third operand. Here is part of how the common type and the value category of the ?: operator are calculated, see cppreference.com for the full details:
If the second and third operand are lvalues of the same type, then the result type will be a lvalue of that type.
If the types are unrelated lvalues, there are some more complex rules to determine the common type, but the result will be a prvalue, not a lvalue. In particular if the two types are arithmetic types such as double and long, then the usual arithmetic conversions are applied to obtain a common type. In the case of long and double that common type would be double. This is the same type calculation that would be done if you e.g. tried to add two different arithmetic type with +, hence the name usual arithmetic conversions.
Therefore decltype(a<b ? a:b) will be a reference type if a and b have the same type and otherwise it will not be a reference type.
This is why the function compiles. The common type is always such that both input types can be converted to it. It is also why the function has undefined behavior if the types are equal, because then decltype gives a reference and so you are going to return a reference to one of the function parameters.
decltype(a<b ? a:a) doesn't work with different types, because the common type of a and a is, as described above, a reference of the type of a. If b then has a different unrelated type, the result of a > b ? a : b will be a prvalue which cannot be bound to a lvalue reference.

A: You may think that
template <class T, class U>
auto x(T a, U b) -> decltype(a < b ? a : b) {
    return a > b ? a : b;
}

std::cout << x<long, double>(1, 2.01) << std::endl;
std::cout << x<long, double>(5, 2.01) << std::endl;

won't compile because trailing return type decltype(a < b ? a : b), i.e. inner expression a < b ? a : b is not the same as the return expression a > b ? a : b but this is perfectly legal because the return type becomes whatever type comes after the ->.
Now, why the following code is not compiled successfully?
template <class T, class U>
auto x(T a, U b) -> decltype(a < b ? a : a) {
    return a > b ? a : b;
}

std::cout << x<long, double>(1, 2.01) << std::endl;
std::cout << x<long, double>(5, 2.01) << std::endl;

It is because you need to remove the reference from the trailing return type, like this:
#include <type_traits>

template <class T, class U>
auto x(T a, U b) -> typename std::remove_reference<decltype(a < b ? a : a)>::type {
    return (a > b ? a : b);
}

Now it compiles successfully. Check here
The reason why the second example does not compile without std::remove_reference is because both types that are part of ternary operator are glvalues and here is said that:

4) If E2 and E3 are glvalues of the same type and the same value
  category, then the result has the same type and value category

so the result of a < b ? a : a is a glvalue. That's why you need to remove the reference. And the result of a < b ? a : b is a prvalue and, therefore, you don't need to remove the reference.


text:
Q: Rails STI renaming objects type, StandardError - The single-table inheritance mechanism failed to locate the subclass I am trying to run a migration that will rename an objects type. I am using Ruby 1.9.3-p327 Rails 3.2.18.
We have a Scorecards model that has many different types, we have used STI to distinguish between the types. Only one of the types of scorecard was named to abstractly. I renamed the model and then fixed all the relationships that belong with it in the system. only now running the migration to change its type is braking. The Type is is model name.
This is the Migration that i am using. it finds all scorecards with that specific type and then updates their types.
class UpdateFscScorecardsToShortTermFinancial < ActiveRecord::Migration
  def up
    Scorecard.where(type: 'FinancialGenericAlphaScorecard').each do |scorecard|
      scorecard.update_column(:type, 'FinancialShortTermGenericAlphaScorecard')
    end
  end

  def down
    Scorecard.where(type: 'FinancialShortTermGenericAlphaScorecard').each do |scorecard|
      scorecard.update_column(:type, 'FinancialGenericAlphaScorecard')
    end
  end
end

when migrating i get this error.
==  UpdateFscScorecardsToShortTermFinancial: migrating ========================
rake aborted!
StandardError: An error has occurred, all later migrations canceled:

The single-table inheritance mechanism failed to locate the subclass:
'FinancialGenericAlphaScorecard'. This error is raised because the column
'type' is reserved for storing the class in case of inheritance. Please rename
this column if you didn't intend it to be used for storing the inheritance class or
overwrite Scorecard.inheritance_column to use another column for that information./Users/Nexus/Work/toolkit/db/migrate/20150518133229_update_fsc_scorecards_to_short_term_financial.rb:3:in `up'
Tasks: TOP => db:migrate

I know that the type column is reserved, but i am not changing the column name, i am just changing the type of a scorecard. What is the best practice around doing this? I can see that it is a risky action changing what is in a type column. all the dependencies work, if i was to create a new FinancialShortTermGenericAlphaScorecard, it works fine. only viewing older FinancialGenericAlphaScorecard dont work. hence the fact i need to change its type.


text:
Q: Pandas : Empty dataframe after using concat() I created an empty datafame,drugs:
drugs = pd.DataFrame({'name':[],
                    'value':[]})

after that, I wanted to add data from another data frame to it using a for loop:
for i in range(227,498):
    value = drug_users[drug_users[drug_users.columns[i]] == 1][drug_users.columns[i]].sum() / 10138
    name = drug_users.columns[i]
    d2 = pd.DataFrame({'name':[name],
                    'value':[value]})
    print(d2)
    pd.concat([drugs, d2], ignore_index = True, axis = 0)

but when I take a sample from drugs, I get the error:
ValueError: a must be greater than 0 unless no samples are taken

A: You need to assign the return value from the concat function, I'm afraid it is not an inplace operation.

A: The concat method return a new dataframe instead of changing the current dataframe. You need to assign the return value, e.g.:
drugs = pd.concat([drugs, d2], ignore_index = True, axis = 0)


text:
Q: Laravel 5.4 - Where to change login procedure Using the command php artisan make:auth I 'created' the default authentication scaffolding.
My application, however, needs rights management. I added a column via the migrations for the rights (small int).
Now, when a user logs in, I want to check the rights the user has and redirect according to the rights.
Where is the actual redirect located (in which PHP file)? So that I can edit this procedure.

A: You should look into the LoginController and the RegistrationController. They are based on some traits (with a lot of protected methods you can adapt)


text:
Q: Firechat/Firebase user moderators I have Firechat powered by Firebase running and integrated with my Wordpress database. It works great, but one thing I'm missing are chat moderators / admins.
From what I can tell from looking at the rules.json :
"moderators": {
      ".read": "(auth != null)"
    },
    "suspensions": {
      ".write": "(auth != null) && (root.child('moderators').hasChild(auth.uid))",
      ".read": "(auth != null) && (root.child('moderators').hasChild(auth.uid))"
    }

...and by a repository search, there seems to be some kind of moderator function. However, I can't find a reference to using it anywhere.
Can you help me understand how the moderator system works? Are they able to control all chat rooms or just one? Are they capable of kick, mute, or ban? How can you set a user as "moderator"?

A: Firechat, in its current version, gives 'moderators' a special, right-click context menu on chat messages that includes some kick and ban behaviors. Moderators are defined as any record stored in <root>/moderators/<moderator-user-id>. In other words, add a record with <user-id>:true under /moderators in your Firebase to enable that context menu.


text:
Q: How to change the style of Contents to this when book documentclass is used To meet the requirements of our school, I need the style of contents table like below:
Preface .....................   I
Abstract ....................  II
1 Introduction
1.1 Section 1 ............... (1)
1.2 Section 2 ............... (3)
2 Another Chapter
2.1 Section 1 ............... (6)
2.2 Section 2 ............... (8)
.
.
.
Ack .........................(54)
References ..................(56)
Appendix 1 ..................(58)
Appendix 2 ..................(60)

I tried titlesec, titletoc and tocloft package, but they will change all 'chapter' or 'section'.  The Abstract, Introduction, Ack and Appendix, all use 'chapter', however, I need Abstract has leaders and page number, Introduction has neither leaders nor page number, Ack and Appendix have leaders and page number(and page number in parentheses).
Is there anyway to do this?

A: Unfortunaly there is no MWE in the question, but here is a suggestion using package tocbasic.
\documentclass{book}
\usepackage{blindtext}% only for dummy text

\usepackage{tocbasic}

\DeclareTOCStyleEntry[
  linefill=\tocchapterlinefill,
  entryformat=\normalfont,pagenumberformat=\normalfont,
  beforeskip=0pt plus .2pt% no additional space before chapter entries
]{tocline}{chapter}
\newcommand*\tocchapterlinefill{\TOCLineLeaderFill}
\newcommand*\tocchapterdotson{\def\tocchapterlinefill{\TOCLineLeaderFill}}
\newcommand*\tocchapterdotsoff{\def\tocchapterlinefill{\hfill}}

\usepackage{expl3}
\ExplSyntaxOn
\clist_map_inline:nn
  {chapter,section,subsection,subsubsection,paragraph,subparagraph}
  {\DeclareTOCStyleEntry[indent=0pt,pagenumberbox=\tocpagenumberbox]{tocline}{#1}}
\ExplSyntaxOff

\newcommand*\tocpagenumberbox[1]{\makebox[2.5em][r]{\tocpagenumber{#1}}}
\newcommand*\tocpagenumber[1]{#1}
\newcommand*\tocpagenumberparentheseson{\renewcommand\tocpagenumber[1]{(##1)}}
%\newcommand*\tocpagenumberparenthesesoff{\renewcommand\tocpagenumber[1]{##1}}

\usepackage{xpatch}
\xapptocmd\mainmatter{%
  \addtocontents{toc}{\protect\tocpagenumberparentheseson}%
  \addtocontents{toc}{\protect\tocchapterdotsoff}%
}{}{\mainmatterPatchFailed}
\xapptocmd\backmatter{%
  \addtocontents{toc}{\protect\tocchapterdotson}%
}{}{\backmatterPatchFailed}

\begin{document}
\frontmatter
\pagenumbering{Roman}
\chapter{Preface}
\chapter{Abstract}
\tableofcontents
\mainmatter
\Blinddocument
\Blinddocument
\backmatter
\chapter{Ack}
\end{document}

Result:


text:
Q: Keep the the alert box without dismiss if there is an error This is just an alert box with radio buttons. All are working fine except one thing. That is If there is an error I cannot retain the alert box until the user enters the correct data. According to the doc I have used return false feature. But no luck yet. Any clue?
Note: This is working fine if inputs are text boxes. Here I need radio buttons.
const allApiKeys = await this.apiKeySqliteProvider.getAllApiKeys();
            const alert = this.alertCtrl.create();
            alert.setTitle('Select Api Key');
            forEach(allApiKeys, (apiKey: ApiKey) => {
              alert.addInput({
                type: 'radio',
                label: apiKey.name,
                value: apiKey.key,
                checked: false
              });
            });
            alert.addButton({
              text: 'Cancel',
              role: 'cancel',
              handler: data => {
                this.loading.dismissLoader(loading);
              }
            });
            alert.addButton({
              text: 'OK',
              handler: data => {
                let navTransition = alert.dismiss();
                navTransition.then(() => {
                 if (data == null) {
                    this.showToastProvider.showErrorToast("Invalid API Key");
                    this.loading.dismissLoader(loading);
                    return false;
                  }
                });
                return false;
              }
            });
            alert.present();
          }

A: return false is not the actual problem. You are calling alert.dismiss, that's the issue. If you don't want to hide alert, you should move dismiss code inside else block.
Please change your code to following
 const allApiKeys = await this.apiKeySqliteProvider.getAllApiKeys();
                const alert = this.alertCtrl.create();
                alert.setTitle('Select Api Key');
                forEach(allApiKeys, (apiKey: ApiKey) => {
                  alert.addInput({
                    type: 'radio',
                    label: apiKey.name,
                    value: apiKey.key,
                    checked: false
                  });
                });
                alert.addButton({
                  text: 'Cancel',
                  role: 'cancel',
                  handler: data => {
                    this.loading.dismissLoader(loading);
                  }
                });
                alert.addButton({
                  text: 'OK',
                  handler: data => {
                      if (data == null) {
                        this.showToastProvider.showErrorToast("Invalid API Key");
                        this.loading.dismissLoader(loading);
                        return false;
                      }

                      // you don't need else here as by default it will hide alert
                  }
                });
                alert.present();
              }


text:
Q: Xcode/Git: Can't see old version in source control I've just followed a basic tutorial on how to use Git in Xcode. I've made a new project with Git initialised from when I created it. I then made some changes and after hitting commit, instead of getting the old and the new files side by side I'm seeing nothing on the right hand side, just says 'File is unversioned'. I definitely have Git turned on - I got the Modified tag for example as I made changes to a couple of files.
Any ideas why this is so?


text:
Q: iOS phone, notifications in background it's not vibrate? I develop flutter project and I use FCM and Local Notification I have issues when iOS phone in background it's not vibrate.
my BackgroundHandler:
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  await setupFlutterNotifications();

  showFlutterNotification(message);
}

I use
await Vibration.vibrate(duration: 500);

to vibration.your text

A: In my opine you can't because notification vibrate is depends on phone settings so you can't do that even forcefully if notification vibration disable from phone settings.
for more details check this link it may helpful.


text:
Q: How to safely unwrap optional variables in dart? I couldn't find a way to safely unwrap an optional variable as we do in swift
var myString: String?
if let myString = myString {
  print(myString) // myString is a string
}

or in Kotlin
var myString: String?
if (myString != null) {
   print(myString) // myString is not null
}

// or
myString?.let {
   print(it) // myString is not null
}

In Dart I'm having to do the following, which doesn't look good:
String? myString;
if (myString != null) {
   print(myString); // myString still an optional
   print(myString!); // myString is now a String! (because of the force unwrap)
}

Is there a way to safely unwrap in a clean way like other null-safety languages? Or we have to always force unwrap variables after a null-check?

A: Your Dart example seems incomplete but it is difficult to say what is wrong without more context. If myString is a local variabel it will be promoted. You can see this example:
void main(){
  myMethod(null); // NULL VALUE
  myMethod('Some text'); // Non-null value: Some text
}

void myMethod(String? string) {
  if (string != null) {
    printWithoutNull(string);
  } else {
    print('NULL VALUE');
  }
}

// Method which does not allow null as input
void printWithoutNull(String string) => print('Non-null value: $string');

It is a different story if we are talking about class variables. You can see more about that problem here: Dart null safety doesn't work with class fields
A solution to that problem is to copy the class variable into a local variable in your method and then promote the local variable with a null check.
In general, I will recommend reading the articles on the official Dart website about null safety: https://dart.dev/null-safety

A: void main(List<String> args) {
  var x;
  if (x != null) {
    // Since you've already checked, the following statement won't give an error.
    print(x!);
  } else {
    print('ERROR');
  }
}

I guess this is how you can safely unwrap optionals or variables that can either be null in Dart.


text:
Q: Spotify API giving CORS error even after adding auth token to get artist's playlist Accessing artist's playlist using Spotify's API requires auth token. I am using the method shown in this link but I am getting following error: "Request header field 0 is not allowed by Access-Control-Allow-Headers in preflight response."
Platform: Ubuntu ; Browser: Google Chrome
Update: My Angular service to retrieve artist's playlist.
import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class SpotifyService {

  private searchUrl: string;
  private authToken: string= "My auth token here";

  constructor( private _http: Http ) { }

  get( query: string, type= "artist" ){

    let headers = new Headers([
      { 'Authorization': 'Bearer ' + this.authToken },
      { 'Accept': 'application/json' }
    ]); // ... Set content type to JSON
    let options = new RequestOptions({ headers: headers }); // Create a request option
    this.searchUrl = "https://api.spotify.com/v1/search?q=" + query + "&type=artist&market=US";

    return this._http.get( this.searchUrl, options )
          .map( response=> response.json() );
   }

}

Update2: Adding Request and Response Headers:
Request Headers
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:0,1,2
Access-Control-Request-Method:GET
Connection:keep-alive
DNT:1
Host:api.spotify.com
Origin:http://localhost:4200
Referer:http://localhost:4200/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Accept, Authorization, Origin, Content-Type
Access-Control-Allow-Methods:GET, POST, OPTIONS, PUT, DELETE
Access-Control-Allow-Origin:*
Access-Control-Max-Age:604800
Connection:keep-alive
Content-Length:0
Date:Sun, 06 Aug 2017 03:30:56 GMT
Keep-Alive:timeout=600
Server:nginx
Strict-Transport-Security:max-age=31536000;
X-Content-Type-Options:nosniff

A: The HTTP headers are not being passed to your request.
Angular's Headers constructor expects an object, not an array.
Your code should look like:
let headers = new Headers({
    'Authorization': 'Bearer ' + this.authToken,
    'Accept': 'application/json'
}); // ... Set content type to JSON


text:
Q: How to implement several independent devices on one FPGA? I need implement 2 or more independent device on FPGA (Altera Cyclone III). For example: two counters by one and by two. How I do this make? And how to use this devices parallel? Thanks everybody!

A: Everything happens in parallel on an FPGA. Heres an example solution in verilog
Counter Module
module counter #(
    parameter pCntNum =1
    ) (
    input iClk,
    input iRst,

    output reg [7:0] oCnt
);
always @ (posedge iClk)
    if (iRst) begin
        oCnt <=0;
    end else begin
        oCnt <= oCnt +pCntNum;
    end
endmodule

Top module
module top (
    input iClk,
    input iRst,

    output [7:0] oCntBy1,
    output [7:0] oCntBy2
);

    //Instantiate count by 1 module
    counter #(
        .pCntNum(1)
    )counter_by_1_inst(
        .iClk(iClk),
        .iRst(iRst),
        .oCnt(oCntBy1)
    );

    //Instantiate count by 2 module
    counter #(
        .pCntNum(2)
    )counter_by_2_inst(
        .iClk(iClk),
        .iRst(iRst),
        .oCnt(oCntBy2)
    );
endmodule

There are many many ways to do this, however I gave a solution which I think best exemplifies what you are asking.
EDIT: I just saw the tag for VHDL and not Verilog. The same approach and mechanisms apply to a VHDL solution,however Quartus accepts both Verilog and VHDL source files (You can even have a code base with both). With a simple VHDL tutorial you will be able to create a solution equivalent to the Verilog one I wrote if need be.


text:
Q: Не могу подключить шрифт Montserrat к проекту. В чем проблема? <!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="css/style.css">

Lorem Ipsum является текст-заполнитель обычно используется в графических, печать и издательской индустрии для предварительного просмотра макета и визуальных макетах.

* {
  /*правильное отображение элементов с учетом всех марджинов и падингов. в начале очистим, чтобы задать потом*/
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

@font-face{
    font-family: "Montserrat";
  src: url(fonts/Montserrat-Italic.ttf) format("truetype");
}

.container {
  width: 100%;
  /*если нет сетки, то в фигме можно посмотреть выделяя от лого до конца элемента навигационного меню*/
  margin: 0 auto;
}

.paragraph{
    font-family: "Montserrat";
}


text:
Q: Should I use Boot-Repair if I can see Grub? I have a Dell XPS 9550 (with an NVIDIA graphics card) on which I had been happily been dual-booting Windows 10 and Ubuntu 18 LTS before I tried to upgrade to Ubuntu 20 LTS last month.  The upgrade seemed to complete successfully, but since then I can only boot into my Windows 10 instance.  GRUB loads, and when I select Ubuntu it simply shows a black screen indefinitely.  If I attempt to load into recovery mode, I freeze at "Loading initial ramdisk...".
For what it is worth, the same thing happens when I attempt to run Ubuntu 20.04 from a USB drive in UEFI mode-- I get a black screen.  If I enable Legacy ROM loading, I can get Ubuntu 20.04 to load on my machine from the USB drive.  My Ubuntu 18.04 USB loads/runs Ubuntu with no problems in UEFI mode.
Things I have tried include:

*

*editing the start script and removing splash and quiet - same result

*editing the start script and adding nomodeset - same result

*editing the start script and adding nouveau.modeset=0 - same result

*Updating my machine's BIOS - same result

Since GRUB is loading, is this a good scenario for running Boot-Repair to see if it resolves my issue?  Or are there better alternatives to try to get my Ubuntu back?


text:
Q: Tomcat Windows Service (Apache Commons procsrv) "The user name or password is incorrect" I've spent 2+ days trying to get this to work and hope somebody might be able to point me in the right direction...
I am trying to run Tomcat 8 on Windows Server 2012 R2 as a service as a specific username.  Due to the complexity of my application I am directly running tomcat8.exe //IS/... instead of using the service.bat script.
When the service runs I get these errors in the commons log:
[2016-05-31 18:00:14] [debug] ( prunsrv.c:1679) [ 3280] Commons Daemon procrun log initialized
[2016-05-31 18:00:14] [info]  ( prunsrv.c:1683) [ 3280] Commons Daemon procrun (1.0.15.0 64-bit) started
[2016-05-31 18:00:14] [info]  ( prunsrv.c:1580) [ 3280] Debugging 'CertAccordServer' service...
[2016-05-31 18:00:14] [debug] ( prunsrv.c:1374) [ 3280] Inside ServiceMain...
[2016-05-31 18:00:14] [debug] ( prunsrv.c:844 ) [ 3280] reportServiceStatusE: 2, 0, 3000, 0
[2016-05-31 18:00:14] [info]  ( prunsrv.c:1127) [ 3280] Starting service...
[2016-05-31 18:00:14] [error] (rprocess.c:497 ) [ 3280] The user name or password is incorrect.
[2016-05-31 18:00:14] [error] ( prunsrv.c:1210) [ 3280] Failed to create process
[2016-05-31 18:00:14] [error] ( prunsrv.c:1210) [ 3280] The user name or password is incorrect.
[2016-05-31 18:00:14] [error] ( prunsrv.c:1536) [ 3280] ServiceStart returned 1
[2016-05-31 18:00:14] [error] ( prunsrv.c:1536) [ 3280] The user name or password is incorrect.
[2016-05-31 18:00:14] [debug] ( prunsrv.c:844 ) [ 3280] reportServiceStatusE: 1, 1066, 0, 1
[2016-05-31 18:00:14] [info]  ( prunsrv.c:1582) [ 3280] Debug service finished with exit code 1
[2016-05-31 18:00:14] [error] ( prunsrv.c:1755) [ 3280] Commons Daemon procrun failed with exit value: 3 (Failed to run service as console application)
[2016-05-31 18:00:14] [error] ( prunsrv.c:1755) [ 3280] The user name or password is incorrect.

Here is the full command I use to add the service:
./tomcat8.exe \
  //IS//MyServer \
 --LogLevel Debug \
  --Description "My service info" \
  --DisplayName "My Server" \
  --Install 'C:\Program Files\MyServer\tomcat\bin\tomcat8.exe' \
  --LogPath 'C:\ProgramData\MyServer\tomcat\logs' \
  --ServiceUser 'myuser@contoso.com' \
  --ServicePassword test123 \
  --StdOutput auto \
  --StdError auto \
  --StartImage "C:\Program Files\MyServer\java\bin\java.exe" \
  --Startup auto \
  --StartMode exe \
  --StopMode exe \
  --StartParams start \
  --StopParams stop \
  --StartClass org.apache.catalina.startup.Bootstrap \
  --StopClass org.apache.catalina.startup.Bootstrap \
  --JvmOptions "-Dcmb.productdir=C:\Program Files\MyServer;-Dcmb.datadir=C:\ProgramData\MyServer;-Dcatalina.home=C:\Program Files\MyServer\tomcat;-Dcatalina.base=C:\ProgramData\MyServer\tomcat;-Djava.endorsed.dirs=C:\Program Files\MyServer\tomcat\endorsed;-Djava.io.tmpdir=C:\ProgramData\MyServer\tomcat\temp;-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager;-Djava.util.logging.config.file=C:\ProgramData\MyServer\tomcat\conf\logging.properties" \
  --JvmMs 256m \
  --JvmMx 1024m \
  --Classpath "C:\Program Files\MyServer\tomcat\bin\bootstrap.jar;C:\Program Files\MyServer\tomcat\bin\tomcat-juli.jar;C:\ProgramData\MyServer\resource;C:\Program Files\MyServer\resource"

In place of --ServiceUser and --ServicePassword I've also tried --User and --Password.  The failure is the same.
When I use --ServiceUser and go into Windows Services, find MyServer -> Properties -> LogOn -> This Account shows myuser@contoso.com.  When I use --User the properties panel has This Account as blank and Local System selected.
The myuser@contoso.com is an AD account.  On the local system where tomcat8 service is being added it has a group policy which gives it "Log On as a service".
I also verified that myuser@contoso.com is a valid account and the password matches by running this from a cmd prompt:
runas /noprofile /user:myuser@contoso.com notepad
Enter the password for myuser@contoso.com: test123

When I look at the Apache Commons procsrv C code I found this section which appears to be where the "Failed to create process" and then "The user name or password is incorrect" errors are triggered:
  if (!LogonUserW(szUsername,
                    NULL,
                    szPassword,
                    bLogonAsService ? LOGON32_LOGON_SERVICE : LOGON32_LOGON_NETWORK,
                    LOGON32_PROVIDER_DEFAULT,
                    &hUser)) {
        /* Logon Failed */
        apxLogWrite(APXLOG_MARK_SYSERR);
        return NULL;
    }

I wrote a simple C program with the above code and verified that if szPassword is NULL or not a match for the AD password for myuser@contoso.com I get "The user name or password is incorrect".
I can't think of anything else to try.  I'm stuck. :(

A: Looking at the Apache Commons Daemon code, I see that the only time that Tomcat actually needs the user details is when it's starting as a separate executable - i.e. when you have installed it as -StartMode exe.
Looking at the way that tomcat is normally installed in service.bat, I see that this uses the JNI form of invocation - i.e. -StartMode jvm.  This will not go through the problematic path and so should avoid your user/password problem.
Alternatively, if you actually need Tomcat to run as a separate executable...  You can see in the same Apache Commons code linked above that it gets all its data from a combination of the command-line and the Windows Registry.  Since you have installed your service with no command-line parameters, it will try to find the user and password in the registry.  In addition, since you have not specified the User or Password on installation, it won't have saved them off to the registry either.  It is therefore pulling in empty values.
So, you have two possible ways that you can resolve this problem:

*

*Start up (and stop) in JVM mode, using -StartMode jvm when you install the service.

*Specify both forms of User and Password when installing your service.  This should put the extra data into the Registry and so make it available when the service tries to start.

A: You used an incorrect parameter name for your username and password.
--ServiceUser 'myuser@contoso.com'  --ServicePassword
test123
It should be:
--User 'myuser@contoso.com'
--Password test123
OR
Try this https://superuser.com/a/842867

A: When entering commands, you should do so as Administrator. E.g. from Windows start menu, type in cmd, right click on the cmd.exe or Command Prompt it gives you, and select Run as administrator.
Install TomcatN as a service:
Just run tomcat's c:\path\to\TomcatN\bin\service.bat and give it a service name to use, i.e. Tomcat8. Or,
sc Create TomcatN binPath= "c:\path\to\TomcatN\bin\tomcatN.exe" displayName= "Apache Tomcat N"

Set the service to run as a specific user:
Most of the time you don't need this. But sometimes you need to access the Windows network as a registered user. For example, if you are taking advantage of some Active Directory functionality. It might work to use the following:
C:\path\to\tomcatN\bin\service.bat install TomcatN --user=George --password=abc123

But probably not. You can configure the service manually instead.
Manually configure the service to use a specific username and password:
From the Windows command prompt, you can use the services configurator. Some commands of interest:
sc
sc query TomcatN
sc qc TomcatN
sc config TomcatN obj= "MyHostName\George" password= "abc123"

Take care to note the space that comes after the equal signs in that last command.
Ensure the user has permissions:
Enter the gpedit.msc command. In the GUI that appears, navigate to
Local Computer Policy                  | ...
    - Computer Configuration           | ...
        - Windows Settings             | []Log on as a service
            - Security Settings        | ...
                User Rights Assignment | ...

Double-click on Log on as a service and Add User or Group.... Type the shorthand for the username you want the service to use into the field, click Check Names, and press OK.
Confirm that TomcatN is running as intended:
You can use the following commands to start, stop, and check the status of the service:
net start TomcatN
net stop TomcatN
sc query TomcatN

Checking that the login works as intended
Make sure you've started the service running. Open Windows Task Manager and view the Processes tab. Click on Show processes from all users if necessary. TomcatN should be listed, with the username you specified next to it.
Credit goes to @andrewk
Resource Link:

*

*How do I run Tomcat service as a specific user in Windows?

*Run Tomcat Service as Different User on Windows 7


text:
Q: OSMOSIS syntax for extracting buildings out of country.pbf via .polyfile I am new to osmosis and osmfilter did not work with my .poly file. I do not get the syntax working. I like to extract all buildings within a poly file.
I tried just for all objects
C:\Program Files (x86)\osmosis\bin>osmosis --read-pbf file="C:\Users\User\PowerFolders\Masterarbeit\QGIS Data\Projekte\Deutschland\germany_01.pbf"--bounding-polygon file="C:\Users\User\PowerFolders\Masterarbeit\QGIS Data\Projekte\Deutschland\buffer.poly" --write-xml file="C:\Users\User\PowerFolders\Masterarbeit\QGIS Data\Projekte\Deutschland\all.osm"
But even this did not work. How to fix this?
failure message below:


text:
Q: java & threads: interrupted exceptions & how to properly use BlockingQueue's take() method What exactly happens when there is nothing on the queue and a take() is called.  The API says the method will wait but does that mean the CPU spins checking for empty/not empty until an item is on the queue or does it mean that the thread yields and will be awoken by an interrupt?  If it is the case of the former, I would probably want to see if the queue is empty and if it is call thread.yield() to give up processor time.  My question is really do I need to call yield or does some inner mechanism handle that for me?
Secondly, what is the interrupted exception meant for?  If I understand correctly it means that if thread A is executing this method and is waiting for input and another thread B calls threadA.interrupt() then thread A will catch the interrupted exception and presumably pause execution, if it is nice.  Is that the correct way of thinking about it?

A: Note that BlockingQueue is an interface. So what follows is implementation dependent. If you look at the source code for (say) LinkedBlockingQueue, the source for take() calls lockInterruptibly() on a RentrantLock. From the doc for this:

If the lock is not available then the
  current thread becomes disabled for
  thread scheduling purposes and lies
  dormant until one of two things
  happens:
* The lock is acquired by the current thread; or
* Some other thread interrupts the current thread, and interruption of

lock acquisition is supported.

I suspect there's be some wait()/notify() or similar going on. Will it spin the CPU ? No (check via top or similar)
Re. your question on interrupts, the Java Specialist newsletter had a very interesting article on interrupt() and catching/handling the InterruptedException.
Read the article, but essentially if you catch the exception, you reinterrupt:
  try {
        Thread.sleep(1000);
      } catch (InterruptedException ex) {
        Thread.currentThread().interrupt(); // very important
        break;
      }

A: The wait() call does not spin, it typically uses OS services to wait for an event/condition - which puts the thread to sleep until the condition/event is signaled again. No processor time is used while waiting.
You typically get the interrupted exception if the thread is blocking in a wait() call, and another thread calls interrupt() on that blocking thread, just like you said.

A: It is considered a bad practice to call yield() as it cannot ensure niceness - you may call it and the scheduler instantly returns to your thread as it were a no-op. Use timed waits (e.g. wait(1000)) instead.
Interruptions are a safe way to signal a thread that you want something from it - stop processing, wake up and respond to something, etc.
In general, these things depend on your concrete scenarios. Java has some nice features about concurrency which can be more applicable to a situation.


text:
Q: The bind value at index 1 is null, getting data from from asyncstorage in react-native I am triyng to generate buttons, with data from multiple arrays.
One of these arrays is dynamic, and its getting generated at constructor().
Problem is. When i try to navigate to screen, i get an error message saying " the bind value at index 1 is null ". The error does not point to any line inside my code, instead, it says the issue have something to do with sqlite and asyncstorage.
Im not sure why this is happening, but maybe it have something to do with the generatedData state not being initialized correctly.
I dont know what to do to solve this, any help would be appreciatted.
Here is the code:
import React, { Component } from 'react';

import {
  Text,
  View,
  TouchableOpacity,
} from 'react-native';

class DataApp extends Component {
  constructor() {
    super()
    this.state = {
      dataLocalIds: [
        "data1Data",
        "data2Data",
        "data3Data",
        "data4Data",
        "data5Data",
        "data6Data"
      ],
      dataLabel: [
        "[ data 1 ]",
        "[ data 2 ]",
        "[ data 3 ]",
        "[ data 4 ]",
        "[ data 5 ]",
        "[ data 6 ]",
      ],
      generatedData: [],
    }

    this.state.dataLocalIds.map((value, index) => {
      this.data = this.getDatas(value);
    })
  }

  async getDatas(value) {
    try {
      const value = await AsyncStorage.getItem(value).then(val => {
        let jsonInit = {};
        jsonInit[value] = value;
        let newArray = this.state.generatedData;
        newArray.push(jsonInit);
        this.setState(generatedData: newArray);
        return JSON.parse(val)
      });
      return value
    } catch (err) {
      throw err
    }
  }

  renderScreen = () => {
      var myData =  JSON.parse(this.state.generatedData);
      return (
          {this.state.dataLabel.map((item, index) => {
            return(
              <TouchableOpacity onPress={}>
                <Text>{this.state.generatedData[index] === "{}" ? item : "foo: " + generatedData.foo + " / bar: " + generatedData.bar}</Text>
              </TouchableOpacity>
              )
            })}
      );
  }

  render() {
    return (
      this.renderScreen()
    );
  }
}
export default DataApp;

A: i have this problem and it was for that i have sended null value to AsyncStorage.getItem() and when i changed it. it solved.

A: This problem can occur when you are trying to use AsyncStorage before the app has been started/registered.
If it is the case, try moving the code that calls AsyncStorage to a componenDidMount/useEffecthook (you can render a loading/empty view while this logic is being executed).

A: I got the same error however using a library that wraps AsyncStorage. Its called react-native-simple-store. The problem was I was trying to get data from the storage using a variable that wasn't ready yet (it was null/undefined). This variable would be ready only after a certain time after rendering. So what I did is add an if condition, if its null dont do anything, when the state changes and the component re-renders, the variable is ready now so it will enter the if statement and access storage.

A: First you should import {AsyncStorage} from 'react-native'
then you have to define any unique key
const ASYNC_STORAGE_COMMENTS_KEY = 'ANYTHING_UNIQUE_STRING'
and while calling AsyncStorage.setItem your first parameter should be ASYNC_STORAGE_COMMENTS_KEY and second parameter should be you json data with stringify
e.g. AsyncStorage.setItem(ASYNC_STORAGE_COMMENTS_KEY, JSON.stringify(data));
and for fetching
const your_var = await AsyncStorage.getItem(ASYNC_STORAGE_COMMENTS_KEY);


text:
Q: Configuring static analysis or linters for C++ with Bazel I'm teaching myself C++ and working on a small project with Bazel. I'd like to make sure I'm writing safe code and following reasonable best practices, but I'm not sure how to go about doing so. I'm aware of several static analysis tools such as tsan and other analyzers, clang-tidy, or cpplint.
However I'm not sure how I'm supposed to go about setting these tools up with Bazel. Some poking around has found custom-looking solutions such as Drake (see cpplint.bzl) or apollo, but it seems weird to need to write a bunch of custom build toolchain logic in order to make these work. Is there a proper way to set these up?

A: I don't have a great answer yet, and I'm still surprised it's this manual, but I have at least got cpplint.py and clang-tidy working, like so:
cpplint
I added this target to my src/BUILD file (you'll want to configure --filter as needed):
py_test(
    name = "cpplint",
    srcs = ["@google_styleguide//:cpplint/cpplint.py"],
    data = [":all_cpp_files"],
    # Not sure if there's a better way to express the paths to the src/ dir
    # Drake uses the location oparator, but needs to jump through hoops to get the list of targets
    args = ["--root=src", "--linelength=100", "--counting=detailed",
            "--filter=..."] +
        ["src/%s" % f for f in glob(["**/*.cc", "**/*.h"])],
    main = "cpplint.py",
    python_version = "PY2",
)

The @google_styleguide workspace is defined like so:
new_git_repository(
    name = "google_styleguide",
    remote = "https://github.com/google/styleguide",
    commit = "26470f9ccb354ff2f6d098f831271a1833701b28",
    build_file = "@//:google_styleguide.BUILD",
)

clang-tidy
I created a custom shell script that roughly looks like this (you'll need to tune which checks you want to enable/disable):
execution_root=$(bazel info execution_root) || exit

clang-tidy \
  -warnings-as-errors=* \
  -header-filter=src/.* \
  -checks="${checks}" \
  "src/"*.cc \
  -- \
    -I "${execution_root}/external/googletest/googletest/include/" \
    -I "${execution_root}/external/absl/" \
    -I "${execution_root}/external/gsl/include/" \
    -I .

A: I needed to add file //cpplint.BUILD and set visibility for @dimo414 solution to work.
//cpplint.BUILD
package(default_visibility = ["//visibility:public"])

py_binary(
    name = "cpplint",
    srcs = ["cpplint.py"],
)

//WORKSPACE
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
    name = "cpplint_archive",
    build_file = "@//:cpplint.BUILD",
    sha256 = "b2979ff630299293f23c52096e408f2b359e2e26cb5cdf24aed4ce53e4293468",
    strip_prefix = "cpplint-1.2.2",
    url = "https://pypi.python.org/packages/source/c/cpplint/cpplint-1.2.2.tar.gz",
)

Last is Python test target.
//solution/BUILD
py_test(
    name = "solution_cpplint_test",
    srcs = ["@cpplint_archive//:cpplint"],
    args = ["solution/%s" % f for f in glob([
        "**/*.cc",
        "**/*.h",
    ])],
    data = [":solution_filegroup"],
    main = "cpplint.py",
)

To run:
$ bazel test solution_cpplint_test


text:
Q: What determines where the next blocks spawn? In Fractal, as you clear blocks, new blocks spawn across the board;

Is there any reasoning behind where the new blocks spawn? Is it based on the blocks you've just cleared (because in my mind this doesn't appear to be the case). Is this completely random?
What determines where the next blocks spawn?

A: Campaign mode is random:

[...] because your starting field is randomized in campaign mode, you can get everything from a 60 points head start to an unsolvable mess.
http://steamcommunity.com/profiles/76561197970582726/recommended/61310/

Puzzle mode is not random:

In the campaign you get to play through 30 levels of randomly generated fields with given conditions, like limited turns or several colours. Goal is to get enough tiles cleared in a given amount of turns to proceed.
In the puzzle mode you have a limited amount of turns, where you get to fulfill puzzles or given conditions in order to unlock harder and longer ones. The fields are not randomly generated.
http://steamcommunity.com/id/Foxy_Opa/recommended/61310/


text:
Q: how to get the .tsr file in QTP We all know that the .tsr file stores the information of the object repository, and We can load the file to an ObjectRepositoryUtil Object in VBS, then we can do a lot through this object.
But how can I capture all the widgets in a window and stores into the .tsr file using VBS?
I mean when we do the following in the QTP GUI:
Resources->Object Repository Manager->Object->Add Object->
"CLICK THE WINDOW WE WANT TO CAPTURE"->File->Save

we actually get the .tsr file of the window and all its components we want to capture.
But how can I do this in VBS, does it have any API?
I look up the document called ObjectRepositoryUtil and find the method GetAllObjects, but it is just not the same thing.
Could anyone solve my problem ? I would really appreciate it.
Thank you.

A: I'm not sure why you want to automate creating an object repository. Usually object repositories are created once and then used for creating tests.
Are you familiar with QTP's Navigate and Learn feature, it allows adding all objects from an application while interacting with the application.

A: If you are looking for a tool or code that can actually mimic the object capturing capability of QTP, outside of QTP - then no such tool/code is available as of now. However code can be written to retrieve the object properties of an application and that I assume you are aware of.


text:
Q: Grafana auto refresh dashboard laytout/panels? When using Grafana, we have it up on some TVs. Does anyone know a way to make it so it'll auto-refresh not just the data, but the actual dashboard if someone adds a panel, changes layout, etc...?
We get real tired of constantly asking for people with remote access to log in and reload the browser. :)

A: In your dash board you can find a option to select refresh time period. In default settings it is set to off. You can select a refresh period and then it will start to auto refresh.
You can find out the refresh option at the right side of the options bar of your dashboard.See image below.

In my case I have set it into 1sec.

A: How about using Chrome extension application? I recommend using this method. I'm using this extension too.
Super Auto Refresh Plus

url : https://chrome.google.com/webstore/detail/super-auto-refresh-plus/globgafddkdlnalejlkcpaefakkhkdoa

Super Auto Refresh Plus is the most user friendly auto refresh and auto reload website extension on the chrome web store market. Super Auto Refresh Plus helps you auto refresh and auto reload any pages and website with selected time interval in just one single click.


text:
Q: Extracting audio from mimeType "video/webm" into "audio/wav" for Speech-to-Text I am using a MediaRecorder with mimeType "video/webm" but would like to upload only the audio of that video with type "audio/wav" to the Google Speech-to-Text service. My current code below returns a file with type "video/x-matroska". How can I solve this problem so that "audio/wav" is used?
I would like to mention that I need the video as well for a separate service so I can't just record only audio initially.
const handleStartCaptureClick = useCallback(() => {
      console.log('handleStartCaptureClick')
      setCapturing(true);
      mediaRecorderRef.current = new MediaRecorder(webcamRef.current.stream, {
        mimeType: "video/webm"
      });

      mediaRecorderRef.current.addEventListener(
        "dataavailable",
        handleDataAvailable
      );

      mediaRecorderRef.current.start();
    }, [webcamRef, setCapturing, mediaRecorderRef]);

const handleDownload = useCallback(() => {
      if (recordedChunks.length) {
        const blob = new Blob(recordedChunks, {
          type: "audio/wav"
        });
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        document.body.appendChild(a);
        a.style = "display: none";
        a.href = url;
        a.download = "react-webcam-stream-capture.wav";
        a.click();
        window.URL.revokeObjectURL(url);
        setRecordedChunks([]);
      }
    }, [recordedChunks]);

A: You can use library like ffmpeg to convert your video/webm to audio/wav.


text:
Q: R reading a tsv file using specific encoding I am trying to read a .tsv (tab-separated value) file into R using a specific encoding.  It's supposedly windows-1252.  And it has a header.
Any suggestions for the code to put it into a data frame?

A: You can also use:
read.delim('thefile.txt', header= T, fileEncoding= "windows-1252")
Simply entering the command into your R consol:
 > read.delim
function (file, header = TRUE, sep = "\t", quote = "\"", dec = ".",
    fill = TRUE, comment.char = "", ...)
read.table(file = file, header = header, sep = sep, quote = quote,
    dec = dec, fill = fill, comment.char = comment.char, ...)

reveals that read.delim is a packaged read.table command that already specifies tabs as your data's separator. read.delim might be more convenient if you're working with a lot of tsv files.
The difference between the two commands is discussed in more detail in this Stack question.

A: df <- read.delim(~/file_directory/file_name.tsv, header = TRUE) will be working fine for single .tsv file, because it is already tab separated, so no need sep = "\t". fileEncoding= "windows-1252" could be used but not necessary.

A: Something like this perhaps?
mydf <- read.table('thefile.txt', header=TRUE, sep="\t", fileEncoding="windows-1252")
str(mydf)


text:
Q: Vim - map last shell command to the key Is there any way to map leader-r to repeat last command sent to bash?
For example, when working with C files I would like to compile and run program from vim without typing :!make or gcc.
I know I can bind specific command to the key but it won't work for other types of files.

A: The :!! command repeats the last :!{cmd}. It's even available in venerable ol' vi.

A: Edit: Ingo Karkat's answer is much better. ... I would delete this post if it wasn't accepted (which means I can't).
Here's one solution. It only searches the last 100 commands, obviously, you could change this number (History indexing starts at -1, which is the last command you typed, so the lower the number, the further is searched).
fun! LastCommand()
        let l:i = -1
        while l:i > -100
                let l:cmd = histget("cmd", l:i)
                if strpart(l:cmd, 0, 1) == "!"
                        let l:i = 1
                        execute l:cmd
                        break
                endif
                let l:i -= 1
        endwhile

        if l:i < 1 | echoerr "No command found" | endif
endfun
nnoremap <Leader>r :call LastCommand()<CR>