text:
Q: Java equivalent for PHP's mysql_real_escape_string() Is there a Java equivalent to PHP's mysql_real_escape_string() ?
This is to escape SQL injection attempts before passing them to Statement.execute().
I know I can use PreparedStatement instead, but let's assume these are one shot statements so preparing them will result in lower performance. I've already changed the code to use PreparedStatement but given the way the existing code was structured, an escape() function would make the code changes much simpler to review and maintain; I prefer easy to maintain code unless there is a compelling reason for the extra complexity. Also PreparedStatements are handled differently by the database, so this could expose us to bugs in the database that we haven't run into before, requiring more testing before releasing to production.
Apache StringEscapeUtils escapeSQL() only escapes single quotes.
Postscript:
There are a lot of subtleties in the environment I inherited that I deliberately avoided in my question.
Two points to consider:
1) Prepared statements are not a panacea and do not provide 100% protection against SQL injection. Some database drivers instantiate parameterised queries using unsafe string concatenation, rather than pre-compiling the query to a binary form. Also, if your SQL relies on stored procedures, you need to ensure the stored procedures do not themselves build queries in unsafe ways.
2) Most prepared statement implementation bind the statement to the database connection the statement was instantiated on. If you are using database connection pooling, you need to be careful to
use the prepared statement reference only with the connection it was prepared on. Some pooling mechanisms do implement this transparently. Otherwise you could pool the prepared statements as well or (simplest but more overhead) create a new prepared statement for every query.

A: Here is some code which achieves what you are looking for. Originally on the Vnet Publishing wiki.
https://web.archive.org/web/20131202082741/http://wiki.vnetpublishing.com/Java_Mysql_Real_Escape_String
/**
  * Mysql Utilities
  *
  * @author Ralph Ritoch <rritoch@gmail.com>
  * @copyright Ralph Ritoch 2011 ALL RIGHTS RESERVED
  * @link http://www.vnetpublishing.com
  *
  */

 package vnet.java.util;

 public class MySQLUtils {

     /**
      * Escape string to protected against SQL Injection
      *
      * You must add a single quote ' around the result of this function for data,
      * or a backtick ` around table and row identifiers.
      * If this function returns null than the result should be changed
      * to "NULL" without any quote or backtick.
      *
      * @param link
      * @param str
      * @return
      * @throws Exception
      */

     public static String mysql_real_escape_string(java.sql.Connection link, String str)
           throws Exception
     {
         if (str == null) {
             return null;
         }

         if (str.replaceAll("[a-zA-Z0-9_!@#$%^&*()-=+~.;:,\\Q[\\E\\Q]\\E<>{}\\/? ]","").length() < 1) {
             return str;
         }

         String clean_string = str;
         clean_string = clean_string.replaceAll("\\\\", "\\\\\\\\");
         clean_string = clean_string.replaceAll("\\n","\\\\n");
         clean_string = clean_string.replaceAll("\\r", "\\\\r");
         clean_string = clean_string.replaceAll("\\t", "\\\\t");
         clean_string = clean_string.replaceAll("\\00", "\\\\0");
         clean_string = clean_string.replaceAll("'", "\\\\'");
         clean_string = clean_string.replaceAll("\\\"", "\\\\\"");

         if (clean_string.replaceAll("[a-zA-Z0-9_!@#$%^&*()-=+~.;:,\\Q[\\E\\Q]\\E<>{}\\/?\\\\\"' ]"
           ,"").length() < 1)
         {
             return clean_string;
         }

         java.sql.Statement stmt = link.createStatement();
         String qry = "SELECT QUOTE('"+clean_string+"')";

         stmt.executeQuery(qry);
         java.sql.ResultSet resultSet = stmt.getResultSet();
         resultSet.first();
         String r = resultSet.getString(1);
         return r.substring(1,r.length() - 1);
     }

     /**
      * Escape data to protected against SQL Injection
      *
      * @param link
      * @param str
      * @return
      * @throws Exception
      */

     public static String quote(java.sql.Connection link, String str)
           throws Exception
     {
         if (str == null) {
             return "NULL";
         }
         return "'"+mysql_real_escape_string(link,str)+"'";
     }

     /**
      * Escape identifier to protected against SQL Injection
      *
      * @param link
      * @param str
      * @return
      * @throws Exception
      */

     public static String nameQuote(java.sql.Connection link, String str)
           throws Exception
     {
         if (str == null) {
             return "NULL";
         }
         return "`"+mysql_real_escape_string(link,str)+"`";
     }

 }

A: Do not assume that PreparedStatements are slower. Try it, measure it, and then judge.
PreparedStatements should always be used in preference to Statement, pretty much without exception, especially when SQL injection attacks are what you're trying to avoid.

A: The only sensible way to avoid SQL injection is to use prepared/parameterized statements.
For example the PreparedStatement you are trying to avoid for some reason. If you do one-shot statements, the time to prepare them should be negligible ("one-shot" and "performance-critical" is a contradiction, IMHO). If you do things in a loop, prepared statements even cause performance to increase.

A: org.apache.commons.lang.StringEscapeUtils.class  in commons-lang.jar could solve your problem!

A: As far as I know, there is no "standard" way to do it.
I strongly suggest using prepared statements despite your current concerns. The performance impact is going to be negligible - we have a similar situation with several thousand statements per second - most of them one-shots as well.
The security you gain should be weighed much higher than a performance problem you have not even seen yet. In my opinion this is a clear situation of "Don't optimize prematurely".
In any case should you really find out later that you run into performance problems, make sure that the prepared statements are really the cause by profiling carefully and then look for alternatives. Till then you should save yourself the hassle of trying to get the escaping right.
This is even more important as I infer you are developing some sort of public facing site - internal apps seldom get enough traffic to be concerned about performance anyway.

A: According to Daniel Schneller, there is no standard way to handle PHP's mysql_real_escape_string() in Java
What I did was to chain replaceAll method to handle every aspect that may be necessary to avoid any exception. Here is my sample code:

public void saveExtractedText(String group,String content)
    {
        try {
             content = content.replaceAll("\\", "\\\\")
                     .replaceAll("\n","\\n")
                     .replaceAll("\r", "\\r")
                     .replaceAll("\t", "\\t")
                     .replaceAll("\00", "\\0")
                     .replaceAll("'", "\\'")
                     .replaceAll("\\"", "\\\"");
        state.execute("insert into extractiontext(extractedtext,extractedgroup) values('"+content+"','"+group+"')");
    } catch (Exception e) {
        e.printStackTrace();

    }

A: I would not trust anything else than PreparedStatement to ensure security. But if you need to have a similar workflow when building queries you may use the code below. It uses a PreparedStatement underneath, works like a StringBuilder, adds escape functions and tracks the parameter indexes for you. It can be used like this:
SQLBuilder sqlBuilder = new SQLBuilder("update ").append(dbName).append(".COFFEES ");
sqlBuilder.append("set SALES = ").escapeString(sales);
sqlBuilder.append(", TOTAL = ").escapeInt(total);
sqlBuilder.append("where COF_NAME = ").escapeString(coffeeName);
sqlBuilder.prepareStatement(connection).executeUpdate();

Here's the code:
class SQLBuilder implements Appendable {
    private StringBuilder sqlBuilder;
    private List<Object> values = new ArrayList<>();

    public SQLBuilder() {
        sqlBuilder = new StringBuilder();
    }

    public SQLBuilder(String str)
    {
        sqlBuilder = new StringBuilder(str);
    }

    @Override
    public SQLBuilder append(CharSequence csq)
    {
        sqlBuilder.append(csq);
        return this;
    }

    @Override
    public SQLBuilder append(CharSequence csq, int start, int end)
    {
        sqlBuilder.append(csq, start, end);
        return this;
    }

    @Override
    public SQLBuilder append(char c)
    {
        sqlBuilder.append(c);
        return this;
    }

    // you can add other supported parameter types here...
    public SQLBuilder escapeString(String x)
    {
        protect(x);
        return this;
    }

    public SQLBuilder escapeInt(int x)
    {
        protect(x);
        return this;
    }

    private void escape(Object o)
    {
        sqlBuilder.append('?');
        values.add(o);
    }

    public PreparedStatement prepareStatement(Connection connection)
        throws SQLException
    {
        PreparedStatement preparedStatement =
            connection.prepareStatement(sqlBuilder.toString());
        for (int i = 0; i < values.size(); i++)
        {
            Object value = values.get(i);
            // you can add other supported parameter types here...
            if (value instanceof String)
                preparedStatement.setString(i + 1, (String) value);
            else if (value instanceof Integer)
                preparedStatement.setInt(i + 1, (Integer) value);
        }
        return preparedStatement;
    }

    @Override
    public String toString()
    {
        return "SQLBuilder: " + sqlBuilder.toString();
    }
}


text: Q: press the button continuously doesn't work after running macro with cnee When I play a recorded macro with cnee, pressing a key continuously doesn't work anymore until the next system start. Is this a known problem?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sharing Google Spreadsheet with C# and REST Ii'm trying to share a Google Spreadsheet using C#. Because the Google Data 3.0 API hasn't been ported to C# yet, I've been trying to interact with their RESTful web service. I haven't worked with REST before.
Google asks for the following:
POST /feeds/default/private/full/<resource_id>/acl HTTP/1.1
Host: docs.google.com
GData-Version: 3.0
Authorization: <your authorization header here>

 <entry xmlns="http://www.w3.org/2005/Atom" xmlns:gAcl='http://schemas.google.com/acl/2007'>
  <category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/acl/2007#accessRule'/>
  <gAcl:role value='writer'/>
  <gAcl:scope type='user' value='new_writer@example.com'/>
</entry>

I'm using the code below to try to access the web service, but it's not working for me. What about this code is incorrect, given the requirements above?
        HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
        entry  = bunchaxml;
        request.Method = "POST";
        request.ContentType = "text/xml";
        request.Headers["GData-Version"] = "3.0";
        request.Credentials = new NetworkCredential(username, password);
        using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
        {
            writer.WriteLine(entry.ToString());
        }
        try
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string sc = response.StatusCode.ToString();
            string scd = response.StatusDescription.ToString();
        }
        catch (Exception e)
        {
            //LogError
        }

A: The credentials you are using are not appropriate for the Google APIs.  You can see how it is done here http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html
Basically, you POST to a login endpoint with a your username and password and they return you a auth token that you can then use in future requests.


text:
Q: How to send magento 2 Order emails through mailchimp? I have mail-chimp account and successfully integrated with my Magento2 website.
I Want to send the order emails via mail-chimp.
Newsletter subscription is working fine and syncing.
Order is not syncing in the MailChimp, it's always empty as below.

But the order email is not sending via mail-chip. Can I send order email only through mail-chimp and other emails through Magento(ex - Customer registration success, Reset password, etc)
How can i send my transnational email via Mailchimp? Is there any possibility?
If i setup the mailchimp all Magento email going through mailchimp like Forget password, Shipment notification, Credit memo etc?


text:
Q: Textbox within a repeater does not return values I am trying to get the value of all the textbox that is inside a repeater, but I can not.
currently the code is like this:
aspx
<asp:UpdatePanel ID="UpdatePanel5" runat="server" UpdateMode="Conditional" EnableViewState="true" RenderMode="Inline" ChildrenAsTriggers="False">
<ContentTemplate>
    <asp:Repeater ID="rptPagsTipoPapel" runat="server">
        <ItemTemplate>

                    <asp:HiddenField ID="hdIdTipoPapelPubEd" runat="server" Value='<%# Eval("IdTipoPapel") %>' />
                    <asp:Label ID="lblTipoPapelPubEd" AssociatedControlID="txtNrPaginasCor" runat="server" Text='<%# Eval("TipoPapel") %>'></asp:Label>

                    <asp:Label ID="Label27" runat="server" Text="Páginas em Cores" AssociatedControlID="txtNrPaginasCor"></asp:Label>
                    (unidades)

                    <asp:TextBox ID="txtNrPaginasCor" runat="server" Width="145" MaxLength="6" AutoPostBack="True"
                        ValidationGroup="vgpCadastroEdicao" OnTextChanged="txtNrPaginasCor_TextChanged" onkeypress="return(ApenasNumero(this,event));"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvNrPaginasCor" runat="server" ControlToValidate="txtNrPaginasCor"
                        ErrorMessage="Páginas em Cores é um campo obrigatório." Display="None" ValidationGroup="valCadastroEdicao">*</asp:RequiredFieldValidator>
                    <asp:CompareValidator ID="cvlNrPaginasCor" runat="server" ErrorMessage="O campo Páginas em Cores é inválido, favor corrigí-lo."
                        ControlToValidate="txtNrPaginasCor" Operator="DataTypeCheck" Type="Integer" Display="None"
                        ValidationGroup="valCadastroEdicao">*</asp:CompareValidator>
                    <asp:CompareValidator ID="cvlGrupoNrPaginasCor" runat="server" ErrorMessage="O campo Páginas em Cores é inválido, favor corrigí-lo."
                        ControlToValidate="txtNrPaginasCor" Operator="DataTypeCheck" Type="Integer" Display="None"
                        ValidationGroup="vgpCadastroEdicao">*</asp:CompareValidator>

                    <asp:Label ID="Label28" runat="server" Text="Páginas em P/B" AssociatedControlID="txtNrPaginasPb"></asp:Label>
                    (unidades)

                    <asp:TextBox ID="txtNrPaginasPb" runat="server" Width="145" MaxLength="6" AutoPostBack="True"
                        ValidationGroup="vgpCadastroEdicao" OnTextChanged="txtNrPaginasPb_TextChanged" onkeypress="return(ApenasNumero(this,event));"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvNrPaginasPb" runat="server" ControlToValidate="txtNrPaginasPb"
                        ErrorMessage="Páginas em P/B é um campo obrigatório." Display="None" ValidationGroup="valCadastroEdicao">*</asp:RequiredFieldValidator>
                    <asp:CompareValidator ID="cvlNrPaginasPb" runat="server" ErrorMessage="O campo Páginas em P/B é inválido, favor corrigí-lo."
                        ControlToValidate="txtNrPaginasPb" Operator="DataTypeCheck" Type="Integer" Display="None"
                        ValidationGroup="valCadastroEdicao">*</asp:CompareValidator>
                    <asp:CompareValidator ID="cvlGrupoNrPaginasPb" runat="server" ErrorMessage="O campo Páginas em P/B é inválido, favor corrigí-lo."
                        ControlToValidate="txtNrPaginasPb" Operator="DataTypeCheck" Type="Integer" Display="None"
                        ValidationGroup="vgpCadastroEdicao">*</asp:CompareValidator>

        </ItemTemplate>
    </asp:Repeater>
 </ContentTemplate>

Excerpt related to code-behind Text Changed event, I need to trigger this event to calculate a value to be displayed to the user so dynamic.
    Protected Sub txtNrPaginasCor_TextChanged(ByVal sender As Object, ByVal e As EventArgs)
    MostrarCustoProducaoPublicacao()
End Sub

Protected Sub txtNrPaginasPb_TextChanged(ByVal sender As Object, ByVal e As EventArgs)
    MostrarCustoProducaoPublicacao()
End Sub

Piece of code where I want to take values from textboxes:
Protected Sub MostrarCustoProducaoPublicacao()
    Dim lIntTiragem As Integer = Nothing
    Dim lIntNrPaginasPbJornal As Integer = Nothing
    Dim lIntNrPaginasCorJornal As Integer = Nothing
    Dim lIntNrPaginasPbOffset As Integer = Nothing
    Dim lIntNrPaginasCorOffset As Integer = Nothing
    Dim IdPublicacao As Integer = SQL.RetiraSQLInjection(hdIdPublicacao.Value)

        For Each itemTipoPapel As RepeaterItem In rptPagsTipoPapel.Items
            Dim hdTipoPapel As HiddenField = CType(itemTipoPapel.FindControl("hdIdTipoPapelPubEd"), HiddenField)
            Dim txtNrPagPB As TextBox = CType(itemTipoPapel.FindControl("txtNrPaginasPb"), TextBox)

            Dim txtNrPagCor As TextBox = CType(itemTipoPapel.FindControl("txtNrPaginasCor"), TextBox)
            If hdTipoPapel.Value = 1 Or hdTipoPapel.Value = 2 Then
                If Not txtNrPagPB.Text.Equals("") Then
                    lIntNrPaginasPbJornal += SQL.RetiraSQLInjection(txtNrPagPB.Text)
                End If
                If Not txtNrPagCor.Text.Equals("") Then
                    lIntNrPaginasCorJornal += SQL.RetiraSQLInjection(txtNrPagCor.Text)
                End If
            ElseIf hdTipoPapel.Value = 3 Or hdTipoPapel.Value = 4 Then
                If Not txtNrPagPB.Text.Equals("") Then
                    lIntNrPaginasPbOffset += SQL.RetiraSQLInjection(txtNrPagPB.Text)
                End If
                If Not txtNrPagCor.Text.Equals("") Then
                    lIntNrPaginasCorOffset += SQL.RetiraSQLInjection(txtNrPagCor.Text)
                End If
            End If
        Next
End Sub

A: Check if there isn't any even rebinding your repeater before your textChanged event's triggers, as for eg. pageLoad.
If somethins it's binding your repeater you won't be able to get any of these values.


text:
Q: Bash script to delete files in a directory if there are more than 5 This is a backup script that copies files from one directory to another.  I use a for loop to check if there are more than five files.  If there are, the loop should delete the oldest entries first.
I tried ls -tr | head -n -5 | xargs rm from the command line and it works successfully to delete older files if there are more than 5 in the directory.
However, when I put it into my for loop, I get an error rm: missing operand
Here is the full script. I don't think I am using the for loop correctly in the script, but I'm really not sure how to use the commands ls -tr | head -n -5 | xargs rm in a loop that iterates over the files in the directory.
timestamp=$(date +"%m-%d-%Y")
dest=${HOME}/mybackups
src=${HOME}/safe
fname='bu_'
ffname=${HOME}/mybackups/${fname}${timestamp}.tar.gz

# for loop for deletion of file
for f in ${HOME}/mybackups/*
do
  ls -tr | head -n -5 | xargs rm
done

if [ -e $ffname ];
  then
      echo "The backup for ${timestamp} has failed." | tee ${HOME}/mybackups/Error_${timestamp}
  else
      tar -vczf ${dest}/${fname}${timestamp}.tar.gz ${src}
fi

Edit: I took out the for loop, so it's now just:
[...]
ffname=${HOME}/mybackups/${fname}${timestamp}.tar.gz

ls -tr | head -n -5 | xargs rm

if [ -e $ffname ];
[...]

The script WILL work if it is in the mybackups directory, however, I continue to get the same error if it is not in that directory.  The script gets the file names but tries to remove them from the current directory, I think...  I tried several modifications but nothing has worked so far.

A:
I get an error rm: missing operand

The cause of that error is that there are no files left to be deleted.  To avoid that error, use the --no-run-if-empty option:
ls -tr | head -n -5 | xargs --no-run-if-empty rm

In the comments, mklement0 notes that this issue is peculiar to GNU xargs.  BSD xargs will not run with an empty argument.  Consequently, it does not need and does not support the --no-run-if-empty option.
More
Quoting from a section of code in the question:
for f in ${HOME}/mybackups/*
do
  ls -tr | head -n -5 | xargs rm
done

Note that (1) f is never used for anything and (2) this runs the ls -tr | head -n -5 | xargs rm several times in a row when it needs to be run only once.
Obligatory Warning
Your approach parses the output of ls.  This makes for a simple and easily understood command.  It can work if all your files are sensibly named.  It will not work in general.  For more on this, see: Why you shouldn't parse the output of ls(1).
Safer Alternative
The following will work with all manner of file names, whether they contains spaces, tabs, newlines, or whatever:
find . -maxdepth 1 -type f -printf '%T@ %i\n' | sort -n | head -n -5 | while read tstamp inode
do
    find . -inum "$inode" -delete
done

A: SMH.  I ended up coming up to the simplest solution in the world by just cd-ing into the directory before I ran ls -tr | head -n -5 | xargs rm .  Thanks for everyone's help!
timestamp=$(date +"%m-%d-%Y")
dest=${HOME}/mybackups
src=${HOME}/safe
fname='bu_'
ffname=${HOME}/mybackups/${fname}${timestamp}.tar.gz

cd ${HOME}/mybackups
ls -tr | head -n -5 | xargs rm

if [ -e $ffname ];
  then
      echo "The backup for ${timestamp} has failed." | tee ${HOME}/mybackups/Error_${timestamp}
  else
      tar -vczf ${dest}/${fname}${timestamp}.tar.gz ${src}
fi

This line ls -tr | head -n -5 | xargs rm came from here

ls -tr displays all the files, oldest first (-t newest first, -r
  reverse).
head -n -5 displays all but the 5 last lines (ie the 5 newest files).
xargs rm calls rm for each selected file

.


text:
Q: Can't see file information (other than the size) in status bar As of today, I can no longer see any file information in the status bar of my Windows Explorer window. I can see the number of files selected, the size and the zone. No date information.
I've tried:

*

*Hiding/showing the status bar.

*Switching settings in Organize (under Layout I only have "menu bar" and "navigation pane").

*The usual (login/out, restart etc.)

I'm on Windows Server and I'm connection to a RDP via VPN. NB it worked yesterday and as far I'm informed, nobody has made any changes. What do I miss?


text:
Q: Java:The child class implement interface, but the parent class override the members of the interface? Typically, a class implements an interface, and the class itself or its child class override the methods in the interface, such as:
Define an interface:
interface Interface {
    void fun();
}

1.Parent class override the interface method, and child class direct inherit:
public class Parent implements Interface{
    public void fun(){
    }
}

public class Child extends Parent{
}

Or:
2.The parent class is defined as an abstract class and the child class override the methods in the interface:
public abstract class Parent implements Interface{
}

public class Child extends Parent{
    public void fun(){
    }
}

However, I also see a strange way to override the interface method:
3.The child class only implement interfaces, but override methods in the interface by the parent class:
public class Parent{
    public void fun(){
    }
}

public class Child extends Parent implements Interface{
}

The third way to override the interface method is very common in the android framework source code, for example:
public interface ViewParent {
    //......
    void requestLayout();
    ViewParent getParent();
}

public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
    //......
    @CallSuper
    public void requestLayout() {
        //......
    }

    public final ViewParent getParent() {
        return mParent;
    }
}

public abstract class ViewGroup extends View implements ViewParent, ViewManager {
    //......
}

The method requestLayout() and getParent() comes from ViewParent, and ViewGroup implements ViewParent, but why does the implementation of the method be done in the parent class View?
What is the reason for this design?

A: Well, every View has a parent View, so the base View class needs a getParent() method and has a mParent property.
However, View doesn't implement ViewParent, since not all views are parents of other views.
If View was implementing some basic "ViewInterface", it would be possible to include getParent() in that interface, but since it doesn't, getParent() was included in the ViewParent interface.
And since View already implements that method, the ViewGroup sub-class doesn't have to implement it.


text:
Q: Ubuntu 12.04 wireless (wifi) not working, can not upgrade to 12.10, touchpad gestures not working. What to do? I installed ubuntu 12.04 LTS 3 days ago and since then wireless feature and touchpad gestures are not working. Tried everything on internet but still unsuccessful. I cant upgrade to ubuntu 12.10.
These are the following comments I tried. Please help me.
EDIT: just realized usb 3.0 is also not working.
COMMAND
lsb_release -r
OUTPUT
-----------------------------------------------------------------
Release:    12.04
-----------------------------------------------------------------

COMMAND
lspci
OUTPUT
------------------------------------------------------------------
00:00.0 Host bridge: Intel Corporation Xeon E3-1200 v3/4th Gen Core Processor DRAM Controller (rev 06)
00:01.0 PCI bridge: Intel Corporation Xeon E3-1200 v3/4th Gen Core Processor PCI Express x16 Controller (rev 06)
00:01.1 PCI bridge: Intel Corporation Xeon E3-1200 v3/4th Gen Core Processor PCI Express x8 Controller (rev 06)
00:02.0 VGA compatible controller: Intel Corporation 4th Gen Core Processor Integrated Graphics Controller (rev 06)
00:03.0 Audio device: Intel Corporation Xeon E3-1200 v3/4th Gen Core Processor HD Audio Controller (rev 06)
00:14.0 USB controller: Intel Corporation 8 Series/C220 Series Chipset Family USB xHCI (rev 05)
00:16.0 Communication controller: Intel Corporation 8 Series/C220 Series Chipset Family MEI Controller #1 (rev 04)
00:1a.0 USB controller: Intel Corporation 8 Series/C220 Series Chipset Family USB EHCI #2 (rev 05)
00:1b.0 Audio device: Intel Corporation 8 Series/C220 Series Chipset High Definition Audio Controller (rev 05)
00:1c.0 PCI bridge: Intel Corporation 8 Series/C220 Series Chipset Family PCI Express Root Port #1 (rev d5)
00:1c.1 PCI bridge: Intel Corporation 8 Series/C220 Series Chipset Family PCI Express Root Port #2 (rev d5)
00:1c.2 PCI bridge: Intel Corporation 8 Series/C220 Series Chipset Family PCI Express Root Port #3 (rev d5)
00:1d.0 USB controller: Intel Corporation 8 Series/C220 Series Chipset Family USB EHCI #1 (rev 05)
00:1f.0 ISA bridge: Intel Corporation HM86 Express LPC Controller (rev 05)
00:1f.2 SATA controller: Intel Corporation 8 Series/C220 Series Chipset Family 6-port SATA Controller 1 [AHCI mode] (rev 05)
00:1f.3 SMBus: Intel Corporation 8 Series/C220 Series Chipset Family SMBus Controller (rev 05)
07:00.0 3D controller: NVIDIA Corporation GF117M [GeForce 610M/710M / GT 620M/625M/630M/720M] (rev a1)
08:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8101E/RTL8102E PCI Express Fast Ethernet controller (rev 07)
09:00.0 Unassigned class [ff00]: Realtek Semiconductor Co., Ltd. RTS5229 PCI Express Card Reader (rev 01)
0f:00.0 Network controller: Qualcomm Atheros QCA9565 / AR9565 Wireless Network Adapter (rev 01)

------------------------------------------------------------------
COMMAND
sudo apt-get install linux-backports-modules-wireless-lucid-generic
OUTPUT
-------------------------------------------------------------------
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package linux-backports-modules-wireless-lucid-generic
-------------------------------------------------------------------
COMMAND
cat /etc/lsb-release; uname -a
OUTPUT
-------------------------------------------------------------------
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=12.04
DISTRIB_CODENAME=precise
DISTRIB_DESCRIPTION="Ubuntu 12.04.5 LTS"
Linux ritwik-PC 3.2.0-67-generic #101-Ubuntu SMP Tue Jul 15 17:46:11 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
-------------------------------------------------------------------
COMMAND
lspci -nnk | grep -iA2 net
OUTPUT
-------------------------------------------------------------------
08:00.0 Ethernet controller [0200]: Realtek Semiconductor Co., Ltd. RTL8101E/RTL8102E PCI Express Fast Ethernet controller [10ec:8136] (rev 07)
    Subsystem: Hewlett-Packard Company Device [103c:225d]
    Kernel driver in use: r8169
--
0f:00.0 Network controller [0280]: Qualcomm Atheros QCA9565 / AR9565 Wireless Network Adapter [168c:0036] (rev 01)
    Subsystem: Hewlett-Packard Company Device [103c:217f]
-------------------------------------------------------------------
COMMAND
lsusb
OUTPUT
-------------------------------------------------------------------
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 002: ID 8087:8008 Intel Corp.
Bus 002 Device 002: ID 8087:8000 Intel Corp.
-------------------------------------------------------------------
COMMAND
iwconfig
OUTPUT
-------------------------------------------------------------------
lo        no wireless extensions.

eth0      no wireless extensions.

-------------------------------------------------------------------
COMMAND
rfkill list all
OUTPUT
-------------------------------------------------------------------
0: hp-wifi: Wireless LAN
    Soft blocked: no
    Hard blocked: no
1: hp-bluetooth: Bluetooth
    Soft blocked: no
    Hard blocked: no
-------------------------------------------------------------------
COMMAND
lsmod
OUTPUT
-------------------------------------------------------------------
Module                  Size  Used by
snd_hda_codec_realtek   224215  1
bnep                   18281  2
rfcomm                 47604  0
bluetooth             180113  10 bnep,rfcomm
parport_pc             32866  0
ppdev                  17113  0
nls_iso8859_1          12713  1
nls_cp437              16991  1
vfat                   17585  1
fat                    61512  1 vfat
snd_hda_intel          33719  3
snd_hda_codec         127706  2 snd_hda_codec_realtek,snd_hda_intel
snd_hwdep              17764  1 snd_hda_codec
snd_pcm                97275  2 snd_hda_intel,snd_hda_codec
snd_seq_midi           13324  0
snd_rawmidi            30748  1 snd_seq_midi
snd_seq_midi_event     14899  1 snd_seq_midi
snd_seq                61929  2 snd_seq_midi,snd_seq_midi_event
nouveau               775039  0
joydev                 17693  0
snd_timer              29990  2 snd_pcm,snd_seq
snd_seq_device         14540  3 snd_seq_midi,snd_rawmidi,snd_seq
ttm                    76949  1 nouveau
uvcvideo               72627  0
snd                    79041  15 snd_hda_codec_realtek,snd_hda_intel,snd_hda_codec,snd_hwdep,snd_pcm,snd_rawmidi,snd_seq,snd_timer,snd_seq_device
videodev               98259  1 uvcvideo
drm_kms_helper         46978  1 nouveau
psmouse                98051  0
drm                   241971  3 nouveau,ttm,drm_kms_helper
i2c_algo_bit           13423  1 nouveau
soundcore              15091  1 snd
snd_page_alloc         18529  2 snd_hda_intel,snd_pcm
v4l2_compat_ioctl32    17128  1 videodev
hp_wmi                 18092  0
serio_raw              13211  0
sparse_keymap          13890  1 hp_wmi
mxm_wmi                13021  1 nouveau
video                  19651  1 nouveau
wmi                    19256  2 hp_wmi,mxm_wmi
mac_hid                13253  0
lp                     17799  0
parport                46562  3 parport_pc,ppdev,lp
r8169                  62190  0
-------------------------------------------------------------------
COMMAND
sudo su
modprobe -v ath9k
OUTPUT
-------------------------------------------------------------------
insmod /lib/modules/3.2.0-67-generic/kernel/net/wireless/cfg80211.ko
insmod /lib/modules/3.2.0-67-generic/kernel/drivers/net/wireless/ath/ath.ko
insmod /lib/modules/3.2.0-67-generic/kernel/drivers/net/wireless/ath/ath9k/ath9k_hw.ko
insmod /lib/modules/3.2.0-67-generic/kernel/drivers/net/wireless/ath/ath9k/ath9k_common.ko
insmod /lib/modules/3.2.0-67-generic/kernel/net/mac80211/mac80211.ko
insmod /lib/modules/3.2.0-67-generic/kernel/drivers/net/wireless/ath/ath9k/ath9k.ko

-------------------------------------------------------------------
COMMAND
do-release-upgrade
OUTPUT
-------------------------------------------------------------------
Err Upgrade tool signature
  404  Not Found [IP: 91.189.88.149 80]
Err Upgrade tool
  404  Not Found [IP: 91.189.88.149 80]
Fetched 0 B in 0s (0 B/s)
WARNING:root:file 'quantal.tar.gz.gpg' missing
Failed to fetch
Fetching the upgrade failed. There may be a network problem.
-------------------------------------------------------------------
COMMAND
sudo modprobe ath9k
dmesg | grep ath9k

NO OUTPUT FOR THEM

COMMAND
dmesg | grep -e ath -e 80211
OUTPUT
-------------------------------------------------------------------
[   13.232372] type=1400 audit(1408867538.399:9): apparmor="STATUS" operation="profile_load" name="/usr/lib/telepathy/mission-control-5" pid=975 comm="apparmor_parser"
[   13.232615] type=1400 audit(1408867538.399:10): apparmor="STATUS" operation="profile_load" name="/usr/lib/telepathy/telepathy-*" pid=975 comm="apparmor_parser"
[   15.186599] ath3k: probe of 3-4:1.0 failed with error -110
[   15.186635] usbcore: registered new interface driver ath3k
[   88.219329] cfg80211: Calling CRDA to update world regulatory domain
[   88.351665] cfg80211: World regulatory domain updated:
[   88.351667] cfg80211:     (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)
[   88.351670] cfg80211:     (2402000 KHz - 2472000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[   88.351671] cfg80211:     (2457000 KHz - 2482000 KHz @ 20000 KHz), (300 mBi, 2000 mBm)
[   88.351673] cfg80211:     (2474000 KHz - 2494000 KHz @ 20000 KHz), (300 mBi, 2000 mBm)
[   88.351674] cfg80211:     (5170000 KHz - 5250000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[   88.351675] cfg80211:     (5735000 KHz - 5835000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
-------------------------------------------------------------------

COMMAND
sudo apt-get install touchpad-indicator
OUTPUT
-------------------------------------------------------------------
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
  gir1.2-gconf-2.0 python-pyudev
Suggested packages:
  python-qt4 python-pyside.qtcore
The following NEW packages will be installed:
  gir1.2-gconf-2.0 python-pyudev touchpad-indicator
0 upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
Need to get 84.1 kB of archives.
After this operation, 1,136 kB of additional disk space will be used.
Do you want to continue [Y/n]? Y
Get:1 http://ppa.launchpad.net/atareao/atareao/ubuntu/ precise/main touchpad-indicator all 0.9.3.12-1ubuntu1 [46.5 kB]
Get:2 http://archive.ubuntu.com/ubuntu/ precise/main gir1.2-gconf-2.0 amd64 3.2.5-0ubuntu2 [7,098 B]
Get:3 http://archive.ubuntu.com/ubuntu/ precise/main python-pyudev all 0.13-1 [30.5 kB]
Fetched 84.1 kB in 2s (31.6 kB/s)
Selecting previously unselected package gir1.2-gconf-2.0.
(Reading database ... 169322 files and directories currently installed.)
Unpacking gir1.2-gconf-2.0 (from .../gir1.2-gconf-2.0_3.2.5-0ubuntu2_amd64.deb) ...
Selecting previously unselected package python-pyudev.
Unpacking python-pyudev (from .../python-pyudev_0.13-1_all.deb) ...
Selecting previously unselected package touchpad-indicator.
Unpacking touchpad-indicator (from .../touchpad-indicator_0.9.3.12-1ubuntu1_all.deb) ...
Processing triggers for bamfdaemon ...
Rebuilding /usr/share/applications/bamf.index...
Processing triggers for desktop-file-utils ...
Processing triggers for gnome-menus ...
Processing triggers for hicolor-icon-theme ...
Processing triggers for software-center ...
INFO:softwarecenter.db.update:no translation information in database needed
Setting up gir1.2-gconf-2.0 (3.2.5-0ubuntu2) ...
Setting up python-pyudev (0.13-1) ...
Setting up touchpad-indicator (0.9.3.12-1ubuntu1) ...
-------------------------------------------------------------------

COMMAND
sudo apt-get install linux-headers-generic build-essential
wget http://www.orbit-lab.org/kernel/compat-wireless-3-stable/v3.6/compat-wireless-3.6.6-1-snpc.tar.bz2
tar jxvf compat-wireless-3.6.6-1-snpc.tar.bz2
sudo su
./scripts/driver-select ath9k

OUTPUT
-----------------------------------------------------------------------
Processing new driver-select request...
Backing up makefile: Makefile.bk
Backup exists: Makefile.bk
Backup exists: Makefile.bk
Backup exists: Makefile.bk
Backup exists: Makefile.bk
Backing up makefile: drivers/net/wireless/Makefile.bk
Backing up makefile: drivers/net/wireless/ath/Makefile.bk
Backing up makefile: net/wireless/Makefile.bk
Backing up makefile: drivers/ssb/Makefile.bk
Backing up makefile: drivers/bcma/Makefile.bk
Backing up makefile: drivers/misc/eeprom/Makefile.bk
Backup exists: Makefile.bk

-----------------------------------------------------------------------
NEXT COMMAND
make
OUTPUT
----------------------------------------------------------------------
./scripts/gen-compat-autoconf.sh /home/ritwik/compat-wireless-3.6.6-1-snpc/.config /home/ritwik/compat-wireless-3.6.6-1-snpc/config.mk > include/linux/compat_autoconf.h
make -C /lib/modules/3.2.0-67-generic/build M=/home/ritwik/compat-wireless-3.6.6-1-snpc modules
make[1]: Entering directory `/usr/src/linux-headers-3.2.0-67-generic'
  CC [M]  /home/ritwik/compat-wireless-3.6.6-1-snpc/compat/main.o
In file included from /home/ritwik/compat-wireless-3.6.6-1-snpc/include/linux/compat-2.6.h:64:0,
                 from <command-line>:0:
/home/ritwik/compat-wireless-3.6.6-1-snpc/include/linux/compat-3.4.h:32:21: error: redefinition of 'kmalloc_array'
include/linux/slab.h:243:21: note: previous definition of 'kmalloc_array' was here
make[3]: *** [/home/ritwik/compat-wireless-3.6.6-1-snpc/compat/main.o] Error 1
make[2]: *** [/home/ritwik/compat-wireless-3.6.6-1-snpc/compat] Error 2
make[1]: *** [_module_/home/ritwik/compat-wireless-3.6.6-1-snpc] Error 2
make[1]: Leaving directory `/usr/src/linux-headers-3.2.0-67-generic'
make: *** [modules] Error 2
----------------------------------------------------------------------
NEXT COMMAND
make install
OUTPUT
----------------------------------------------------------------------
make -C /lib/modules/3.2.0-67-generic/build M=/home/ritwik/compat-wireless-3.6.6-1-snpc modules
make[1]: Entering directory `/usr/src/linux-headers-3.2.0-67-generic'
  CC [M]  /home/ritwik/compat-wireless-3.6.6-1-snpc/compat/main.o
In file included from /home/ritwik/compat-wireless-3.6.6-1-snpc/include/linux/compat-2.6.h:64:0,
                 from <command-line>:0:
/home/ritwik/compat-wireless-3.6.6-1-snpc/include/linux/compat-3.4.h:32:21: error: redefinition of 'kmalloc_array'
include/linux/slab.h:243:21: note: previous definition of 'kmalloc_array' was here
make[3]: *** [/home/ritwik/compat-wireless-3.6.6-1-snpc/compat/main.o] Error 1
make[2]: *** [/home/ritwik/compat-wireless-3.6.6-1-snpc/compat] Error 2
make[1]: *** [_module_/home/ritwik/compat-wireless-3.6.6-1-snpc] Error 2
make[1]: Leaving directory `/usr/src/linux-headers-3.2.0-67-generic'
make: *** [modules] Error 2
----------------------------------------------------------------------

Not able to find ( drivers/net/wireless/ath/ath9k/hw.c ) or ( drivers/net/wireless/ath/ath9k/hw.h )

A: Is your wired network working?
There's a solution for your problem in this thread. Instead of upgrading to the unsupoorted, older 12.10, you should rather upgrade to 14.04, which is the current long term supported release. The newer kernel in 14.04 might fix a few of your issues. Here's a howto

A: Although you are running the version codenamed Precise, you attempted to install the backports version for Lucid. It isn't available in the Precise repositories. I suggest you try:
sudo apt-get update
sudo apt-get install linux-backports-modules-cw-3.12-precise-generic
sudo modprobe ath9k

Your wireless should now be working.


text:
Q: how to keep the variable order in ```cut ```order while using ```complete``` I am using cut to generate subtotal of people count in age groups. The sample data and the codes are:
set.seed(12345)

#create a numeric variable Age
AGE <- sample(0:110, 100, replace = TRUE)

Sample.data <-data.frame(AGE)

summary_data<- Sample.data %>%
  group_by(grp =  cut(
    AGE,
    breaks=c(-Inf, 0,0.001, 0.083, 2, 13, 65,1000),
    right=TRUE,
    labels = c("Foetus(0 yr)","Neonate (0.001 - 0.082 yr)","Infant(0.083-1.999 yrs)","Child(2-12.999 yrs)", "Adolescent(13-17.999 yrs)","Adult(18-64.999 yrs.)","Elderly(65-199 yrs)")
  )) %>% summarise(TotalPeople = n())

Here is what I get:

I would like to keep the age groups that doesn't have observation in the table. So I add complete and fill. I was able to fill 0 for the empty age groups, but the age groups's order also changed which I do not want it. See codes and results:
summary_data<- Sample.data %>%
  group_by(grp =  cut(
    AGE,
    breaks=c(-Inf, 0,0.001, 0.083, 2, 13, 65,1000),
    right=TRUE,
    labels = c("Foetus(0 yr)","Neonate (0.001 - 0.082 yr)","Infant(0.083-1.999 yrs)","Child(2-12.999 yrs)", "Adolescent(13-17.999 yrs)","Adult(18-64.999 yrs.)","Elderly(65-199 yrs)")
  )) %>% summarise(TotalPeople = n(),)%>% complete(grp = levels(grp), fill = list(TotalPeople = 0))

Is there a way to keep age groups in the order of cut order? Or is there a way to keep the age groups with 0 observation in another way so the age groups won't change its order?  The ideal results should looks like this:

A: You can prevent dropping the groups by adding .drop = FALSE to group_by:
library(dplyr)
set.seed(12345)

#create a numeric variable Age
AGE <- sample(0:110, 100, replace = TRUE)

Sample.data <-data.frame(AGE)

summary_data<- Sample.data %>%
  group_by(grp =  cut(
    AGE,
    breaks=c(-Inf, 0,0.001, 0.083, 2, 13, 65,1000),
    right=TRUE,
    labels = c("Foetus(0 yr)","Neonate (0.001 - 0.082 yr)","Infant(0.083-1.999 yrs)","Child(2-12.999 yrs)", "Adolescent(13-17.999 yrs)","Adult(18-64.999 yrs.)","Elderly(65-199 yrs)")
  ), .drop = FALSE) %>% summarise(TotalPeople = n())
#> `summarise()` ungrouping output (override with `.groups` argument)
summary_data
#> # A tibble: 7 x 2
#>   grp                        TotalPeople
#>   <fct>                            <int>
#> 1 Foetus(0 yr)                         1
#> 2 Neonate (0.001 - 0.082 yr)           0
#> 3 Infant(0.083-1.999 yrs)              0
#> 4 Child(2-12.999 yrs)                  2
#> 5 Adolescent(13-17.999 yrs)           14
#> 6 Adult(18-64.999 yrs.)               37
#> 7 Elderly(65-199 yrs)                 46

A: You can add ordered_result = TRUE. With table you can get the counts and with as.data.frame  you get a data.frame of the counts per group.
grp <- cut(Sample.data$AGE, breaks=c(-Inf, 0, 0.082, 2, 13, 18, 65, Inf)
 , ordered_result = TRUE
 , labels = c("Foetus(0 yr)","Neonate (0 - 0.082] yrs","Infant (0.082-2] yrs",
    "Child (2-13] yrs", "Adolescent (13-18] yrs","Adult (18-65] yrs",
    "Elderly >65 yrs"))
as.data.frame(table(grp))
#                      grp Freq
#1            Foetus(0 yr)    1
#2 Neonate (0 - 0.082] yrs    0
#3    Infant (0.082-2] yrs    2
#4        Child (2-13] yrs   14
#5  Adolescent (13-18] yrs    5
#6       Adult (18-65] yrs   32
#7         Elderly >65 yrs   46

To get in addition the mean age you can use xtabs
x <- table(grp)
cbind(TotalPeople=x, meanAge=xtabs(AGE ~ grp, cbind(AGE, addNA(grp))) / x)
#                        TotalPeople   meanAge
#Foetus(0 yr)                      1  0.000000
#Neonate (0 - 0.082] yrs           0       NaN
#Infant (0.082-2] yrs              2  1.500000
#Child (2-13] yrs                 14  9.071429
#Adolescent (13-18] yrs            5 15.000000
#Adult (18-65] yrs                32 41.093750
#Elderly >65 yrs                  46 87.434783

Or you can use aggregate
aggregate(AGE ~ grp, cbind(AGE, addNA(grp)), function(x)
 c(TotalPeople=length(x), meanAge=mean(x)), drop=FALSE)
#                      grp AGE.TotalPeople AGE.meanAge
#1            Foetus(0 yr)        1.000000    0.000000
#2 Neonate (0 - 0.082] yrs              NA          NA
#3    Infant (0.082-2] yrs        2.000000    1.500000
#4        Child (2-13] yrs       14.000000    9.071429
#5  Adolescent (13-18] yrs        5.000000   15.000000
#6       Adult (18-65] yrs       32.000000   41.093750
#7         Elderly >65 yrs       46.000000   87.434783

or you can use by
by(AGE, grp, function(x) c(TotalPeople=length(x), meanAge=mean(x)))
#grp: Foetus(0 yr)
#TotalPeople     meanAge
#          1           0
#------------------------------------------------------------
#grp: Neonate (0 - 0.082] yrs
#NULL
#------------------------------------------------------------
#grp: Infant (0.082-2] yrs
#TotalPeople     meanAge
#        2.0         1.5
#------------------------------------------------------------
#grp: Child (2-13] yrs
#TotalPeople     meanAge
#  14.000000    9.071429
#------------------------------------------------------------
#grp: Adolescent (13-18] yrs
#TotalPeople     meanAge
#          5          15
#------------------------------------------------------------
#grp: Adult (18-65] yrs
#TotalPeople     meanAge
#   32.00000    41.09375
#------------------------------------------------------------
#grp: Elderly >65 yrs
#TotalPeople     meanAge
#   46.00000    87.43478


text:
Q: How to use 'Node.js 3.0 or later' on mongoose connection? I am developing a Node JS API but suddently, my MongoDB connection configuration stopped working.
This is how my configuration looks like:
const mongoose = require('mongoose');

try {
  mongoose.connect('mongodb+srv://<user>:<password>@hackerrank.jyajn.mongodb.net/<dbname>?retryWrites=true&w=majority', {useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false});
  mongoose.Promise = global.Promise;
}
catch(error) {
  console.log(error);
}

module.exports = mongoose;

This connection was working until yesterday, but when I tried to run it today it threw the error:
Error: querySrv ENOTFOUND

I saw on this post that

According to MongoDB, SRV is possibly not working due to Mongoose.

So I changed the connection string to the "Node.js 2.2.12 or later" version, as mentioned on the post and it really worked.
My question is, why did this happen? Shouldn't I be able to use the latest connection string, since my node version is v12.17.0?


text:
Q: What do I need to do to raise my "Speed" rating? In Tempest Trials, after winning a trial, you're shown a point calculation. It increases the number of levels you beat by certain multipliers. One of these is Speed. I almost always get an E rating which only gives me a 10% bonus. Once, I got a D rating, but I'm not sure how I did that, because I felt that I spent a lot of time setting up in that run.
What should I be trying to do in the Tempest Trials to increase my Speed rating?

A: You need to focus on completing your maps in the fewest turns possible to increase your speed. On average I complete most maps in 2-3 turns, 4-5 max. This gives me a consistent A rank for speed. Since the multipliers stack, don't worry to much about surviving and focus on quick wins. If your team dies and you have to use a second team as long as you kept up the speed and had a bonus ally you'll suffer only a small drop in your score

A: As noted by Arcane, "speed" in this context means the total number of turns it takes to complete all of the battles.  As noted on the wiki, the way to get an A is to beat all of the battles in 28 turns or less:
Speed Rank  Multiplier  Total Turns
    A          1.5x      Turns ≤ 28
    B          1.4x        29-31
    C          1.3x        32-35
    D          1.2x        36-39
    E          1.1x      Turns ≥ 40

This number does not appear to be affected by the number of maps, so it's much harder to get an A rank on the harder difficulties.  With only 3 maps, that's an average of ~9 turns/map, while with 7 maps you only get 4 turns/map.
A suggestion that may help in this category is to use units with more mobility and range.  Using cavalry units will help you get into position easier, and bow/dagger/magic users will be able to hit enemy units from a farther distance.  A team of armored units are unlikely to clear these battles efficiently enough to get an A for speed.
Note that each team you lose loses you 5% bonus from the survival category, which stacks multiplicatively.  An A for survival with an E rank for speed is 1.2*1.1 = 1.32 which is slightly worse than a D survival and C speed (1.05*1.3 = 1.365), so it'll be worth losing a few weaker teams for speed as long as you can at least get a C.


text:
Q: Cannot use sidebar android in Card view I have a Card View which displays the list of items. I tried aligning the cards one below another and I was not able to implement it. Another problem I'm facing now is that I cannot access the sidebar items. I'm able to see the sidebar by swiping to right and the icon for sidebar is missing on the nav bar.
Here is the code snippet:
activity_top_ten_items.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_teams"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

    <include layout="@layout/topteam_recycler" />

</android.support.v4.widget.DrawerLayout>

app_bar_teams.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.neonsec.ctftime.ctf_timemobile.MainActivity">

    <include
        layout="@layout/content_top_ten_teams"
        android:layout_width="match_parent"
        android:layout_height="667dp"
        tools:layout_editor_absoluteY="59dp" />

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

</android.support.design.widget.CoordinatorLayout>

content_top_10_items.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_margin="@dimen/card_margin"
        android:elevation="3dp"
        card_view:cardCornerRadius="@dimen/card_album_radius">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/thumbnail"
                android:layout_width="match_parent"
                android:layout_height="@dimen/album_cover_height"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:layout_marginTop="59dp"
                android:background="?attr/selectableItemBackgroundBorderless"
                android:clickable="true"
                android:scaleType="fitXY" />

            <TextView
                android:id="@+id/tname"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/thumbnail"
                android:paddingLeft="@dimen/album_title_padding"
                android:paddingRight="@dimen/album_title_padding"
                android:paddingTop="@dimen/album_title_padding"
                android:textSize="@dimen/album_title" />

            <TextView
                android:id="@+id/tpoints"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/tname"
                android:paddingBottom="@dimen/songs_count_padding_bottom"
                android:paddingLeft="@dimen/album_title_padding"
                android:paddingRight="@dimen/album_title_padding"
                android:textSize="@dimen/songs_count" />

        </RelativeLayout>

    </android.support.v7.widget.CardView>

</RelativeLayout>

A: To aligning the cards one below another you need to use a RecyclerView List with Cards. That would be a list of CardViews one below the other. Take a look on this: https://www.androidtutorialpoint.com/material-design/android-cardview-tutorial/  , or this: http://www.truiton.com/2015/03/android-cardview-example/
 or this one to https://code.tutsplus.com/tutorials/getting-started-with-recyclerview-and-cardview-on-android--cms-23465
The sidenav items can be found here: res/menu/activity_main_drawer.xml. Make shure you have defined items there.
The button on the nav_bar for the sidenav is created programatically on your controller this way:
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    ActionBar actionbar = getSupportActionBar();
    actionbar.setDisplayHomeAsUpEnabled(true);
    actionbar.setHomeAsUpIndicator(R.drawable.ic_menu);

See: https://developer.android.com/training/implementing-navigation/nav-drawer.html
Hope it solve!!


text:
Q: Send post via CURL After sending POST to webmoney merchant, appear error:

The page cannot be displayed
There is a problem with the page you are looking for and it cannot be
  displayed. This error can occur if you are trying to display an HTML
  page that resides in a directory that is configured to allow Execute
  or Script permissions only. Please try the following:
Contact the Web site administrator if you believe this directory
  should allow read access. HTTP Error 403.2 - Forbidden: Read access is
  denied. Internet Information Services (IIS)
Technical Information (for support personnel)
Go to Microsoft Product Support Services and perform a title search
  for the words HTTP and 403. Open IIS Help, which is accessible in IIS
  Manager (inetmgr), and search for topics titled Using Virtual
  Directories, Changing Default Web Site Settings, and About Custom
  Error Messages.

CODE:
$param = array(
    'LMI_PAYMENT_AMOUNT' => '2',
    'LMI_PAYMENT_DESC' => 'Return a debt by invoice',
    'LMI_PAYMENT_NO' => rand(0, 9999),
    'LMI_PAYEE_PURSE' => 'Z401998872708',
    'LMI_SIM_MODE' => '0',
);

//
$url = "https://merchant.webmoney.ru/lmi/payment.asp";
$post = "LMI_PAYEE_PURSE=Z401998872708&LMI_PAYMENT_AMOUNT=1&LMI_PAYMENT_DESC=Return a debt by invoice";
$user_agent = "Mozilla/5.0 (Windows NT 5.1; rv:2.0) Gecko/20100101 Firefox/4.0";
$referer = "https://merchant.webmoney.ru/lmi/payment.asp";
$pathCerts="/mnt/d/web/test/WMunited.cer";
//
$ch = curl_init();

curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $param);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_REFERER, $referer);
curl_setopt($ch, CURLOPT_CAINFO, $pathCerts);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);

curl_setopt($ch, CURLOPT_COOKIEJAR, $_SERVER['DOCUMENT_ROOT'].'/cookies.txt');//куки сохранить
curl_setopt($ch, CURLOPT_COOKIEFILE,$_SERVER['DOCUMENT_ROOT'].'/cookies.txt');
//  curl_setopt ($ch, CURLOPT_ ,);
//  curl_setopt ($ch, CURLOPT_ ,);
$result = curl_exec ($ch);

echo $str = str_replace ("<head>","<head><base href = 'https://merchant.webmoney.ru/lmi/'>", $result);


text:
Q: Reading Strings from text files in java im studying for my programming final exam. I have to write a program which opens a file which is stored in the string fileName  and look in the file for a String called personName and this should print the first string after personName then the program should terminate after printing it,
if the argument personName is not in the file then it should print "this name doen't exsit" then if an IOException occurs it should then print "there is an IO Error" and the program should exsit using system.exit(0)
the program should use the file info.txt and each line should contain two strings
 first string name and second age.
everything must be in one method
data.txt contains
Max 60.0
joe  19.0
ali  20.0
my code for this so far is :
public class Files{

    public void InfoReader(String fileName, String personName)
    {

      try{
         try{
                   // Open the file that is the first
                  // command line parameter
                  FileInputStream fstream = new FileInputStream("C://rest//data.txt");
                  // Get the object of DataInputStream

                  DataInputStream in = new DataInputStream(fstream);
                  BufferedReader br = new BufferedReader(new InputStreamReader(in));

                  //Read File Line By Line
                  while ((fileName = br.readLine()) != null) {
                      // Print the content on the console
                      (new Files()).infoReader("info.txt","Joe"); //this prints the age
                  }
                  //Close the input stream
                  in.close();
              }

              catch (IOException e)
              {//Catch exception if any
                    System.out.println(" there is an IO Error");
                    System.exit(0);
              }
     }
    catch (Exception e)
              {//Catch exception if any
                    System.out.println("that name doesn't exists");

              }
    }
}

infoReader(info.txt,Joe); should print 19.0
But I am getting a java.lang.StackOverflowError
any help would be much appreciated!!
Thanks in advance!

A: This is what I think you are trying to do. And if doesn't, at least can work as an example. Just as amit mentions, your current error is because of the recursive call, which I think is not necessary.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class Files {

    public void InfoReader(String fileName, String personName) {
        try {
            // Open the file that is the first command line parameter
            FileInputStream fstream = new FileInputStream(fileName);

            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));

            String line = null;

            //Loop until there are no more lines in the file
            while((line = br.readLine()) != null) {
                //Split the line to get 'personaName' and 'age'.
                String[] lineParts = line.split(" ");

                //Compare this line personName with the one provided
                if(lineParts[0].equals(personName)) {
                    //Print age
                    System.out.println(lineParts[1]);
                    br.close();
                    System.exit(0);
                }
            }

            br.close();
            //If we got here, it means that personName was not found in the file.
            System.out.println("that name doesn't exists");
        } catch (IOException e) {
            System.out.println(" there is an IO Error");
        }
    }
}

A: If you use the Scanner class, it would make your life so much easier.
  Scanner fileScanner = new Scanner (new File(fileName));

  while(fileScanner.hasNextLine()
   {
      String line = fileScanner.nextLine();

      Scanner lineScanner = new Scanner(line);

      String name = lineScanner.next(); // gets the name
      double age  = Double.parseDouble(lineScanner.next()); // gets the age

      // That's all really! Now do the rest!
   }

A: Use commons-io and dont forget the encoding!
List<String> lines = FileUtils.readLines(file, encoding)


text:
Q: Initialize data with Entity Framework I want to initialize dummy data to the database before the application runs. I have a SQL script which inserts data directly to the tables.
The problem is when I want to update an element I get this exception:
'System.InvalidOperationException' en EntityFramework.dll: Attaching an entity of type 'Es.Udc.DotNet.MiniPortal.Model.Book' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.
This is my update method:
public void Update(E entity)
{
    dbContext.Entry<E>(entity).State = EntityState.Modified;
    dbContext.SaveChanges();
}

I think that's happening because EF doesn't track the items, but I don't know what can I do. What's the best approach to initialize the dummy data and get tracked by EF? Thanks.

A:
I think that's happening because EF doesn't track the items

This is happening because EF is tracking entities. Using the same DbContext instance you're trying to read and update an entity through different instances of that entity. Entities are tracked by reference.
This means that the entity you pass to this Update() method is different from the one you read from the database in the first place.
If you don't do that explicitly in code, it may be that the code goes through a mapping phase where the entity-to-update is new'ed (either explicitly or through reflection) and populated from another entity, for example a viewmodel that is mapped through AutoMapper.
Another scenario is where the context has a too long lifetime, for example because it's used from a static variable and/or singleton or a incorrectly configured dependency injection container.
So either:

*

*Fix the lifetime of the DbContext so the lookup and the update happen on different instances of the context.

*Make sure you update the entity returned from the first lookup, if the lookup has to happen on the same DbContext instance as the update.

*Use AsNoTracking() at the lookup. Querying the same entity multiple times may make sense, in which case using non-tracked entities in certain locations may be the solution.

Whichever approach you choose, you need to deal with concurrency, which you don't want to handle yourself. Optimistic concurrency support is present by default in Entity Framework.

A: I suggest you to do a select (with EF) before send the entity to your Update method then also try to attach the entity to the context after set it as modified (it depend if you use changetraking options or not)
 dbContext.Set<TEntity>().Attach(entity);

for example this is my Repository Update method (just for an example):
public void Update(TEntity updated, Tkey key)
        {
            updated.ObjectState = ObjectState.Modified;

            var existing = _dbSet.Find(key);
            if (existing == null) return;

            existing.ObjectState = ObjectState.Modified;
            dbContext.Entry(existing).CurrentValues.SetValues(updated);
            dbContext.Set<TEntity>().Attach(existing);

        }


text:
Q: SignatureDoesNotMatch.The request signature we calculated does not match the signature you provided. Check your key and signing method I am trying to implement the auto-update functionality in an electron app using a private s3 bucket. but it giving me a signature mismatch error. Please can anyone help me with this?
I have used the following code structure,
let opts = {
service: 's3',
region: 'us-east-1',
host: 'bucket-name.s3.amazonaws.com',
path: '/latest.yml'
};
console.log(opts);

aws4.sign(opts, {
    accessKeyId: 'XXXXXXXXXXXXXXXXXXXX',
    secretAccessKey: 'XXXXXXXXXXXXXXXX'
})
console.log(opts.headers);
autoUpdater.requestHeaders = opts.headers;

autoUpdater.checkForUpdates();
autoUpdater.on('checking-for-update', () => {

  })

A: The problem should be the / before latest.yml in your opts. Removing it should work


text:
Q: How to prove this product rule? If $f,g:\Omega\subset\mathbb{R}^n\rightarrow\mathbb{R}$ are differentiable in $x_0\in\Omega$ ($\Omega$ is open), then the function $(f*g)$ is differentiable in $x_0$ and:
$(f\cdot g)'(x_0)=f'(x_0)g(x_0)+f(x_0)g'(x_0)$
How to prove this product rule?
(Note: specifically for $\mathbb{R}^n\rightarrow\mathbb{R}$)

A: In the following $x\in{\mathbb R}^n$ is a point held fixed, and $h\in{\mathbb R}^n$ is a variable vector, whereas $f$, $g$ and $p:=f\cdot g$ are scalar functions. Both $f$ and $g$ are bounded in some neighborhood of the point $x$.  Therefore we may write
$$\eqalign{p(x+h)-p(x)&=\bigl(f(x+h)-f(x)\bigr)g(x) + f(x)\bigl(g(x+h)-g(x)\bigr)\cr&\qquad\qquad+\bigl(f(x+h)-f(x)\bigr)\bigl(g(x+h)-g(x)\bigr)\cr
&=\bigl(df(x).h+o(|h|)\bigr)g(x)+f(x)\bigl(dg(x).h+o(|h|)\bigr)\cr&\qquad\qquad+
\bigl(df(x).h+o(|h|)\bigr)\bigl(dg(x).h+o(|h|)\bigr)\cr
&=g(x)\>df(x).h+f(x)\>dg(x).h+o(|h|)\ \cr}$$
when $h\to0$.

A: \begin{align}
\frac{d(f(x)g(x))}{dx}&=\lim_{h\to 0}\frac{f(x+h)g(x+h)-f(x)g(x)}{h}\\
&=\lim_{h\to 0}\frac{f(x+h)g(x+h)+f(x+h)g(x)-f(x+h)g(x)-f(x)g(x)}{h}\\
&=\lim_{h\to 0}\frac{f(x+h)(g(x+h)-g(x))+g(x)(f(x+h)-f(x))}{h}
\end{align}
Then you can consider that $\lim_{h\to 0}f(x+h)=f(x)$.
When $x\in \mathbb R^n$, you have $$\frac{dF}{dx} = \sum_{i=1}^n\frac{\partial F}{\partial x_i}e_i$$ and the definition of the derivative is
$$\frac{\partial F}{\partial x_i}=\lim_{h\to 0}\frac{F(x+he_i)-F(x)}{h}$$


text:
Q: Sharing data from static lib between dynamic libs I have next situation:

*

*Static library with class A; (logger)

*Main application which creates class A instance as singleton

*Different delay loaded dynamic libraries (plugins) that links with (1.) and need to use instance of class A.

How should I share singleton from main application (2.) between plugins (3.)? Are there any features in Qt / C++ to do this?
Currently I'm using ugly solution based on shared memory and I don't think that it is right.
I'm thinking about refactoring with using of dependency injection pattern but it imposes some restrictions.
SAMPLE:
Static library "log.lib":
struct Log
{
  void write( QString text );
};

Main application "app.exe":
Log *logger = new Log; // I need only one logger for all application

int main()
{
  logger->write( "Main" );
  ...
}

Plugin 1 "plg1.dll"
extern Log *logger; // Logger from "app.exe"
void Foo()
{
  logger->write( "Foo" );
}

Plugin 2 "plg2.dll"
extern Log *logger; // Logger from "app.exe"
void Bar()
{
  logger->write( "Bar" );
}

A: Right, so in order:

*

*You seem not to use the singleton pattern for singleton use cases.

*Your original question is not much related to Qt.

*This has little to nothing to do with the distinction of static library or not.

*You could make the plugin interface accept a logger mutator so that you could then set that with the instance from the application.

I would personally just use the singleton pattern properly, and the plugin could also query the very instance. Please take a look at the following Qt macro:

Q_GLOBAL_STATIC( Type, VariableName)
Creates a global and static object of type QGlobalStatic, of name VariableName and that behaves as a pointer to Type. The object created by Q_GLOBAL_STATIC initializes itself on the first use, which means that it will not increase the application or the library's load time. Additionally, the object is initialized in a thread-safe manner on all platforms.

You could easily build the singleton pattern on top of it, and actually this would be even thread-safe.
Here you can find another example not using Q_GLOBAL_STATIC, but QObject inheritance and facilitates the job with QCoreApplication that we implemented in our project.
https://projects.kde.org/projects/playground/games/gluon/repository/revisions/master/entry/core/singleton.h
This version above is also-thread safe.


text:
Q: Jquery Post function return value My first question so here it goes.
My goal is to have a simple form post and if everything checks out proceed.
$.post("anotherpage.php", $("#form").serialize(),function(data){

if(data == 'sent'){
alert("True:  " + data);
}    else{
alert("False:  " + data);
}

$("#somediv").text(data);

     });

here is 'anotherpage.php'
<?php

echo 'sent';

?>

Here is my problem, '#somediv' shows the word 'sent' but my function fails every time. Also when it does fail when it alerts it looks like this. "False: s..." It makes me think I have some problem up the stream that is effecting this but I don't know what.

A: When trying to be explicit with your HTTP response, it's easy to accidentally return extra whitespace, especially at the end of your PHP block (carriage returns after the closing angle-bracket being the usual suspects).
Some tips:

*

*Make sure there is no whitespace before the start of your php block.

*Explicitly end the response with exit() on the last code line of your php block:

e.g.
  <?php

  echo 'sent';
  exit();

  ?>

There are a few cool functions in PHP regarding output control. You can buffer the output, clear it, store it or flush it. See here for more information.

A: here is 'anotherpage.php'
<?php

echo "var status='sent';";

?>

 $.post("anotherpage.php", $("#form").serialize(),function(data){
alert(date);
eval(date); // its make as perfect js var string;
    alert(date);
if(status == 'sent'){
    alert("True:  " + status );
    }    else{
    alert("False:  " + status );
    }

    $("#somediv").text(status );

         });


text:
Q: Proof that the first reappearing remainder when dividing one by a prime number is one I am trying to proof that the first reappearing remainder when dividing one by a prime number is one.
What I found is that if the expansion of $1/p$ recurs with period $k$ then $10^k-1$ is divisible by $p$.
What I don't see is how this relates to my question although it somehow should, I guess.
Thank you!
EDIT
Is it perhaps possible to proof that the first reappearing remainder when dividing one by a prime number is one directly follows from the condition that if the expansion of $1/p$ recurs with period $k$ then $10^k-1$ is divisible by $p$?

A: The remainders are the successive remainders on dividing $1,10,100,1000,10000,\dots$ by $p$. If $m\lt n$ and you get the same remainder from $10^m$ as from $10^n$ then (try to prove that) you get the same remainder from $10^0$ as from $10^{n-m}$.

A: Adapting Gerry Myerson's answer to your request, if $10^k-1$ is divisible by $p$ then the remainder from dividing $10^{k+c} = (10^k-1)\times 10^c +10^c$ by $p$ is the same as from dividing $10^c$ by $p$, so the remainders reappear.
The first remainder to reappear is $1$, which is the remainder from dividing $1$ by $p$ and from dividing $10^k$ by $p$. If any other remainder reappeared earlier, e.g. from both $10^m$ and $10^n$ with $0<m<n<k$ then $1$ would reappear even earlier than $10^n$ at $10^{n-m}$ and $p$ would divide $10^{n-m}-1$.


text:
Q: Set up a javascript time to alert if page not refreshed I have a site in production environment that reloads automatically every 3 mins. However, sometimes it gets stuck and does not update.
So I am looking for a small bit of javascript which will check the time since last page reload and if it exceeds 4 mins since last refresh then it will show me a alert that the page has not been updated since last 4 minutes or so.
Can I have a counter value which resets when page is reloaded and when if it exceeds a certain value say after 3 mins it gives a alert popup.
Can this be done?

A: Your javascript code starts executing once a page is loaded. Write some function that will be executed once the page is loaded and set timer to 4 minutes which will generate the notification. If the page reloads than the timer won't reach it's time and no notification will be generated.
Read about timer here

A: The final code for someone else if they require. Thanks for maximus help
    <script>
        function reloadCheck() {
             setInterval(function(){alert("Please Reload Page")},10000);
             }
    </script>
<body onload="reloadCheck()">
Checking page Reload
</body>


text:
Q: flush_rewrite_rules on MultiSite I'm trying to update all the permalinks on my MU install. But I'm not sure how to go about it.
This is what I have so far. But I think it's only updating the first sites permalinks.
   switch_to_blog( $site->id );
    delete_option( 'rewrite_rules' );
    global $wp_rewrite;
    $wp_rewrite->init();
    $wp_rewrite->flush_rules();
   restore_current_blog();


text:
Q: How do I set a #define for each file? What exactly is the purpose of #define in C#?
I currently develop an application using the ShareFile .NET API from https://github.com/citrix/ShareFile-NET
However, the samples don't run because the function which I want to call is in this block:
 #if Async

 #endif

I know I can do
 #define Async

at the top of the files, but do I have to do this for every file which has functions in this #if block? What's the purpose of this?

A:
do I have to do this for every file?

No. You can pass symbols ("defines") to the compiler. Using Visual Studio, you can set that on the project level, at Project -> Properties -> Build -> Conditional compilation symbols.
Using the command-line C# compiler (csc) you use the /define: flag, and when using other IDEs or compilers, see their documentation.


text:
Q: Darknet- Segmentation fault (core dumped) I'm trying to do object detection using YOLOv2 on my  custom dataset(ubuntu 18.04). The following error ocurs:-
115: nan, nan avg loss, 0.001000 rate, 17.887053 seconds, 2760 images
Loaded: 0.000045 seconds
 Very small path to the image:
 Very small path to the image:
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 4
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 7
116: nan, nan avg loss, 0.001000 rate, 17.891146 seconds, 2784 images
Loaded: 0.000038 seconds
 Very small path to the image:
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 5
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 6
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
117: nan, nan avg loss, 0.001000 rate, 17.822857 seconds, 2808 images
Loaded: 0.000036 seconds
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 4
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 6
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 8
118: nan, nan avg loss, 0.001000 rate, 17.878035 seconds, 2832 images
Loaded: 0.000035 seconds
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 6
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 7
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 5
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 31
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 10
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 16
119: nan, nan avg loss, 0.001000 rate, 17.851080 seconds, 2856 images
Loaded: 0.000033 seconds
 Very small path to the image:
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 8
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 5
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 8
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 6
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
Region Avg IOU: nan, Class: -nan, Obj: nan, No Obj: nan, Avg Recall: 0.000000,  count: 3
120: nan, nan avg loss, 0.001000 rate, 17.872121 seconds, 2880 images
Resizing
512 x 512
Loaded: 0.122598 seconds
Segmentation fault (core dumped)


text:
Q: HTML and character encoding vs HTML Entity When writing an HTML document, is it acceptable to use the direct special character such as the captial letter C with a cedilla underneath as regular text: Ç or to use the HTML Entity name of this charecter, &Ccedil ?
I have seen both being used in practice, but surely there are rules governing the appropriate usage of this, as well as advantages to one way over another. For instance, this website maintains the raw-form of this character, but other websites may end up rendering it as a square block.

A: Real characters:

*

*Are easier to type if your system is set up for a language that uses those characters

*Produce more readable code

*Save bytes

HTML entities:

*

*Let you more or less forget about character encoding

Obviously, characters with special meaning in HTML (<, &, etc) still need to be represented by entities.

A: If you're using UTF-8 character encoding, then most entity characters (other than &, > and <) become redundant.
If you're not using UTF-8, then you need entities for everything.

A: It all depends on the character encoding of the document. If you're unsure of whether or not you should use the the regular text or the encoding version, you could run your page through the W3C Validator.
Consider this code:

  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>Stuff</title>

©

©

The document encoding is set to UTF-8 and when it's validated, it returns an error:

Sorry, I am unable to validate this document because on line 7 it contained one or more bytes that I cannot interpret as utf-8 (in other words, the bytes found are not valid values in the specified Character Encoding). Please check both the content of the file and the character encoding indication.


text:
Q: WebDriverException generated from Webdriver.SendKeys in InternetExplorer on Selenium Grid When I attempt to run my IE tests on the Grid I get this stack trace

If I run the tests locally off the grid things run fine. My chrome and firefox tests both run on the grid with no issue, it just seems to be IE. Not sure what other information would be helpful any advice is greatly appreciated.
Here is the log from the node.

Test Framework:
Selenium standalone server 2.53.1
Selenium.WebDriver 2.53.1
Selenium.Support 2.53.1
Selenium.WebDriver.IEDriver 2.53.1.1
NUnit 3.4.1
.NET 4.5
   C#

Node setup
Windows Server 2008 R2 6.1
IE 11

A: My issue was not that SendKeys() wasnt working it was actually that it was just typing so slow  WebDriverException was thrown before typing could finish. https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/3072

A: I've had similar problems when using the 64-bit IE driver.  Text entry is painfully slow.  Switching to the 32-bit IE driver solves this problem.


text:
Q: Ansible module_stdout: command not found when using sudo on Centos 7 I am connecting to centos 7 virtual and physical machines using ansible with a user called ansible that has passwordless sudo permissions on all the boxes. On most machines it works, but on one box I get this error:
FAILED! => {
    "changed": false,
    "module_stderr": "Shared connection to ... closed.\r\n",
    "module_stdout": "/var/tmp/sclpbsoCZ: line 8: -H: command not found\r\n",
    "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error",
    "rc": 127
}

I set up passwordless sudo using advice from this link:
https://code-maven.com/enable-ansible-passwordless-sudo
(basically, edit /etc/sudoers to let user ansible sudo without a password)
I thought these machines were identical, but obviously something is amiss.
Adding -vvv to the ansible-playbook command lets me see that the command it is trying to run is:
'/bin/sh -c '"'"'sudo -H -S -n -u root /bin/sh -c '

How is it that this one machine isn't working with ansible?

A: I found this, but at first blush it seemed unrelated to ansible:
https://unix.stackexchange.com/questions/192809/sudo-i-returns-an-error
It turns out that centos has scl (software collections) that can be enabled.
I had devtoolset-7 enabled at boot:
https://www.softwarecollections.org/en/scls/rhscl/devtoolset-7/
This happens to wrap sudo with a script that doesn't seem to actually handle all of the options of the original sudo. It seems like this could be considered a bug  (or at least bad behavior) in devtoolset-7.
For now the fix was to remove the entry in /etc/profile.d/ that was enabling the devtoolset-7.
It was running this code:
source /opt/rh/devtoolset-7/enable
If I ssh'd into the machine and ran the offending command:
sudo -H -S -n -u root /bin/sh
It would give me the same error:
# sudo -H -S -n -u root /bin/sh
/var/tmp/sclKpdWFR: line 8: -H: command not found
And pointed me to the problem when I queried which sudo was being used...
# which sudo
/opt/rh/devtoolset-7/root/usr/bin/sudo
What a rabbit hole!


text:
Q: SQL how to map a row to column? Database structure with two 1-n connections.
User table
==========
user_id

Attribute table
===============
attribute_id
user_id
attribute_name

Attribute_Value table
=====================
attribute_value_id
attribute_id
attribute_value

Is there a way that I can receive the data in the following row style:
user_id | firstname | lastname
---------------------------
1       | Simon     | Smith
2       | John      | Doe

Where name is the first attribute_name entry from the Attribute table and lastname the second.

A: The only way you can do it with a dynamic number of columns is to use dynamic sql- use one sql statement to generate another by string concatenation.
Edit: I am not sure this is possible in mysql since there's not pivot command. Let me know if you want to see an example query from MS Sql I wrote. It is a similar data model, but there's just a lot more fields / joins.
Also I want to point out that you have a flaw in your design if attribute names wind up not being unique.

A: Since you know the names of the values that you are looking for, a join will do the trick.
select
  u.user_id,
  a1.attribute_value as firstname,
  a2.attribute_value as lastname
from User u
inner join Attribute a1
on u.user_id = a1.user_id
and a1.attribute_name = 'name'
inner join Attribute_Value v1
on a1.attribute_id = v1.attribute_id
inner join Attribute a2
on u.user_id = a2.user_id
and a2.attribute_name = 'lastname'
inner join Attribute_Value v2
on a2.attribute_id = v2.attribute_id

or so (did not run this). Use left joins if not everybody has a first or last name.


text:
Q: Powerbuilder - Updating A Window Control Obejct From Called Function Calling the function with the window w_test_1
The code for the function wf_access_test
Hi
This is a simple example to hopefully explain my problem for a more complex application.
However, I am calling this function from many different windows.  So I thought rather than 'hard code' the specific window intoduce a variable.
Unfortnately as you can see from this image powerbuilder does not like it!
I am obviously doing something wrong, but I have exhausted all avenues that I am aware of.
I'm relatively new to using Powerbuilder and the manuals don't seem to have an example of this - which does seem strange to me.
An idiot guide answer would be most appreciated.
Many thanks in anticipation.

A: Sorry, try this:
Long i
StaticText  lo_st

For i = 1 to UpperBound( iw_Window.Control[] )
    If Typeof( iw_Window.Control[i] ) = statictext! Then

        lo_st = iw_Window.Control[i]
        lo_st.text = iw_Window.ClassName()

    End If

Next

Return 0


text:
Q: What is the Taylor series of $\sqrt{z}$ around $z=-1$ How do I calculate the Taylor series of $\sqrt{z}$ around $z=-1$ in the branch that implies $\sqrt{-1}=+i$ ?
I didn't find an answer in the web.

A: Just like any Taylor series.
$$(\sqrt z)'=\frac1{2\sqrt z},$$
$$(z^{1/2})^{(n)}=\frac{(-1)^{n-1}(2n-3)!!}{2^n}z^{1/2-n},$$
Then
$$\sqrt{-1}=i,$$
$$\frac1{2\sqrt{-1}}=-\frac i2,$$ $$\cdots\\$$
$$((-1)^{1/2})^{(n)}=\frac{(-1)^{n-1}(2n-3)!!}{2^n}(-1)^{1/2-n}=-i\frac{(-1)^{n-1}(2n-3)!!}{2^n}.$$
For coherence, $(-1)^{1/2}=i$ everywhere.


text:
Q: Propagation of changes in Mercurial I have a following question. Suppose I have a bunch of repositories hosted that form an hierarchy, e.g.: A -> B -> C (means A is the central repository and all the rest are it's descendants).
Now suppose I work with the clone of C. Suppose I want to get the changes not just from C, but from the central repository, so I do the following commands:
hg pull [Address of A]
hg up

That seems perfectly legal, but what happens then I commit my changes and push them to C? Not only my local modifications will be pushed, but also the modifications of central repository (if there are any). What will happen if someone will try to pull the changes from A to C? Will there be a conflict or it will merge successfully the changes A -> local -> C with changes A -> C. Will Mercurial recognize it as the same changeset or not?
The identical situation takes place if I decide that my code is stable enough and can be placed in central repository:
hg commit -u spirit -m "A local modification that is stable"
hg push [Address of A]

What will happen if I make a pull from A to C and then pull from C to my local repo again, will it recognize these changeset as originating from my local repo, or will it report a conflict and suggest a merge?
And what is the best practice in that case anyway? Performing just subsequent pulls and pushes (i.e. A<->B, B<->C, C<->local)? But the problem is that I have just access to my local repository that is clone of C. How can I make a pull from B to C if I would want to on my local machine? How does Mercurial handle

A:
What will happen if someone will try to pull the changes from A to C? Will there be a conflict or it will merge successfully the changes A -> local -> C with changes A -> C. Will Mercurial recognize it as the same changeset or not?

The changesets that already exist in C will be seen to already exist because their IDs will already be present. This is why changes are immutable. If you could modify a changeset it's ID would change (The ID is a hash of the changeset contents). Mercurial then (correctly) sees it as a different changeset. By keeping the changesets immutable we can be sure that their hash will be the same whichever repo they come from.

*

*pull = copy changesets from over there that have IDs I haven't seen

*push = copy changesets to over there that have IDs they haven't seen

Will there be a conflict

No

or it will merge successfully the changes A -> local -> C with changes A -> C.

No merge takes place because they are the same changes. It just sees that it already has them.
Merges don't happen unless you want to combine the changes from two parallel sets of changes, and not unless you explicitly ask for it.

A: As long as the changeset are identical, i.e. they have the same id hash. Mercurial considers them to be the same.
When you modify changesets with rebase or mq commands, the id hashs change and mercurial might place two very similar changesets into a repository.


text:
Q: Technique for rendering rich-text from API with react & JSX I'am using a rich-text editor lately which sends a JSON-object to my API which includes all text and formatting.
The editor has the following options:

*

*Basic text formatting (e.g. bold, italic)

*Tag users with @username
The API then generates a HTML-string from this object and store it in the database for better performance, because the most entries are comments which are loaded in batches of 15 items.
The tagged users are striped out of this and are replaced with a placeholder {{userX}}.
The striped out data is stored separately in a values JSON-schema.
After saving to HTML it looks like this:

    Hello {{user1}},
    how are you doing?

And the values like this:
{
    "user1": {
        "text": "@anna",
        "username": "anna"
    }
}

The main reason for this is that I have to generate the links on the client-side to make it usable with the react-router.
So my thought was to render it to something like this in the client:

    Hello <Link to="/users/anna">@anna</Link>,
    how are you doing?

But afaik I'am not able to render this dynamic JSX-code in react's render function or with dangerouslysetinnerhtml.
So I think my api-design could be wrong but I'am lacking for better ideas how to solve this problem.

A: It's been a while but in the meantime the htm package was released which should have solved the problem.
With htm it is actually possible to parse a JSX-string at runtime (on server or in browser) and connect it to an React-api (Like React itself, or Preact, etc.)


text:
Q: ui-router state url issue Is here anybody able to help me with ui-router?
I don't understand the behavior of URL constructing by ui-route in the nested views.
Look at the code bellow. There are thee nested views. If I click [Courses], I see http://localhost:8080/#/courses URL. That's correct. But if I click [Course #1] next after that, the URL becomes http://localhost:8080/# . Where is the rest of URL? However, If I click [Lessons] then, URL becomes as it was expected - http://localhost:8080/#/courses/1/lessons
So, what's wrong with the middle state?
index.html
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Trial app</title>

Trial App

[Courses]
<ui-view></ui-view>

appp.js
'use strict';
var myApp = angular.module('myApp', ['ui.router']);

myApp.controller('CoursesListCtrl', function ($log, $state, $scope) {
    $scope.selectCourse = function (courseId) {
        $state.go('courses.course', {courseId: courseId});
    };
});

myApp.controller('CourseCtrl', function ($log, $state, $scope) {
    $scope.courseId = $state.params.courseId;
});

myApp.config(function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/');
    $stateProvider
        .state('courses', {
            url: '/courses',
            template: '
Courses
' +
            '[Course #1]
' +
            '<ui-view></ui-view>',
            controller: 'CoursesListCtrl'
        })
        .state('courses.course', {
            url: '/{courseId}',
            template: '
Course #{{courseId}}
' +
            '[Lessons]
' +
            '<ui-view></ui-view>',
            controller: 'CourseCtrl'
        })
        .state('courses.course.lessons', {
            url: '/lessons',
            template: '
Lessons
'
        })
    ;
});

A: Your first template should be anchor has href='#' it should be change, you could use ui-sref to create a href dynamically
Markup
[Course #1]

Above ui-sref will create and dynamic url that could have href="#/courses/1"


text:
Q: ProFTPD stops working after a few transfers My ProFTPD server is able to accept connections for a while, but after about 5-6 transfers or 10 minutes it all further transfers fail.
It doesn't matter if they are uploads or downloads, but I have noticed when uploading it often creates an empty file, then asks me if I want to overwrite it.
The only way I have found to resolve this issue is to restart the server, simply reconnecting the client does not help.
I have checked netstat and ps, and everything looks as I would have expected it to
Server: ProFTPD Version 1.3.4a
Client: FileZilla 3.5.3 (Windows)
Connection: implicit TLS

Config which may be important:
ServerType                      standalone
AllowRetrieveRestart            on
AllowStoreRestart               on
MaxInstances                    30


text:
Q: How to import 'gz'( which already exported into server ) file into mysql database using php code? Please help me to find out code for importing 'gz'file( which already exported into server using php code)  into mysql database using php code.
here i need only import code ?
thanks

A: You need the PHP function readgzfile()
If you provide more detail, I'll try to ...er... provide more detail :)

A: you can use this Snippet.
$srcName='1.gz';
$dstName='2.txt'
$sfp = gzopen($srcName, "rb");
$fp = fopen($dstName, "w");

while ($string = gzread($sfp, 4096)) {
     fwrite($fp, $string, strlen($string));
}
gzclose($sfp);
fclose($fp);

after extract with this class you can use simple below code to execute.
mysql_query(file_get_contents("2.txt"));


text:
Q: Passing global Javascript variables through callback functions to other JS files So I have an interesting problem. I declare a global variable before referencing other Javascript files, but the variable does not seem to carry through. Maybe I am missing a step somewhere?
The variable is a string that is the contents of an uploaded file like so:
function getText(s){ //creates a global variable that can hold the file
        window.text = s;
        console.log(window.text);
  };
  function handleFileSelect(event) {
    var files = event.target.files; // The file that is uploaded
      var reader = new FileReader();
     reader.onloadend = function(event){
        getText(event.target.result); //pulling out the content of the file
        loadScript('total.js',function(){ //starts app code
            window.text
        });
     };
    reader.readAsText(files[0],"UTF-8");//required to read the text
};
  try{
        document.getElementById('files').addEventListener('change',
         handleFileSelect, false); //listens for the uploaded file
  }
  catch(e){
        alert(e);
  };

So once a user uploads a file, the contents are copied into window.text like so. The contents are logged to ensure I caught the right thing. loadScript then allows for the rest of the app code to start running. I needed my program to wait for the user to specify a file before it could continue, and I had some weird quirks with AngularJS, so running it in this manner was the only workaround I could think of.
The contents of loadscript:
function loadScript(url, callback){

var script = document.createElement("script")
script.type = "text/javascript";

script.onload = function(){
    callback();
};

script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);

};
total.js begins with this line of code, which eventually leads to the output:
var csv=window.text;

Everything works. The output looks like it should...save for it's empty. Meaning window.text isn't pulling through correctly.
Is it due to the callback that it's not making it all the way through? How can I solve this?
Edit:
The function from my callback simply isn't running at all, I've figured out, so it's not an issue of passing the variable through. But PHPglue's input is still valid. Thanks.

A: Instead of window.text, just declare your variable with, which I recommend, or without the var keyword, above all of your code, like:
var windowText;
function getText(s){
    windowText = s;
    console.log(windowText);
}

In JavaScript variables automatically carry down, if they are written above other code, unless they are scoped inside a function specifically. As long as you don't use the var keyword in your function code, you can reuse windowText.