Q:

Closing MySql datareader connection

So this is a little bit code-ceptionlike.
I have a function that is checking the last ID in a table, this function is called within another function. At the end of that function, I have another function that's opening another datareader.
Error:

There is already an open Datareader associated with this connection which must be closed first.

getLastIdfromDB()
public string getLastIdFromDB()
{
     int lastIndex;
     string lastID ="";
     var dbCon = DB_connect.Instance();

     if (dbCon.IsConnect())
     {
         MySqlCommand cmd2 = new MySqlCommand("SELECT ID FROM `competitor`", dbCon.Connection);

         try
         {
             MySqlDataReader reader = cmd2.ExecuteReader();

             while (reader.Read())
             {
                   string item = reader2["ID"].ToString();
                   lastIndex = int.Parse(item);
                   lastIndex++;
                   lastID = lastIndex.ToString();
              }
         }
         catch (Exception ex)
         {
              MessageBox.Show("Error:" + ex.Message);
         }
     }

     return lastID;
}

This function is later-on used in this function:
private void addPlayerBtn_Click(object sender, EventArgs e)
{
     ListViewItem lvi = new ListViewItem(getLastIdFromDB());
     .........................................^
     ...                                    HERE
     ...
     ...   irrelevant code removed
     .........................................

            var dbCon = DB_connect.Instance();

            if (dbCon.IsConnect())
            {
                MySqlCommand cmd = new MySqlCommand("INSERT INTO `competitor`(`ID`, `Name`, `Age`) VALUES(@idSql,@NameSql,@AgeSql)", dbCon.Connection);
                cmd.Parameters.AddWithValue("@idSql", getLastIdFromDB());
                cmd.Parameters.AddWithValue("@NameSql", playerName.Text);
                cmd.Parameters.AddWithValue("@AgeSql", playerAge.Text);

                try
                {
                    cmd.ExecuteNonQuery();
                    listView1.Items.Clear();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error:" + ex.Message);
                    dbCon.Connection.Close();
                }
                finally
                {
                    updateListView();
                }
        }
}

What would be the best way for me to solve this problem and in the future be sure to close my connections properly?
UPDATE: (per request, included DB_connect)
    class DB_connect
    {
        private DB_connect()
        {
        }

        private string databaseName = "simhopp";

        public string DatabaseName
        {
            get { return databaseName; }
            set { databaseName = value; }
        }

        public string Password { get; set; }
        private MySqlConnection connection = null;

        public MySqlConnection Connection
        {
            get { return connection; }
        }

        private static DB_connect _instance = null;

        public static DB_connect Instance()
        {
            if (_instance == null)
                _instance = new DB_connect();
            return _instance;
        }

        public bool IsConnect()
        {
            bool result = true;

            try
            {
                if (Connection == null)
                {
                    if (String.IsNullOrEmpty(databaseName))
                        result = false;

                    string connstring = string.Format("Server=localhost; database={0}; UID=root;", databaseName);

                    connection = new MySqlConnection(connstring);
                    connection.Open();

                    result = true;
                }
            }
            catch (Exception ex)
            {
                Console.Write("Error: " + ex.Message);
            }

            return result;
        }

        public void Close()
        {
            connection.Close();
        }
    }
}

A:

As suggested by Pikoh in the comments, using the using clause indeed solved it for me.
Working code-snippet:
getLastIdFromDB
using (MySqlDataReader reader2 = cmd2.ExecuteReader()) {

      while (reader2.Read())
      {
         string item = reader2["ID"].ToString();
         lastIndex = int.Parse(item);
         lastIndex++;
         lastID = lastIndex.ToString();
      }
}


Q:

Porcentajes en SQL

Estoy intentando hacer una consulta en la que me muestre todos los meses del año y el total de los tres porcentajes que estoy seleccionando por mes, y le estoy dando una condición para filtrarlo por año, pero resulta que yo tengo solo datos del 2018 mas no del 2019 y al yo ejecutar la consulta me muestra los mismos resultados para los dos años cuando debería no mostrarme nada en el 2019, espero me puedan ayudar.
  SELECT MesEfic, SUM((TotalEjec*100/TotalProg) + (TotalPerAprob*100/TotalPerCap )+(TotalPerAsis*100/TotalPerProg)) / 3  as Porcentaje
        FROM [Evaluaciones].[dbo].[CAP_EfectividadProg], CAP_CoberturaProg, CAP_EficaciaProg
        WHERE CAP_EfectividadProg.Año = 2019 AND CAP_CoberturaProg.Año = 2019 AND CAP_EficaciaProg.Año = 2019
        AND MesCober = 'ENERO' AND MesEfec =  'ENERO' AND MesEfic = 'ENERO'
        OR MesCober = 'FEBRERO' AND MesEfec =  'FEBRERO' AND MesEfic = 'FEBRERO'
        OR MesCober = 'MARZO' AND MesEfec =  'MARZO' AND MesEfic = 'MARZO'
        OR MesCober = 'ABRIL' AND MesEfec =  'ABRIL' AND MesEfic = 'ABRIL'
        OR MesCober = 'MAYO' AND MesEfec =  'MAYO' AND MesEfic = 'MAYO'
        OR MesCober = 'JUNIO' AND MesEfec =  'JUNIO' AND MesEfic = 'JUNIO'
        OR MesCober = 'JULIO' AND MesEfec =  'JULIO' AND MesEfic = 'JULIO'
        OR MesCober = 'AGOSTO' AND MesEfec =  'AGOSTO' AND MesEfic = 'AGOSTO'
        OR MesCober = 'SEPTIEMBRE' AND MesEfec =  'SEPTIEMBRE' AND MesEfic = 'SEPTIEMBRE'
        OR MesCober = 'OCTUBRE' AND MesEfec =  'OCTUBRE' AND MesEfic = 'OCTUBRE'
        OR MesCober = 'NOVIEMBRE' AND MesEfec =  'NOVIEMBRE' AND MesEfic = 'NOVIEMBRE'
        OR MesCober = 'DICIEMBRE' AND MesEfec =  'DICIEMBRE' AND MesEfic = 'DICIEMBRE'
        group by MesEfic
        order by DBO.FECHANUM(MesEfic)

A:

En la forma en la que está escrita tu consulta, el problema que tienes es que estás mezclando operadores lógicos and y or de tal manera que el motor los interpreta diferente a lo que, leyendo la descripción de tu problema, entiendo que quieres.
Pero, en mi humilde opinión, tienes un problema más grave, que es el que voy a resolver, y por tanto no voy a profundizar en la explicación del primero, más que a mencionar que puedes resolverlo utilizando paréntesis para que el motor pueda interpretar las condiciones de la manera en que tú las estás pensando.
Volviendo a tu principal problema, este es que no estás haciendo explicita la condición del join de tus tablas. Escribes el query con una sintaxis que es previa al estándar SQL de 1992. Si, 1992, ¡hace casi 30 años!.
La lógica detrás de la manera en la que lo escribes, es realizar el producto cartesiano de todas las tablas involucradas y luego filtrar con la clausula where los resultados que sean de interés.
Con la llegada de la nueva sintaxis join a la clausula from del estándar, en 1992, se hizo posible definir las condiciones con las que cada tabla se integra a la consulta.
El resultado final puede ser el mismo pero, de nuevo en mi opinión, la mayor ganancia está en que podemos dividir la lógica de cómo relacionamos las tablas, con la lógica del filtrado de los resultados.
Por lo mismo, propongo que utilices join explícitos, indicando en cada caso la condición que une a las tablas. Esto hará más fácil de leer la sentencia, y casualmente, también resolverá el problema que estás observando.
SELECT   MesEfic
       , SUM((TotalEjec*100/TotalProg) + (TotalPerAprob*100/TotalPerCap )+(TotalPerAsis*100/TotalPerProg)) / 3  as Porcentaje
  FROM   [Evaluaciones].[dbo].[CAP_EfectividadProg]
         inner join CAP_CoberturaProg on CAP_CoberturaProg.Año = CAP_EfectividadProg.Año and CAP_CoberturaProg.MesCober = CAP_EfectividadProg.MesEfec
         inner join CAP_EficaciaProg on CAP_EficaciaProg.Año = CAP_EfectividadProg.Año and CAP_EficaciaProg.MesEfic = CAP_EfectividadProg.MesEfec
 WHERE CAP_EfectividadProg.Año = 2019
 group by MesEfic
 order by DBO.FECHANUM(MesEfic)


Q:

Multiple joins sql

I have a query which must contain 3 joins, however I get this error:

Syntax error (Missing operator)

The SQL:
SELECT
    Agents.[PF],
    Agents.[User_ID],
    Agents.[First_Name],
    Agents.[Second_Name],
    Agents.[Third_Name],
    Agents.[Family_Name],
    Agents.[Gender],
    Agents.[Contract_Type],
    Agents.Area,
    Teams.Team_Name,
    Agents.Hiring_Date,
    Resignation_Pool.Resignation_Date,
    Resignation_Pool.Effective_Date,
    Replace(
          IIf(Skills.Skill_Directory IS NULL, '', 'Directory, ')
        + IIf(Skills.Skill_TRC IS NULL, '', 'TRC, ')
        + IIf(Skills.Skill_Prepaid IS NULL, '', 'Prepaid, ')
        + IIf(Skills.Skill_Postpaid IS NULL, '', 'Postpaid, ')
        + IIf(Skills.Skill_KeyAccount IS NULL, '', 'KeyAccount, ')
        + IIf(Skills.Skill_Blackberry IS NULL, '', 'Blackberry, ')
        + IIf(Skills.Skill_Broadband IS NULL, '', 'Broadband, ')
        + IIf(Skills.Skill_Concierge IS NULL, '', 'Concierge, ')
        + IIf(Skills.Skill_ISP IS NULL, '', 'ISP, ')
        + IIf(Skills.Skill_Mada IS NULL, '', 'Mada, ')
        + IIf(Skills.Skill_CSCS IS NULL, '', 'CSCS, ')
        + '$', ', $', ''
    ) AS Skills
FROM Agents
LEFT JOIN Resignation_Pool
    ON Agents.PF = Resignation_Pool.PF
LEFT JOIN Teams
    ON Agents.Team = Teams.ID
LEFT JOIN Skills
    ON Agents.PF = Skills.PF
WHERE Agents.Contract_Status = 'Active'

What is causing this error?

A:

MS Access requires parentheses around JOIN syntax with multiple tables.  You will need to use something similar to this:
FROM ((Agents
LEFT JOIN Resignation_Pool
    ON Agents.PF = Resignation_Pool.PF)
LEFT JOIN Teams
    ON Agents.Team = Teams.ID)
LEFT JOIN Skills
    ON Agents.PF = Skills.PF


Q:

Changing Android Device Admin Settings

If you go into your android device to Settings-> Security, under the Device Administration section there are some settings for Verify Apps.
While working on AOSP, I am trying to get some testing software to work. So part of that requires I enable and disable this feature. I already have code to disable some other features, they look like this:
    //Allow mock locations
    Settings.Secure.putInt(getContentResolver(),
            Settings.Secure.ALLOW_MOCK_LOCATION,
            1);

    //Stay on while plugged in
    Settings.Global.putInt(getContentResolver(),
            Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
            BatteryManager.BATTERY_PLUGGED_USB);

Note* I am running as root so I can change these settings. So to clarify, my question is how to change the settings Verify Apps, where is that located?

A:

You're looking for Settings.Global.PACKAGE_VERIFIER_ENABLE. It doesn't seem to be up on the documentation site, but you can see it in the source.
Definition:

android.provider.Settings.java

Example usage by the default settings app:

com.android.settings.SecuritySettings.java


Q:

Solve linear system for equal polynomials

I'm having trouble solving the following equality:
$$x^5 + 25x^4 + 250x^3 + 1250x^2 + 3124x + 3120 $$
$$=$$
$$ax^5 + (b+c)x^4 +(10c+3d)x^3 + (d(b+c))x^2 + (24a+62d)x + 104e$$
It's supposed to end up in an augmented matrix form, so I can solve it with gaussian elimination and the likes, but it has been forever since I've dealt with this. Any tips on how to begin? I also couldn't think of more relevant search topics, so I apologize.
I recall something to do with, instead of just equating the coefficients of the terms with the same exponents, I should instead factor out the variables I want to find out. So I did that, but couldn't go much further.

A:

I don't think this'll turn up linear immediately because of the $d(b+c)$ term. If you have to end up with some kind of linear system in matrix form, you could do this:
First off, notice that $b+c = 25$ by equating the $x^4$ coefficients. Then leave the $b+c$ with the $x^4$ untouched, but change $d(b+c)$ to $25d$.
If you now want a matrix-form of this system, I suppose you could plug in $5$ values of $x$ in both sides, and then write that out.
For example taking $x = 1 $ in both sides leads to $7770 = 25 a+b+11 c+90 d+104 e $, so the first row of your matrix would be $\left(25,1,11,90,104\right)$.
$$
\begin{pmatrix}
  25 & 1 & 11 & 90 & 104 \\
  ? & ? & ? & ? & ? \\
  ? & ? & ? & ? & ?  \\
  ? & ? & ? & ? & ?  \\
  ? & ? & ? & ? & ?
\end{pmatrix}
\begin{pmatrix}
  a \\ b \\ c \\ d \\ e
\end{pmatrix}
=
\begin{pmatrix}
  7770 \\ ? \\ ? \\ ? \\ ?
\end{pmatrix}
$$
Spoiler:

 If you want to avoid huge values, try plugging in $x = -6, -5, -4$.


Q:

Using Maximize with LABColor

I'm writing a function that, given a color, returns a contrasting color.  It does this by maximizing the ColorDistance between the input and output colors.  However, I'm getting an error that's complaining about how LABColor[l, a, b] is symbolic and not a color, which it is until Maximize gives it numerical value (and ultimately does find a nominally contrasting color).  What do I do to LABColor to stop this error?
(Note that I don't think this scheme for finding contrasting colors is particularly good, I just want to know how to fix this error for general knowledge)
(* bounds of RGB space in LAB space *)
rgbCube = Cuboid[{0, -0.8, -1.13}, {1, 0.94, 0.94}];

(* Find a highly contrasting color *)
Maximize[
 ColorDistance[Pink, LABColor[l, a, b]], {l, a, b} \[Element]
  rgbCube]

ColorDistance: Pink and LABColor[l, a, b] should be two valid color directives, images, or lists of objects with the same dimension.

Out[1]= {2.00573, {l -> 0., a -> -0.8, b -> -1.13}}

A:

You can avoid that warning by stating that they are numeric like this:
rgbCube = Cuboid[{0, -0.8, -1.13}, {1, 0.94, 0.94}];
f[l_?NumericQ, a_?NumericQ, b_?NumericQ] := ColorDistance[
     RGBColor[1, 0.5, 0.5], LABColor[l, a, b]]
Maximize[f[l, a, b], {l, a, b} \[Element] rgbCube]


Q:

CLRMD Architecture MisMatch

I am working on CLRMD library and trying to load a dump. I am getting Mismatched architecture between this process and the dac. Console applicatin which is x86 application which creates a string array.
static void Main(string[] args)
    {
        string[] strArray = null;

        for (int i = 0; i < 100; i++)
        {
            strArray = new string[100];
            strArray[i] = "One";
            System.Threading.Thread.Sleep(1000);
            Console.WriteLine(i);
        }

        Console.Read();
    }

I used 32Bit TaskManager to create a dump and when I load the dump I get the Architecture mismatch error.

dataTarget.Architecture is Amd64 and PointerSize 8.

But When same application process is attached, dataTarget.Architecture is x86 and Pointersize is 4.

Don't know when this difference. am I missing something when I am taking the dump. Please let me know how to load the dump into CLRMD
thanks in advance.

A:

It is a very straight-forward mismatch, your program runs as a 32-bit process but the minidump was created from a 64-bit process.  The DAC does not support mixing.
You have to remove the jitter forcing so your program runs as a 64-bit process as well.  Project > Properties > Build tab, change the Platform target setting to AnyCPU and untick the "Prefer 32-bit" checkbox.  Repeat for the Release configuration.
Do note that the solution platform name is not relevant to this setting, a possible reason your test console app turned out to be a 64-bit process even though you thought it targeted x86.  You can double-check with Task Manager, Details tab, add the "Platform" column.


Q:

change selected combobox value in javascript

i have 2 combobox , if i select value "foto" , the other combobox will show #foto_cat. when i choose "panen" the foto_cat is hidden and else. if not choose, the foto_cat is hidden too.
this is my script

    Kategori Report :
    <?php
            $options = array(
              '0'  => '--------',
              'panen'  => 'Panen',
              'foto'  => 'Foto',
            );
            echo form_dropdown('combo[combo1]',$options,'0','id="combo1"');
        ?>

Kategori Foto :
    <?php
            $options = array(
              '0'  => '--------',
              'pupuk'  => 'Pemupukan',
              'pelihara'  => 'Pemeliharaan',
            );
    echo form_dropdown('combo[combo5]',$options,'0','id="combo5"');
        ?>

the question is . how to change combobox id=combo5 when i choose in combo1 value = "0" the combobox combo5 will select same value = 0 and hide other option, when i choose value "foto" the combobox is show and the option will show too?.
sory for my bad english.

A:

try something like
 function SetSel(val)
    {
        var secondCombo = document.getElementById ( "cmb" );
        secondCombo.value = val.value;
    }


Q:

Sum of Combinations with Variable Sample Size

I was working on a problem and this specific sum came up. I've tried simplifying it or evaluating it with no luck, and a quick search didn't get me what I'm looking for. Essentially, I need the sample size to change on each term:
$$\sum_{i=1}^n{{i}\choose{k}}, k\in\mathbb{N}$$

A:

Observe that
$$\binom{i}{k} = 0$$
when $k > i$ since it is not possible to select a subset with more elements than the set contains.  Hence,
$$\sum_{i = 1}^{n} \binom{i}{k} = \sum_{i = k}^{n} \binom{i}{k}$$
We will show that
$$\sum_{i = k}^{n} \binom{i}{k} = \binom{n + 1}{k + 1}$$
The right hand side counts the number of $k + 1$ element subsets of a set with $n + 1$ elements.  It remains to show that the left hand side counts the same quantity.
Consider $k + 1$ element subsets of the set $S_{n + 1} = \{1, 2, 3, \ldots, n, n + 1\}$ with largest element $i + 1$.  Observe that for such a subset to exist, $k \leq i \leq n$.  In order to form a $k + 1$ element subset of $S_{n + 1}$ with largest element $i + 1$, we must select $k$ of the $i$ elements in the subset $S_i = \{1, 2, 3, \ldots, i\} \subseteq S_{n + 1}$, which can be done in $\binom{i}{k}$ ways.  Hence, the number of $k + 1$ element subsets of the set $S_{n + 1}$ is
$$\sum_{i = 1}^{n} \binom{i}{k} = \binom{n + 1}{k + 1}$$
This is known as the hockey-stick identity.


Q:

Can I suspend iScroll functionality?

I want to disable the scroll sometimes so I can do multi-touch events in the same area, something like...
if event.originalEvent.touches.length is 2 then myScroll.disable()

Is something like this possible?

A:

myScroll.disable()

Then on touchend
myScroll.enable()

:)


Q:

How to get value from dynamic checkbox and textbox

Hey guys i have a problem to get value from my checkbox and textbox which i added dynamically. This is my checkbox and textbox display

This is my html code to call my checkbox and textbox
<fieldset data-role="controlgroup" id="pilihtambahan" style="margin-top: 5px;">

</fieldset>
 $.ajax({
            url: host+'/skripsi3/phpmobile/tambahbarang.php',
            data: { "id": getacara},
            dataType: 'json',
            success: function(data, status){
                console.log(data);
                $.each(data, function(i,item){

            $("#pilihtambahan").append('<input class="tambahsewa" type="checkbox" value="'+item.idbarang+'" name="cektambah" id="'+item.idbarang+'">'+item.namabarang+' @ Rp.'+item.harga+',-<input type="text" id="'+item.idbarang+'" name="jumsewa" placeholder="Jumlah Sewa '+item.namabarang+'">
').trigger("create");

                });

            },
            error: function(){
                console.log("error");
                //output.text('There was an error loading the data.');
            }
        });

and this is my tambahbarang.php
<?php
session_start();
include "config.php";
$idacara=mysql_real_escape_string($_GET["id"]);
//$arr = array();
$result=mysql_query("select * from barangsewa where id_acara='$idacara'");
if (!empty($result))
{
    while ($row=mysql_fetch_array($result))
    {
        $fetchbarang[] = array
        (
            'idbarang' => $row['id_barang'],
            'namabarang' => $row['namabarang'],
            'harga' => number_format($row['harga'], 0, ',', '.'),
            'kosong' => "tidak"
        );
    }
}

mysql_close($con);

header('Content-Type:application/json');
echo json_encode($fetchbarang);
?>

Maybe someone can help me.
Thank You and Have a nice day!! Cheersss!!

A:

$('#pilihtambahan input[type=checkbox]:checked, #pilihtambahan input[type=text]').each(function(index, element){
    console.log($(element).val());
});


Q:

Amazon RDS Aurora vs RDS MySQL vs MySQL on EC2?

I've been looking around for best practices when setting up your database on the cloud but it still isn't clear to me which of the following solutions should we be going for?

Amazon RDS Aurora
Amazon RDS MySQL
MySQL on EC2 instances

I see Amazon Aurora being marketed as the better alternative however after some research it doesn't seem like people are using it. Is there a problem with it?

A:

You should benchmark Aurora carefully before you consider it. Launch an instance and set up a test instance of your application and your database. Generate as high of load as you can. I did at my last company, and I found that despite Amazon's claims of high performance, Aurora failed spectacularly. Two orders of magnitude slower than RDS. Our app had a high rate of write traffic.
Our conclusion: if you have secondary indexes and have high write traffic, Aurora is not suitable. I bet it's good for read-only traffic though.
(Edit: the testing I'm describing was done in Q1 of 2017. As with most AWS services, I expect Aurora to improve over time. Amazon has an explicit strategy of "Release ideas at 70% and then iterate." From this, we should conclude that a new product from AWS is worth testing, but probably not production-ready for at least a few years after it's introduced).
At that company, I recommended RDS. They had no dedicated DBA staff, and the automation that RDS gives you for DB operations like upgrades and backups was very helpful. You sacrifice a little bit of flexibility on tuning options, but that shouldn't be a problem.
The worst inconvenience of RDS is that you can't have a MySQL user with SUPER privilege, but RDS provides stored procs for most common tasks you would need SUPER privilege for.
I compared a multi-AZ RDS instance versus a replica set of EC2 instances, managed by Orchestrator. Because Orchestrator requires three nodes so you can have quorum, RDS was the clear winner on cost here, as well as ease of setup and operations.

A:

I don't use Aurora personally, but I can HIGHLY recommend RDS over running your own on EC2. Having the failover happen automatically and also the backups is just worth every penny. Especially since RDS isn't that much more expensive.
Aurara looks really good on paper, but the more flexible choice of instances has kept me at PostGreSQL until now. We're looking at migrating to Aurora though, mainly because of the autoscaling storage provisioning and the higher performance.

A:

AWS RDS is the managed database solution which provides support for multiple database options Amazon Aurora, PostgreSQL, MySQL, MariaDB, Oracle, and Microsoft SQL Server. When you go with RDS it will provide inbuilt configuration options such as.

Database Replication for High Availability
Read Replicas for Scalability
Backups & Restore
Operating system and software patches & etc.

This simplifies the overhead of database administration. However the flexibility is limited to the RDS offerings.
Alternatively if you host your database in EC2 instance, you can install the required versions of the database engines, install needed extensions & etc. which provides more flexibility but also requires expertise & adds administration overhead.
When you consider Amazon Aurora in RDS, it differs from the rest of the engines because, its new and fully implemented by Amazon from ground up and offers higher performance, reliability out of the box (As marketed by Amazon) with reasonable pricing. However one limitation with Aurora is that its not included in AWS free-tier, where the smallest instance type it supports is "small".
Note: Some of the features offered by RDS and cost differs, based on the database option you select.


Q:

if telnet is disabled will imap_open() work

I am trying to connect to my mailbox on my hosting via imap_open() (php) . But its throwing authentication failed error.
According to my hosting provider they have disabled telnet for security reasons. Could disabling telnet cause php to not be able to make an imap connection ??

A:

No. These are different protocols. IMAP is working on port 143 and telnet on port 23. Your confusion likely comes from the fact that IMAP is a text based protocol and you can use the telnet client program to control an IMAP session.
If the error messages states that the authentication failed, this is a strong hint that the IMAP server is working and answering your connection attempts but you somehow failed to offer proper credentials.


Q:

Weird Behavior of RecyclerView

I have a Fragment which has a RecyclerView in it.
On top of the RecyclerView, I place a View.
But to my surprise. RecyclerView is still swipable, isn't it suppose to be blocked by the View. How is it possible that it still receives touch events?
Any thoughts on this please? How can I prevent RecyclerView from receiving touch events when a View is on top of it?

A:

As you have View On RecyclerView and you want to prevent touch on RecyclerView, you need to add TouchListener on View. Adding TouchListener on View will prevent touch on RecyclerView.

((View)findViewById(R.id.view)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(activity, "view clicked", Toast.LENGTH_SHORT).show();
            }
        });

If there is no touch event binded with the topmost view then it goes to the next layout.


Q:

How can I SELECT rows with MAX(Column value)?

My table
ODR_NBR |   Snbr12      |   appot_nbr      | Creatins_ts
1       |   4001        |   2458           | 11/24/2015 4:38:00 PM
1       |   4001        |   2458           | 11/22/2015 4:50:00 PM
2       |   4005        |   3598           | 11/27/2015 4:38:00 PM
2       |   4005        |   3598           | 11/24/2015 4:20:00 PM

My table after sql
ODR_NBR |   Snbr12      | Creatins_ts
1       |   4001        |  11/24/2015 4:38:00 PM
2       |   4005        |  11/27/2015 4:38:00 PM

A:

This should give you the result you want:
Sample data:
CREATE TABLE table1 (ODR_NBR int ,  Snbr12     int ,  appot_nbr    int   ,Creatins_ts datetime)

 INSERT INTO table1
 VALUES
    (1       ,  4001        ,  2458           ,'11/24/2015 4:38:00 PM'),
    (1       ,  4001        ,  2458           ,'11/22/2015 4:50:00 PM'),
    (2       ,  4005        ,  3598           ,'11/27/2015 4:38:00 PM'),
    (2       ,  4005        ,  3598           ,'11/24/2015 4:20:00 PM')

Query:
    SELECT ODR_NBR ,  Snbr12  ,  MAX(Creatins_ts) AS Creatins_ts
    FROM table1
    GROUP BY ODR_NBR ,  Snbr12

Results:


Q:

Varying results when trying to handle errors in database login form

I am making a application which will verify a login to a MySQL Server, which is being done with an ADODB.Connection, then open up another HTA if no errors are given. I am trying to achieve this using nothing but HTA, VBScript and hard work … Without going into too much detail, I would like to catch an error message which will come up if the user puts in the wrong username/password.
Normally,  if you do put in the wrong password or username, it comes up with a HTML Error message, which doesn't look very user friendly. That's what this code is trying to catch and make more friendly. Code segment below:
Sub MainLogin_click
  dim strError
  Uname = usertext.Value
  Pword = passtext.Value
  cstring = "DRIVER={MySQL ODBC 5.2w Driver};SERVER=Localhost;UID=" & Uname _
    & ";PWD=" & Pword & ";DATABASE=maindb;"
  conn = CreateObject("ADODB.Connection")
  On Error Resume Next
  conn.Open cstring
  Call MakeDSN
  If Err.Number <> 0 Then
    strError = "LongBow Error" & VbCrLf & " Error Number: " & Err.Number _
      & VbCrLf & " Error Source: " & Err.Source _
      & VbCrLf & " Error Description: " &  Err.Description
    MsgBox(strError)
    Err.Clear
  Else
    Set objShell = CreateObject("WScript.Shell")
    objShell.Run("bin\LongBowAgent.hta")
    Window.close
    conn.Close
  End If
  On Error GoTo 0
End Sub

Basically when I run this code, and my HTA as a whole, either

Nothing happens, no activity when the 'login' button is pressed.

or

I get a nice error box (even with the right username/password) saying
Error 424, VBScript runtime error, object Required.

Honestly - I've been at this for 2 days now and tried many things. None have really worked, but then Google Searching can only do so much.
Any Help, and any advise would be great. I do not mind trying something completely different here, so long as it stays within HTA & VBScript.

A:

The scope of your OERN is to large - it does not only hide errors of the .Open, but also problems in MakeDSN and in the error handling code.
Ironically, the first culprit is not covered by the OERN:
conn = CreateObject("ADODB.Connection")

is wrong, because you assign an object. Try
Set conn = CreateObject("ADODB.Connection")


Q:

How can I get Cassini web hosting framework to work without adding it to GAC?

I am trying to use Cassini (from http://www.asp.net/Downloads/archived/cassini/) to host my old style asp.net web service in-process, ideally in a WCF style. However, when I run it, I get an exception that the Cassini.dll could not be found. The Readme.txt that comes with it says to add it to the GAC, but the whole point of using an inprocess hosting is to avoid installing stuff in global places. Any ideas how to make it work without the GAC? Or maybe some other alternatives?

A:

Extract the WebDev.WebHost DLL from your GAC. It has no other dependecies apart from the .NET Framework itself. You can then reference it locally, and instantiate a Server object from it which has a Start() and - hooray - a Stop() method.
I normally browse to the GAC folders at a command prompt and copy files out, but if you Google you'll find other approaches.

A:

Found the way to use the Cassini as well: I had to put Cassini.DLL in the Bin directory under the application root for the your web application.
Source: http://forums.asp.net/p/869425/869846.aspx


Q:

Change only the local TimeZone to Default UTC using Javascript

I need to change the local or current TimeZone to Default UTC (GMT+0000) time zone.
I used the predefined javascript function toLocaleString, but some machines has their own datetime format so the service request gets mismatched.
My requirement is just change the TimeZone without changing the current value (NO CONVERSTION)
let dtime = new Date();
console.log(dtime);

Output: Fri Jul 07 2017 17:07:32 GMT+0530 (India Standard Time)
Required Format is Fri Jul 07 2017 17:07:32 GMT+0000 (???)
Scenario: I'm selecting DOB in DatePicker (Angular Material), Its returning the datetime offset value. If I pass those value from client to Server, it automatically converts it to Local to UTC Default.
For Example: I'm selecting DOB as 1990-01-01 in datepicker, it returns the value 1990-01-01 00:00:00 but in HTTP call it goes as 1989-12-31 18:30:00. Because I'm in INDIA (UTC +0530), so it subtracts the 05 Hours and 30 Minutes. This is the issue I'm facing.
Kindly assist me.

A:

You can try the following piece of code
date.setMinutes((date.getTimezoneOffset() * -1));

No need of localization, use this code just before doing any service call. It will pass you the exact date what you selected in the datepicker.
It will work in all timezone (+) and (-),
Example: 1990-01-01 00:00:00 GMT+0530 (India Standard Time), the above said code covert it as 1990-01-01 05:30:00 GMT+0530 (India Standard Time). While on Service it converts it as 1990-01-01 00:00:00.
I think it will solve your problem.


Q:

Does Devi Bhagavata Purana asserts that Sita was Mandodari and Ravana's Daughter?

According to Wikipedia Sources, Devi Bhagavata Purana mentions Mandodari was Sita's Mother, as well the same is mentioned in Abhuta Ramayana, If So, Where is the Respective Mentions for the Same.

A:

Note: The story about the origin of Sîtâ Devî runs thus :-- Râvana,
  the king of Ceylon (Lankâ) practised very severe austerities and got
  extraordinary powers. He brought the three worlds under his
  subjection, levied taxes from all. The Devas and all the other
  inhabitants of the several worlds paid their taxes, as imposed by
  Râvana. Râvana sent messengers to the Risis and the Munis, the
  ascetics, dwelling in forests and asked them to pay their taxes. The
  Risis replied that they had no property. But Râvana insisted.
  The Risis gave, then, blood, cutting their thighs, in a jar that was
  carried to Lankâ. Râvana kept that jar under the custody of his queen
  Mandodarî, and instructed her that the jar contained poison and that
  she should not eat that. Mandodarî, however, ate a portion of that,
  out of curiosity, and became pregnant and gave birth to a daughter.
  Fearing Râvana, she floated the jar with the daughter, in the ocean,
  which, floating through oceans and rivers, came and touched the lands
  of the King Janaka. The peasants while tilling, found that and took
  the girl to the king, who reared her as his daughter. Thus Sîtâ, born
  out of the blood of the Brâhmanas, took away subsequently the kingdom,
  life, and all of Râvana.

Another version is this :-- As before, the messengers advised the
  Munis to give something; otherwise Râvana would insist and put them to
  various troubles. So the Munis cut their thighs and gave blood as
  their tax, saying that that blood in the jar would cause ruin and
  desolation to the country where it will be kept. Râvana, hearing this,
  ordered the jar to be carried to the kingdom of the king Janaka, thus
  causing ruin to him. The jar was brought and placed in the fields of
  Janaka. Now it happened that there was a very severe drought; rains
  were absolutely wanting; and a dire famine was imminent. The Brâhmin
  Pundits informed the king that if the king and his wife ploughed
  themselves the fields, rains would fall. So the king with his wife did
  that, the king holding the plough and the queen holding the hand of
  the king. The fore end of the plough accidentally hit upon that jar,
  out of which came out Sîtâ Devî with two women Riddhi and Siddhi,
  waving chowries on her two sides. The two ladies disappeared and Sîtâ
  Devî looked like a girl. The king Janaka reared her, as if his
  daughter. Sîtâ Devî used to lift daily with her left hand the bow of
  S’iva, kept in the king’s house, and daily worshipped that, and thus
  cleansed the place. Seeing this, the king Janaka pledged the vow that,
  whoever would break the S’iva’s bow, would marry Sîtâ.

Both these above accounts of Sri Sita's origin are given by the translator as notes on Devi Bhagavatam's 3rd Book's 28th Chapter.
So, as per both these stories, Ravana was somehow involved in the process but he was in neither cases the father. In both the versions it was the blood of the Munis, that Ravana brought, which was responsible for the birth of Sita.
As per the 1st version however, Mandodari, Ravana's wife, actually gave birth to Sita from her womb.
Now, coming to the question whether the aforementioned Purana itself contains these stories or not then it seems - No - because otherwise it wouldn't have been necessary for the translator to give them separately as footnotes under a chapter of that same Purana.


Q:

How to force Maven to download maven-metadata.xml from the central repository?

What I want to do is to force Maven to download the 'maven-metadata.xml' for each artifact that I have in my local repository.
The default Maven behaviour is to download only metadata from remote repositories (see this question).
Why I want to do that:
Currently I have a remote repository running in a build machine. By remote repository I mean a directory located in the build machine that contains all dependencies that I need to build my Maven projects. Note that I'm not using a repository manager like Nexus, the repository is just a copy of a local repository that I have uploaded to my build machine.
However, since my local repository did not contain the 'maven-metadata.xml' files, these metadata files are also missing in the build machine repository. If I could retrieve the metadata files from the central repository, then it would be possible to upload a working remote repository to my build machine.

A:

You don't want to get the metadata from the public repositories, it will contain all the versions available of a given artifact, whereas your repository will have some subset of the releases.
It's worth pointing out that you really would be better off with a repository manager. The following steps allow you to generate your artifact metadata once. But if your needs change, you'll have to repeat the process or update the files manually, so why not just use a manager? Nexus can run standalone and has a very small footprint.

Even if you're not planning on using Nexus for a repository manager, you can still use it to generate your metadata.

First install Nexus.
Locate the nexus work directory (by default ${user.home}/sonatype-work.
Copy your local repository contents to the nexus-work/releases sub-directory.
Start Nexus and connect to the Nexus home page in the browser (by default http://localhost:8081/nexus)
Log in using the admin account (password admin123)
Click on the repositories link on the left hand side.
Select the Releases repository, right-click and click Rebuild Metadata

In a few moments you should have the metadata generated for all the artifacts. You can then copy them to wherever you need them to be and uninstall Nexus.

A:

The default repositories are defined in the super pom.xml that all poms inherit from by default.
If by local you mean you want to only use ~/.m2/repos/* then work in offline mode. Add  <offline>true</offline> to your settings.xml
If by local you mean your local server, you could install a repository manager like Nexus, modify your settings file to use nexus under "mirrors" like this:
<mirror>
  <id>central-proxy</id>
  <mirrorOf>central</mirrorOf>
  <url>my/local/nexus/server</url>
</mirror>

And disable remote repositories you don't want in Nexus.


Q:

Set & Get methods - Java

I am new to Java and have been set some tasks to complete, so far I have completed the first section shown below:
"1. Design a class Manual with the following properties:
serial number - string, - default:??????
title - string, - default: Untitled
author - string, - default: Unknown
Write a constructor and a method to print details of a Manual on the console. "
Code:
public class Manual {

    String serialNumber, title, author;

    public static void main(String [] args){
        Manual man= new Manual();
        man.printDetails();
    }

    public Manual(){
        serialNumber = "??????";
        title = "Untitled";
        author = "Unknown";
    }

    public void printDetails(){
        System.out.println("Serial Number = " +serialNumber+" Title = "+ title+" Author = "+author);}

}

For the next section I have been required to:
"2. Amend your Manual class by writing the following additional methods: methods to set and get the properties of a Manual
a method to ask the user for details of a Manual
a toString() method. "
So far I have attempted the set & get method part of the section and my code is as follows:
public class Manual {

    String serialNumber, title, author;

    public static void main(String [] args){
        Manual man= new Manual();
        man.printDetails();
    }

    public Manual(){
        serialNumber = "??????";
        title = "Untitled";
        author = "Unknown";
    }

    public String getserialNumber(){
        return serialNumber;
    }

    public String gettitle(){
        return title;
    }

    public String getauthor(){
        return author;
    }

    public void setserialNumber(String serialNumber){
        serialNumber = ??????;
    }

    public void settitle(String title){
        title = Untitled;
    }

    public void author(String author){
        author = Unknown;
    }

    public void printDetails(){
        System.out.println("Serial Number = " +serialNumber+" Title = "+ title+" Author = "+author);}

}

Would anyone be able to tell me wether the code I have thus far is correct & if any changes need to be made. Also, any help assisting on the next tasks will be appreciated.
Thank you

A:

You're on the right track. I can see you're confused about your setters. Title, Author, and Serial Number are variables accessible to the whole class, so in your setters you can directly place values inside of them. In the parameter of your setters, you should have a different name than the names of these variables. For example:
public void setTitle(String t)
{
    title = t;
}

the function will have a string passed through its parameters (String t) and that value is placed inside title. Right now, you're placing the default values into the variable setters, and that is incorrect. The default values are for the default constructor, which you did correctly. To help you understand a little more, I'll give you an example of what your test classes might look like:
Manual myManual = new Manual(); //now that the Manual Object has been instantiated,
                                //the variables contain the default values from your
                                //default constructor.

myManual.setTitle("Some Title"); //"Some Title" was passed through the parameters of the
                                 //setTitle method, and the title variable in Manual is equal
                                 //that value

On a side note, you could always capitalize the beginning of a word following the first word in titles of methods, variables, etc. setTitle, getAuthor, etc

EDIT:
The first snippet of code is how your setters should look in the Manual class. You should change all your setters to look similar in format. The second few lines with all the comments would be in the main method.
Also, I looked at your pastebin code and you still are setting the variables in your setters to the default values. That is not correct. You should be setting your variable to whatever was passed through the parameter.


Q:

Form with target="_blank" returning PDF not working in home screen web-app

In my Angular app I have a form with target="_blank" which, after submit, returns a PDF.
This works fine in every browser, but not if I do it from my homescreen icon of the web-app in Android/Chrome.
There is a new window opening but it stays blank, and the PDF does not show.
What needs to be done to be able to view the PDF?

A:

My initial goal was to have the PDF displayed embedded in a new tab.
Of course this can not work from an iOS homescreen icon.
After some trying I found the best way to resolve my issue was to simply get rid of target="_blank".
It looks all the browsers handle it fine and offer a download-dialog, and actually display the PDF when selecting "download".


Q:

Problem using GWT-VL?

I'm trying to evaluate GWT validation library with a very simple example taken from the author site.
and here is a code snippet
validator.addValidators( "birthYear",new IntegerValidator(schoolName_txt, 1890, 2009)
                .addActionForFailure(new StyleAction("validationFailedBorder"))
                .addActionForFailure(new LabelTextAction(error_label))
                );

but the problem is that when I run the application I got the following error:
no property localization given for key: birthYear

but I'm sure that I have included this key in my localization files,so what is this?
Thanks

A:

To get rid of this error message you have to extend ValidationMessages:
import eu.maydu.gwt.validation.client.i18n.ValidationMessages;
public class CustomValidationMessages extends ValidationMessages {
  @Override
  public String getPropertyName(String propertyName) {
    return propertyName;   // This just returns the property name instead of the error message
  }
}

Then change pass an instance of this class to the ValidationProcessor instance instead of just an empty parameter:
ValidationProcessor validator = new DefaultValidationProcessor(new CustomValidationMessages());

The purpose of this I suppose to give you a chance to change the displayed input name in the error message if your app is multi-language.


Q:

Insert into #tmp table using lin2db

I have a set of tables I need to run some queries against.
2-3 tables used are the same so makes sense to create a tmp table (limited access to the server so no views, stored proc solutions please).
Any idea how to achieve that using linq2db?
TIA

A:

using (var db = new DataConnection()
{
    var tempTable = db.CreateTable<MyTempTable("#tmp");

    (
        from t in ...
        select t...
    ).Insert(tempTable, t => new MyTempTable { Field1 = t.... });
}


Q:

Where is the root morpheme in Modern English evacuate and vacuum?

They both are cognates (it can be easily proved by many etymological sources). The question is : Is it possible to consider VAC as a common root for evacuate and vacuum (we may go further - vacation, vacancy, vacuous etc.).

A:

Clearly they are related through Latin, from e- and vacare (out of and to empty) and from vacuus (empty), and in Latin the shared morpheme is vac-.
More interesting may be the relationships with vain, vast and waste which have similar origins in Latin or proto-Indo-European, but which have more specific meanings in modern English.


Q:

How to bind a key to issue two commands in visual mode?

This question is more general than the problem I am currently faced with, and may not have a solution. But my real problem may have a solution if there is no general solution.
What I want to do is if I use y from visual mode, I want Vim to yank both to the + register and to the regular " register.
I don't care about clobbering the system clipboard, because there are tools I use to record past clipboard entries. I just want a way to yank to clipboard which is easy enough to perform that I may actually make use of it.
Possible approaches

bind key to function which somehow hopefully can grab the range of the selection, and then stick it into both registers -- i think this can be done, i have a magic snippet in my vimrc that does this. I have no idea how it works. Looks like this: vnoremap <silent> x :<C-u>execute 'normal! vlF' . nr2char(getchar()) . 'of' . nr2char(getchar())<CR>
yank and then call function that explicitly copies " register to + register. Not sure how to do a yank and then call some function. might be easier
???
no direct profit likely

A:

set clipboard^=unnamedplus

See :help 'clipboard'.

I don't care about clobbering the system clipboard, because there are tools I use to record past clipboard entries. I just want a way to yank to clipboard which is easy enough to perform that I may actually make use of it.

Clobbering the system clipboard is precisely a rather big issue with synchronizing the unnamed register and the clipboard register when you use a system-wide clipboard manager. It becomes hard to find what you are looking for, which is probably buried below dozens upon dozens of meaningless entries. Think about that.
Another option could be to remap y in visual mode to yank to the system clipboard:
 xnoremap y "+y

Since all yanks are sent to the unnamed register no matter what, the command above will effectively yank the visual selection to the unnamed register and the clipboard register. This is in my opinion a much cleaner solution than using 'clipboard'.


Q:

AWS Gateway API and file response

Is it possible for AWS Gateway API to respond with a file (zip file) from a HTTP endpoint integration? I heard somewhere AWS Gateway API doesn't support binary formats but wasn't sure if that was for input or input and output.
I have an existing HTTP endpoint and I want to add AWS Gateway API over it; it currently returns a file (zip) on the response.

A:

You cannot respond with a Zip(any binary type) file using API Gateway so far. (As stated in AWS official forum)
As a work around, you can store your file on S3 and dispatch the link of the file using API Gateway.


Q:

Which Version of Exchange Server 2013 should i use

I'm setting up an Exchange Server for private use.
On this Exchange Server there will be up to 10 Users.
Now i don't know which version of Exchange 2013 i have to use.
I saw that the Exchange 2013 Standard has 5 mailbox databases and the Enterprise Version 100 mailbox databases.
But what is a Mailbox Database? Does it need 1 mailbox database per user?
If it's so: i need the Exchange Server 2013 Enterprise for 10 users, right?
Sorry if the question is a little bit stupid, but i just want to be sure.
Thank you for your answer and have a nice weekend!

A:

you don't need a mailbox database per user. You can configure all 10 user mailboxes within one mailbox database.
you only need more than 5 mailbox databases if you are using a really big setup with distributed servers and/or database availability groups for high availability.
So, according to your requirements Exchange 2013 Standard Edition should be fine.


Q:

Ошибка RuntimeException при загрузки картинки из галереи в ImageView

Мне нужно, чтобы при нажатии на ImageView можно было загрузить картинку из галереи в этот ImageView. При тестировании на телефоне при открытии картинки перед ее помещением в ImageView возникает ошибка
public class EditProfile extends AppCompatActivity {

    private final int PICK_IMAGE_REQUEST = 1;
    private static final int STORAGE_PERMISSION_CODE = 911;
    private String imagePath;
    ImageView ivEditProfil;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_profile);

        ivEditProfil = (ImageView) findViewById(R.id.iv_edit_profil);

        requestStoragePermission();
        ivEditProfil.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showFileChooser();
            }
        });
    }

private void showFileChooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_PICK);
    startActivityForResult(Intent.createChooser(intent, "Выберите изображение"), PICK_IMAGE_REQUEST);
}

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

            Uri selectedImageUri = data.getData();
            imagePath = getRealPathFromURI(selectedImageUri);

            Picasso.with(this)
                    .load(new File(imagePath))
                    .resize(200, 200)
                    .centerCrop()
                    .into(ivEditProfil);
        }
    }

    private String getRealPathFromURI(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        android.support.v4.content.CursorLoader loader = new android.support.v4.content.CursorLoader(this, contentUri, proj, null, null, null);
        Cursor cursor = loader.loadInBackground();
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String result = cursor.getString(column_index);
        cursor.close();
        return result;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (requestCode == STORAGE_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "Предоставлены права на чтение.", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "Права на чтение не были предоставлены.", Toast.LENGTH_LONG).show();
            }
        }
    }

    //Requesting permission
    private void requestStoragePermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
            return;
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            //If the user has denied the permission previously your code will come to this block
            //Here you can explain why you need this permission
            //Explain here why you need this permission
        }
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
    }
}

Ошибка:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=file:///storage/emulated/0/download/21-54-59-photo.jpg typ=image/jpeg flg=0x1 }} to activity {com.halfway.yogamylife/com.halfway.yogamylife.EditProfile}: java.lang.NullPointerException: Attempt to invoke interface method 'int android.database.Cursor.getColumnIndexOrThrow(java.lang.String)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3744)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3787)
at android.app.ActivityThread.access$1500(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1424)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:5529)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int android.database.Cursor.getColumnIndexOrThrow(java.lang.String)' on a null object reference
at com.halfway.yogamylife.EditProfile.getRealPathFromURI(EditProfile.java:241)
at com.halfway.yogamylife.EditProfile.onActivityResult(EditProfile.java:227)
at android.app.Activity.dispatchActivityResult(Activity.java:6508)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3740)
... 9 more

A:

Attempt to invoke interface method 'int android.database.Cursor.getColumnIndexOrThrow(java.lang.String)' on a null object reference

У Вас cursor в функции getRealPathFromURI равен null, вероятнее всего loadInBackground() ничего не возвращает.


Q:

Boolean value won't change

I'm working on a small program that basically just shows that I know how to use superclasses. Everything works great except my boolean value. It's supposed to ask the use of they would like to sign up for the mailing list. If "yes" is entered, the boolean should be true, if "no" is entered it should be false. My problem is that even when I enter "no" it still registers as "yes" making the boolean value true. Please help? (I hope that made some semblance of sense.)
 import java.util.Scanner;

public class CustomerDemo
{
    public static void main(String[] args)
    {
        String name;
        String address;
        String telephone;
        int customerNumber;
        String input;
        boolean mail = false;

        Scanner keyboard = new Scanner(System.in);

        System.out.print("Enter your name: ");
        name = keyboard.nextLine();

        System.out.print("Enter your address: ");
        address = keyboard.nextLine();

        System.out.print("Enter your phone number: ");
        telephone = keyboard.nextLine();

        System.out.print("Enter your customer number: ");
        customerNumber = keyboard.nextInt();

        keyboard.nextLine();

        System.out.print("Do you want to be on the mailing list (Yes or No): ");
        input = keyboard.nextLine();

        if (input.equalsIgnoreCase("yes")) {
            mail = true;
        }

        Customer cust = new Customer(name, address, telephone, customerNumber, mail);

        System.out.println("Hello " + cust.getName() + "!");

        System.out.println("You are customer " + cust.getCustomerNumber() + ".");

        if(mail = false){
            System.out.println("You are not on the mailing list. ");
        }

        else {
            System.out.println("You are on the mailing list. ");
        }
    }
}

A:

You're not doing a comparision, you're doing an assignment...
This if(mail = false), equates to if (false) because false is assigned back to mail...
Do if(!mail) this instead, which equates to if (!true) (or you can also do if(mail == false) if you really, really want to)


Q:

How do I pass value to MVC3 master page ( _layout)?

I have a custom modelbinder, its check the authentication cookie and return the value.
public class UserDataModelBinder<T> : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {

        if (controllerContext.RequestContext.HttpContext.Request.IsAuthenticated)
        {
            var cookie =
                controllerContext.RequestContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];

            if (cookie == null)
                return null;

            var decrypted = FormsAuthentication.Decrypt(cookie.Value);

            if (!string.IsNullOrWhiteSpace(decrypted.UserData))
                return JsonSerializer.DeserializeFromString<T>(decrypted.UserData);
        }

        return null;
    }
}

if I need to use it, I just need to pass it to the action. everything works.
public ActionResult Index(UserData userData)
{
    AccountLoginWidgetVM model = new AccountLoginWidgetVM();
    if (null != userData)
        model.UserData = userData;

    return View(userData);
}

However, I want to use it in my master page, because once user login, i want to display their info on the top on every page.  I tried a few things, coudln't get it work
 @Html.RenderPartial("LoginPartial", ???model here??)

A:

We did it as follows:

Defined separate viewmodel for masterpages.
public class MasterPageViewModel
{
    public Guid CurrentUserId { get; set; }
    public string CurrentUserFullName { get; set; }
}

Added injection filter and filter provider.
public class MasterPageViewModelInjectorFilterProvider: IFilterProvider
{
    public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        return new [] {new Filter(new MasterPageViewModelInjectorFilter(), FilterScope.Action, null), };
    }

    private class MasterPageViewModelInjectorFilter: IResultFilter
    {
        public void OnResultExecuting(ResultExecutingContext filterContext)
        {
            var viewResult = filterContext.Result as ViewResult;
            if (viewResult == null)
                return;

            if (viewResult.ViewBag.MasterPageViewModel != null)
                return;

            //setup model whichever way you want
            var viewModel = new MasterPageViewModel();
            //inject model into ViewBag
            viewResult.ViewBag.MasterPageViewModel = viewModel;
        }

        public void OnResultExecuted(ResultExecutedContext filterContext)
        {
        }
    }
}

Configure filter provider:
//in Application_Start
FilterProviders.Providers.Add(new MasterPageViewModelInjectorFilterProvider());

Use in master:
ViewBag.MasterPageViewModel

This way you have fine uncoupled architecture. Of course you can combine it with Dependency Injection (we do, but I left it out for clarity) and configure your action filter for every action whichever way you want.


Q:

If statement searches values only in specific order

I am loading two JSON files and iterate them in order to replace values from of the JSON's using references from the other.
{"Target":{
 "TV_1":{
                "id":"001_101_001",
                "query_name":"tvchview",
                "param":{"$source":"tv","$channel":["RTL","rrr"]},
                "target_group_type":"multiple",
                "mapping_list":{}
            },
  "TV_2":{
                "id":"001_101_003",
                "query_name":"tvch_1hr",
                "param":{"$source":"tv"},
                "target_group_type":"multiple",
                "mapping_list":{}
            }}}

{"Target_queries": {
"tvchview":{
             "name":"tvchview",
             "description":"Select panelists that have watched a tv channel at least one time.",
             "sql":"SELECT DISTINCT pnr, channel AS value FROM $source WHERE channel IN ( $channel ) AND slice_start >= $startdate AND slice_start <= $enddate ;"
               },
  "tvch_1hr":{
             "name":"tvch_1hr",
             "description":"Select panelists that have watched tv channels for at least one hour.",
             "sql":"SELECT pnr, channel AS value FROM $source WHERE slice_start >= $startdate AND slice_start <= $enddate AND duration >= 3600 AND channel != '-' GROUP BY pnr, channel;"
              }}}

My code works when the JSON files look like this, but when I switch the places of TV_1 and TV_2 (TV_2 goes in the place of TV_1) my code doesnt return anything, meaning it doesnt match the two dicts by name and query_name.
This is the part of code where i replace the values:
for (k, v), (k1, v1) in zip(params_to_replace.items(), queries.items()):
    if v1['name'] in v['query_name']:
        params = v['param']
        split_queries = v1['sql'].split()
        final_string = ' '.join(str(params.get(word, word)) for word in split_queries)
        final_string = re.sub(r'(\[)|(\])', '', final_string)
        replaced_queries[k] = final_string
    else:
        pass

v1['name'] is where the name of the queries are ("name":"tvchview") and v['query_name'] is the names, but in the other JSON ("query_name":"tvchview"). When I switch again the structure of the queries it works again. Somehow the if statement search only when the order of the query names matches on both files. Any ideas?

A:

I think the problem is with the zip statement, which only joins two entries. Instead you want to test all possible combinations. For this you can use itertools.product
The corrected code:
import re
import itertools
params_to_replace = {
    "TV_2": {
        "id": "001_101_003",
        "query_name": "tvch_1hr",
        "param": {"$source": "tv"},
        "target_group_type": "multiple",
        "mapping_list": {}
    },
 "TV_1":{
                "id":"001_101_001",
                "query_name":"tvchview",
                "param":{"$source":"tv","$channel":["RTL","rrr"]},
                "target_group_type":"multiple",
                "mapping_list":{}
            },
}

queries = {
"tvchview":{
             "name":"tvchview",
             "description":"Select panelists that have watched a tv channel at least one time.",
             "sql":"SELECT DISTINCT pnr, channel AS value FROM $source WHERE channel IN ( $channel ) AND slice_start >= $startdate AND slice_start <= $enddate ;"
               },
  "tvch_1hr":{
             "name":"tvch_1hr",
             "description":"Select panelists that have watched tv channels for at least one hour.",
             "sql":"SELECT pnr, channel AS value FROM $source WHERE slice_start >= $startdate AND slice_start <= $enddate AND duration >= 3600 AND channel != '-' GROUP BY pnr, channel;"
              }}

replaced_queries = {}

for (k, v), (k1, v1) in itertools.product(params_to_replace.items(), queries.items()):
    if v1['name'] in v['query_name']:
        params = v['param']
        split_queries = v1['sql'].split()
        final_string = ' '.join(str(params.get(word, word)) for word in split_queries)
        final_string = re.sub(r'(\[)|(\])', '', final_string)
        replaced_queries[k] = final_string
    else:
        pass

print(replaced_queries)

{'TV_2': "SELECT pnr, channel AS value FROM tv WHERE slice_start >= $startdate AND slice_start <= $enddate AND duration >= 3600 AND channel != '-' GROUP BY pnr, channel;", 'TV_1': "SELECT DISTINCT pnr, channel AS value FROM tv WHERE channel IN ( 'RTL', 'rrr' ) AND slice_start >= $startdate AND slice_start <= $enddate ;"}


Q:

Spring Data JpaRepository findAll(Iterable ids) + findAll(Sort sort)

With Spring Data JpaRepository is there any capability to get select collection of given Id with some sorting. That mean I need to make enable following query. I have found some solution apply with @NamedQuery but I can't make enable it because I am using Spring-data-jap 1.4.2.RELEASE. Thanks.
public Iterable<User> findAll(Iterable<Integer> userIds) {

 Sort sort = new Sort(Direction.ASC, "name");

 Iterable<User> users = userRepository.findAll(userIds, sort);

 return users;
}

A:

Just declare a query method like this:
public interface UserRepository extends Repository<User, Integer> {

  Iterable<User> findByIdIn(Collection<Integer> ids, Sort sort);
}


Q:

Annoying php error

I have spent the last 6 hours searching the web and looking over my code but yet I continue to get this error message.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '$register' at line 1

here is my code (well the part that I believe the problem lies with):
$month = $_POST['month'];
$day = $_POST['day'];
$content = $_POST['content'];
$title = $_POST['titlename'];
$author = $_POST['author'];

$register = mysql_query("INSERT INTO posts (month, day, author, content, title) VALUES ('$month', '$day', '$author', '$content', '$title')");
    mysql_query('$register');
    echo mysql_error();

I have a table called "posts", the spelling is correct on everything, and all the quotes have mates. I am completely stumped. The really weird part is, I have compared it to previous code of mine that actually works and there really is no difference.
PS I do realize that I shouldn't use user inputs directly into the table, however I am going to be the only one accessing this table. I am making this table to make my life easier.

A:

Remove quotes..
 mysql_query($register);

Update
You are running you sql query twice. Remove mysql_query('$register');


Q:

Realtek rtl8821ce wifi driver problem in Linux Mint 18.2

I've installed Linux Mint 18.2 on my ThinkPad E470. I can't connect to wifi as no wireless option shows up. I searched around and found an old post with the exact problems as mine - https://ubuntuforums.org/showthread.php?t=2187780. But the solution to it is old and doesn't work for the new linux. And, lspci doesn't list my wifi adapter model. I also tried the solution given by Pilot6(Can't post the link as i have an upper limit on no. of links). But it doesn't work. This is the output of lspci -knn | grep Net -A2. https://pastebin.com/mMa6465h
04:00.0 Ethernet controller [0200]: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller [10ec:8168] (rev 10)
    Subsystem: Lenovo RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller [17aa:505b]
    Kernel driver in use: r8169
    Kernel modules: r8169
05:00.0 Network controller [0280]: Realtek Semiconductor Co., Ltd. Device [10ec:c821]
    Subsystem: Lenovo Device [17aa:c024]

Please guide further.

A:

Worked solution (Requirements: kernel >=4.11) :
(UPD: In the latest release of endlessm you need kernel version 4.15)

Download driver directory from this repo:
https://github.com/endlessm/linux/tree/master/drivers/net/wireless/rtl8821ce

You can do it by this link:
    https://minhaskamal.github.io/DownGit/#/home?url=https://github.com/endlessm/linux/tree/master/drivers/net/wireless/rtl8821ce

Unpack zip archive.
Change the Makefile. Line "export TopDIR ?= ..." to export "TopDIR ?= PATH TO EXTRACTED DIRECTORY".
make
sudo make install
sudo modprobe -a 8821ce


Q:

Q:python: why is my char considered as a str?

I just started python and I'm stuck on a stupid error but I don't understand why it's not working
def encryption(str1):
    i = 0
    for x in str1:
        if (x >= 'a' and x <= 'z' or x >= 'A' and x <= 'Z'):
            str1[i] = str1[i] + 3 % 26 #str[i] = x + 3 % 26
        i+=1
    return str1

when I execute the program I got this error:

TypeError: string indices must be integers, not str.

Can someone explain me why str[i] - 23 is considered as a str ? To me I'm just modifying the ascii value of a char.

A:

Strings in python are not arrays like in C. They are immutable, ie
you can't make in place changes to the string. Your options are turn
the string into a list (similar to a c array) or make a new empty string
and concatenate each encrypted letter onto it (this will probably be faster). Ord converts string to ascii number and chr converts the inverse.
the isalpha method tests true iff the character is in {a-z A-Z}
str1 = 'this is a test string!@#$@#$@'

def encryption(str1):
    new_string = ''
    for character in str1:
        if character.isalpha():
            new_string += chr(ord(character) + 3 % 26)
        else:
            new_string += character
    return new_string

print(encryption(str1))


Q:

Moving a movie strip into next free channel

If a script tries to move a movie strip to a channel that is full, does the script abort with an error?
Is there a flag I could use, to increment the strips channel so it moves the strip to the next free channel?
How could I do this?

A:

If a script tries to move a movie strip to a channel that is already full, it automatically moves to the next empty channel.


Q:

How to search a webpage using selenium by any of the keywords inputted?

I am new to selenium in python. I am searching the supreme website by keywords using Xpath as such:
WebDriverWait(driver, 5).until(EC.element_to_be_clickable(
    (By.XPATH, "//a[contains(text(),'Supreme Time Tee')]"))).click()

My question is how would I search keywords for any text and skip until it finds it? For example, I struggle to grab the t shirt labeled "Dragon Tee Heather Grey" that is split into two a href link tags "Dragon Tee" and "Heather Grey".
I want to be able to click either element but I am not sure how to construct this.

A:

can you try this xpath:
 //a[contains(text(),'Dragon Tee')] /parent::div/following-sibling::*/a[contains(text(),'Dusty')]


Q:

GKE Menu interface workloads continous delivery

Since few days I notices in GCP Kubernetes Engine, Workloads actions menu a new command : Continous Delivery. But it's inactive and even the Learn more doesn't work.
Is it a new features, an easy CD integration ? How to use it ?
Thank you
Menu UI Continous Delivery

A:

It seems that this is a feature that will become available in the future,
There’s an issue tracker for this [1], if you follow the link and if logged in with any Google Account, you can click the star on the top left to receive updates on this.
For the meantime, I think that this document it’s what I think the “learn more” will point to [2]. I cannot confirm that this will be the document linked in the future.
Cheers!

[1] https://issuetracker.google.com/142372527
[2] https://cloud.google.com/solutions/continuous-delivery/


Q:

open policy agent - OPA - How to use --config-file from kubernetes configmap object

I am trying to setup my OPA as below.

OPA installed as a sidecar in Kubernetes
Policy will be managed as bundle
OPA policy will be stored and served from a separate service [ Bundle ]
OPA need to be configured using config-file to get the policy from external service
config-file will be stored as a config map in kubernetes.
That config map need to be used in --config-file

My config map in kubernetes
kubectl create configmap policyconfig --from-file=./config/config.yaml

My Sidecar OPA
 - name: opa
          image: openpolicyagent/opa:latest
          args:
            - "run"
            - "--server"
            - "--addr=0.0.0.0:443"
            - "--addr=0.0.0.0:8181"
            - "--config-file=policyconfig"
      volumes:
        - name: policyconfig
          configMap:
            name: policyconfig

Let me know if it is possible to implement in this way

A:

You can use kube-mgmt as sidecar for managing OPA on top of Kubernetes.
kube-mgmt automatically discovers policies stored in ConfigMaps in Kubernetes and loads them into OPA. kube-mgmt assumes a ConfigMap contains policies if the ConfigMap is:

Created in a namespace listed in the --policies option. If you specify --policies=* then kube-mgmt will look for policies in ALL namespaces.
Labelled with openpolicyagent.org/policy=rego

https://medium.com/capital-one-tech/policy-enabled-kubernetes-with-open-policy-agent-3b612b3f0203
Update:
With your current setup and requirement you need to add a volumeMounts to make it work
 - name: opa
          image: openpolicyagent/opa:latest
          args:
            - "run"
            - "--server"
            - "--addr=0.0.0.0:443"
            - "--addr=0.0.0.0:8181"
            - "--config-file=policyconfig"
          volumeMounts:
          - name: policyconfig
            mountPath: /config
      volumes:
        - name: policyconfig
          configMap:
            name: policyconfig


Q:

My 3D object looks different when exporting it to Unity?

I'm new to blender and Unity so my Question is simple , My Design lost some materials like some colors after Importing it to Unity , I exported it as .fbx file and Imported it to unity.
Here is The design from Blender :

and here is it after importing it to Unity and lost some colors , and looks bad not like in blender (note I didn't use textures in Blender just colors from Blender itself) :

Any help is Appreciated .

A:

It sort of looks like you have a subsurf modifier on the object. Unity doesn't actually take the raw blender file when you import it as an asset. It actually exports the blender model as an fbx and then imports that into Unity. Exporters tend to apply modifiers before they export. What Unity is allowing you to do is sit back while it does all of the export/import work for you. It's also going to have some wonkiness when it comes to translating the materials so you should always use a UV texture even if you're just talking about a flat color on the object just so you have some predictability and control.


Q:

Log output to file and system log at the same time

I am trying to diagnose an issue in an app I have written. The issue is a sporadic one, and occurs only under real-world conditions: in the field, away from my PC, and when I’m in the middle of something else, with no resources to spare for immediate debugging. Therefore, my best bet is collecting and analyzing log data.
Unfortunately, by the time I realize the issue has struck again and get around to debugging it, any log data has already rotated out of the Android log as I frequently have other chatty apps running at the same time. Increasing the size of the log buffer has not helped (either Android does not honor it or other apps are still too chatty) so I have abandoned this route.
For this reason, I am now considering having my app log to a separate text file in addition to the regular log.
Now I could easily double every call like
Log.i(TAG, "something happened");

adding another call that writes the same thing to the log file—but that does not seem very elegant to me.
Another option would be to replace all calls to Log with a wrapper that writes the event both to the Android log and the log file.
Question: Does the Android API provide a built-in mechanism for this, i.e. telling Log to write its data to the default log and a text file at the same time? Or do I need to code this by myself?
Edit:
Assumptions:

I know where in my code I need to generate log output (which can happen anywhere, which may or may not involve an exception) and what I want to be written to the log.
Getting log data from the device to my PC is also not a concern (one-man show, I just plug my phone into my PC and transfer the log file).

If you know the current Android API has no built-in mechanism to achieve what I want, then ”no, Android does not support this” is a perfectly acceptable answer. In that case the solution is clear—I would fall back to the wrapper function. I am specifically not looking for a different approach to the problem.

A:

After doing some more research, it seems the Android API does not provide a standard way to do this. There are two possible workarounds:
Mirror output at the source

System.out and System.err output, which is written to the console in desktop systems, writes to the log on Android. These two can be redirected into any PrintStream of your choice, which would give you all Java console output. You can subclass PrintStream to duplicate its input, feeding it into the default stream as well as into a file of your choice.
Create a class which exposes the same methods as android.util.Log. In each method, call through to the respective android.util.Log method and additionally log the data to a file. If you call your class Log (but with a different package name, e.g. org.example.Log), then all you need to do is replace imports of android.util.Log with an import of your class, and any Log method calls will go to your class.

Caveats: This will only give you data explicitly logged by your code (i.e. for which you have the source files), as well as anything that goes to System.out or System.err. It will not include log output from JAR libraries (if you cannot modify their source code), nor any output generated by the system (such as stack traces from default exception handlers) or by other processes (some of which may be system processes and report conditions related to your process).
Read the logs from the command line
This article explains how to read the logs from within Android. In a nutshell:

Android includes a command line utility called logcat on the device, which will give you a continuous feed of log messages until stopped. (Try it by adb shelling into your device and running it. It has a bunch of command-line options to control its behavior. Not sure if it is present on all distributions, though.)
Launch this command via Runtime.getRuntime().exec("logcat"), then obtain the input stream of the process returned. This will give you an input stream of log messages.
According to the article, your app needs the android.permission.READ_LOGS permission to read logs.

I have read statements that certain versions of Android (4.2 was mentioned) do not allow this permission to be granted to non-system apps, though. According to my own tests, behavior without this permissions differ: Anbox will return the full logcat, while LineageOS (tested on 15.1) will only show log entries from the app which called it (including previous instances, presumably everything associated with the same Linux user). This can be a limitation or a welcome filter feature. YMMV.
logcat conveniently has a command line option, -f, to specify an output file. I tried
Runtime.getRuntime().exec("logcat -f " + absolutePathToLogFile);

and logcat keeps logging as long as the app’s process runs. Killing the app (by clicking the X in the title bar on Anbox) apparently also terminated the child process.
Now you can either run this code when your app starts up, or you can turn this functionality into a separate app which starts on boot and continuously collects logs for all apps.
Caveats: This may fill up your storage space quickly if you have some chatty apps running (which is why entries rotate out of the logcat so quickly in the first place). It is recommended to make log mirroring configurable (e.g. via Preferences) and/or ensure old files are deleted regularly. Also, if you keep the logcat process running until your app terminates, you will not be able to access the file over MTP as there is no easy way to run the media scanner (if you scan the file while it is still written to, it will appear truncated over MTP until another media scan runs).


Q:

gcc link the shared library in specified path but not in the standard path

I came across a strange issue when using gcc to link the shared library in specified path but not in the standard path.
When I downloaded GNU readline library version 6.3 and compiled it successfully in path $HOME/Downloads.
GNU readline library needs to link libtinfo, so I installed it by sudo apt-get install libtinfo.
After that, I created a small sample test named rl.c to check it. To build my sample project, I also created two symbolic links like follow:
$ ls -lrt ~/Downloads/
drwxr-xr-x 6 sfzhang sfzhang    4096 Mar  2 15:45 readline-6.3
lrwxrwxrwx 1 sfzhang sfzhang      12 Mar  2 16:00 readline -> readline-6.3

$ ls -lrt ~/Downloads/readline-6.3/shlib/
-rwxr-xr-x 1 sfzhang sfzhang 833856 Mar  2 15:36 libreadline.so.6.3
lrwxrwxrwx 1 sfzhang sfzhang     18 Mar  2 16:28 libreadline.so -> libreadline.so.6.3

To use the new built readline library, I export the path to LD_LIBRARY_PATH:
$ echo $LD_LIBRARY_PATH
/home/sfzhang/Downloads/readline/shlib

And, I compiled rl.c using the following command:
$ gcc -o rl rl.c -I$HOME/Downloads -L$HOME/Downloads/readline/shlib -lreadline -ltinfo

Checking the rl linked libraries:
$ ldd rl
linux-vdso.so.1 =>  (0x00007fffe09a3000)
libreadline.so.6 => /lib/x86_64-linux-gnu/libreadline.so.6 (0x00007fe22d243000)
libtinfo.so.5 => /lib/x86_64-linux-gnu/libtinfo.so.5 (0x00007fe22d01a000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fe22cc8d000)
/lib64/ld-linux-x86-64.so.2 (0x00007fe22d492000)

I also tried anther command, but got the same result:
gcc -o rl rl.c -I$HOME/Downloads -L$HOME/Downloads/readline/shlib -lreadline -ltinfo -Wl,-rpath,$HOME/Downloads/readline/shlib

So, why the rl was liked to /lib/x86_64-linux-gnu/libreadline.so.6 but not $HOME/Downloads/readline/shlib/libreadline.so.
OS: Linux debian 3.2.0-4-amd64 #1 SMP Debian 3.2.65-1+deb7u1 x86_64 GNU/Linux
gcc: gcc version 4.7.2 (Debian 4.7.2-5)
ldd: ldd (Debian EGLIBC 2.13-38+deb7u6) 2.13

A:

You need a symbolic link called libreadline.so.6 too, not just libreadline.so. The reason is that the soname of libreadline.so.6.3 is libreadline.so.6.
A soname is a "generic" name embedded in the library itself. When you link against a shared library that has a soname, it is that name that gets embedded in your executable and is later looked up by the dynamic linker. (For shared libraries without sonames the filename is used instead, though this is uncommon.) You can tell what the soname of a library is by running e.g.
objdump -p <library> | grep SONAME

The point of sonames is to make it so that your executable is linked against the most generic library name that should be compatible (usually this is the library name with just the major version -- 6 in this case -- tacked on), rather than just the specific (e.g., minor bug fix release) version that you happened to link against.
The output from ldd also tells you that it's looking specifically for libreadline.so.6.


Q:

Rounding price to the nearest multiple of 5cent in java

I'm new to java programming. I would like to round up a price to the nearest 2 decimal places.
E.g.
38.82 into 38.80
38.87 into 38.90
38.85 stays the same.
I did the E.g. 1 and E.g. 2 but it comes out only 1 decimal place. E.g. 38.82 to 38.8
this is my code:
import java.text.DecimalFormat;

public class RoundUp {

    public static void main(String[] args){
        DecimalFormat df = new DecimalFormat("#.##");
        double num = 38.84;
        System.out.println(df.format(Math.round(num*10.00)/10.00));
    }
}

I have looked into other model answers by experts in this web but none of it really answer my question. Setting into 2 decimal places, I'm using DemicalFormat. That I know, but rounding the number, let's say 38.83 to 38.85 and 38.87 to 38.90 is what I really want. It is a rounding system that my country is using. Can check it out here.
And please everybody.. please don't change my question to a duplicate one. you think that its a duplicated one, please ask me for more info. I can ensure you that it is not a duplicated (I think...)

A:

One way to do this is to convert the price to cents, divide by 5, round to, multiply by 5 again and convert back to dollars:
double rounded = Math.round(num * 100.0 / 5.0) * 5.0 / 100.0;


Q:

Regular Expression for IP address separated by comma or *

I want to build a RegEx that will match with a string of IPs separated by comma (,) OR string will have only *. String should not have both IP address & *

Validate IP i.e 1.1.1.1 (Numbers and . dot char). Also, * alone is allowed
* is present, no other IPs should be present.

This is the regex
(((25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)(,\n|,?))|(,*))

Testing string:
192.168.1.1,192.56.3.23,189.35.2.2,198.23.45.56,198.168.1.255

How do I check for *?

A:

You may use
^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|\*)(?:,\s*(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|\*))*$

See the regex demo
Expanded//verbose/free-spacing version:
^         # start of string
 (?:      # start of a grouping
  (?:     # start of another grouping
   (?:25[0-5]|2[0-4]\d|[01]?\d\d?)\. # First octet and .
   (?:25[0-5]|2[0-4]\d|[01]?\d\d?)\. # Second octet and .
   (?:25[0-5]|2[0-4]\d|[01]?\d\d?)\. # Third octet and .
   (?:25[0-5]|2[0-4]\d|[01]?\d\d?)   # Fourth octet
   |\*                               # or just a * char instead of an IP
  )                                  # end of another grouping
 )                                   # end of grouping
 (?:,\s*             # a group that will repeat 0+ times, matches , then 0+ whitespaces
  (?:                # an IP matching grouping
   (?:25[0-5]|2[0-4]\d|[01]?\d\d?)\. # First octet and .
   (?:25[0-5]|2[0-4]\d|[01]?\d\d?)\. # Second octet and .
   (?:25[0-5]|2[0-4]\d|[01]?\d\d?)\. # Third octet and .
   (?:25[0-5]|2[0-4]\d|[01]?\d\d?)   # Fourth octet
  |\*)                               # Or a *
 )*                                  # ... zero or more times
$                                    # end of string


Q:

Prove that $\int_{\mathbb{R}} \frac{1}{(a^2+t^2)(b^2+t^2)} dt= \frac{\pi}{ab(a+b)}$

Prove that $\int_{\mathbb{R}} \frac{1}{(a^2+t^2)(b^2+t^2)} dt= \frac{\pi}{ab(a+b)}$

For $a,b>0$, the Fourier transform of $f(x) = e^{-a|x|}$ is $\widehat{f}(t) = \dfrac{2a}{a^2+t^2}$.
Otherwise, we have $\int_{\mathbb{R}}\dfrac{1}{(a^2+t^2)^2} dt= \dfrac{\pi}{2a^3} $.
I have to show that $\int_{\mathbb{R}} \dfrac{1}{(a^2+t^2)(b^2+t^2)} dt= \dfrac{\pi}{ab(a+b)}$ ?
I have no idea to do it. Could someone help me ?

A:

Hint:
$$\frac{1}{(a^2+t^2)(b^2+t^2)}=\frac{1}{b^2-a^2}\left(\frac{1}{a^2+t^2}-\frac{1}{b^2+t^2}\right).$$


Q:

Edit Value In Excel Range

I have an excel sheet with values in a range which I want to perform some calculations on in vb.net. I pass that range to vb.net using COM. When I try editing the values of the range, nothing happens.
My question seems to be very similar to these questions, but I can't quite figure out what step I am missing.
How to edit cell value in VB.net - Using .Interop.Excel
VB.net Office Solution - Accessing value in named Range in a Worksheet
VBA CODE:
Function MyTestRange (Byref myrng as range)

   Set classLib = New VBProject.CClass
   MyTestRange = classLib.MyTestRange(myrng)

End Function

VB.NET code
Imports Microsoft.Office.Interop.Excel

Public Class CClass
    Function MyTestRange(ByRef myrng As Range) As Double
     Dim newrng As Range
     Dim b As Integer = myrng.Rows.Count
     Dim i As Integer

     newrng = myrng
     For i = 1 To b
         newrng.Value2(i, 1) = myrng.Value2(i, 1) + 1
     Next i
     MyTestRange = newrng.Value2(1, 1)
    End Function
End class

While this code doesn't generate an error, it doesn't change the values in newrng.
Edit:
I have tried many iterations based on the link provide, but always get the same error :
An exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll but was not handled in user code
Additional information: Exception from HRESULT: 0x800A03EC
This is the simplest way to generate the error:
    Dim c As Object

    c = myrng.Value
    myrng.Value = c

Hence amending the values to something new, seems out of reach!
Edit 2:
After chatting with user Mat's Mug, I tried to edit a value in a range, purely in VBA.
This sub works perfectly:
Sub rangesub()
 Dim example As Range
 Set example = Range("A1:A4")
 example.Value = Application.Transpose(Array(1, 2, 3, 4))
End Sub

Excel functions also seem able to handle passing ranges:
Function SimpleCopyRange(myrng)
 SimpleCopyRange = myrng
End Function

A very simple combination of this code works:
Function EditRange(myrng)
 Dim example As Range
 Set example = Range("A1:A4")
 EditRange = example
End Function

However there is an unspecified error if I try to edit the range:
Function EditRange(myrng)
 Dim example As Range
 Set example = Range("A1:A4")
 example.Value = Application.Transpose(Array(1, 2, 3, 4))
 EditRange = example
End Function

The application.transpose part obviously adds a layer of complexity, and can be replaced with example.Value = 8 without any changes in results.

A:

Looking at this question/answer:
Excel VBA: Iterating over range parameter and change cell values
It appears that a UDF can only change the calling cell.
I think therefore this method is impossible.
The workaround is to to rewrite the code to work with an array, assign the range to an array, edit the array and pass it to the new function.


Q:

Generating power using a black hole's accretion disk?

Could you power a starship by feeding matter into a black hole and collecting the plasma produced by the tidal forces ripping apart whatever you fed it, or is this impossible/impractical? I keep reading about how black hole starships can harvest the energy produced by the black hole's Hawking radiation to propel the ship, but this honestly doesn't seem that outstanding relative to the amount of effort you'd need to expend creating the damn black hole, especially when the sweet spot seems to be a power output of a few petawatts for only 3-5 years. That's an astounding amount of power don't get me wrong, but it won't be enough for truly large spacecraft to reach significant fractions of c. On top of that it only lasts a few years before you need to make a new one, and it bleeds less energy than you'd have to put into making it.
So could you create an indefinitely sustainable black hole engine by feeding matter into the accretion disk and harnessing the resulting plasma, or must we settle for inefficiently sucking up the black hole's Hawking radiation?

A:

The main problem is mass. Black holes are massive. The black hole engine will be more massive than the spacecraft itself. Also, while BHs are powerful the massive they become the less useful power can be extracted.

Since the holes mass millions of tonnes, any associated starship should likewise mass similar amounts, so the acceleration can be ~halved. The very smallest black holes might prove difficult to feed at the indicated rates, since they’re smaller than protons, so Crane & Westmoreland suggested using the black hole as a “battery” – a finite store of energy – and letting it push self and payload until just before its final explosive last few seconds. One problem is that the hole becomes very energetic indeed as it loses mass, so just when the appropriate time to EJECT is an interesting question. For every 10-fold decrease in mass, the self-acceleration increases 1000-fold, so a crewed starship would need either acceleration mitigation or would need to eject once the black-hole was under one million tonnes.

A useful paper on BH powered spaceships is this on authored by [Crane and Westmoreland][1].
The interstellar travel and space buff Adam Cowl in his review of black hole starships came to the following conclusion.

In conclusion the concept needs considerable work before it can be considered an interstellar drive option. The radiation intensities that need to be handled boggle the mind. However coupling our particle theories to black holes is not without problems – quantum gravity may well alter the intensity once the hole is small enough and we have no clear idea of the fate of the multitudinous particles produced. Does a super dense ball of quagma result, “stuck” to the ball by gluons dragged out of the vacuum of space? The related idea, of quark matter, might present the option of embedding a Kugelblitz inside a quark nugget. A more developed understanding of the quantum chromodynamic (QCD) vacuum and quantum gravity needs developing.
For now, like the original Photon Rocket, this idea goes back on the
  shelf, until our physics catches up.

Basically BH powered starships sound like a nifty idea, but on closer examination they're more like a luxury vehicle that cost an arm and an leg to run, and spend most of their time in repair shop. While ordinary vehicles have much, much better performance characteristics and you can get some useful mileage out of them. Like fusion rockets, for example.


Q:

Date format in an Html.DropDownListFor

New to MVC, bear with me.
I'm trying to populate an Html.DropDownListFor control with a list of dates.  I need the text to be just MM/DD/YYYY and the data to be DateTime.  I can't figure out how to format the text to drop the date.
Here's the code from the view:
@Html.DropDownListFor(m => m.RunDate, Model.ReportRunDates, "--Select Report Date--", new { @class = "dropdown" })

From the viewModel:
[Display(Name = "Date")]
public IEnumerable<SelectListItem> ReportRunDates { get; set; }

[DisplayFormat(DataFormatString = "{0:d}")]
public string RunDate { get; set; }

from the controller:
[HttpGet]
public ActionResult StatusReport()
    {
        var vm = new ViewModels.ReportHistoryViewModel
        {
            ReportRunDates = GetReportRunDates(),
        };
        return View("StatusReportSearch", vm);
    }

private SelectList GetReportRunDates()
{
    var ReportRunDates = new List<ReportHistory>();

    ReportRunDates = RenewalUnderwritingLayer.GetReportRunDates();

    return new SelectList(ReportRunDates, "RunDate", "RunDate");
}

Code from the model:
public class ReportHistory
{
    [Key]
    public int Id { get; set; }
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid ReportHistoryGuid { get; set; }
    public DateTime ActivityDate { get; set; }
    public DateTime RunDate { get; set; }
}

Code that calls out to DAL:
    public static List<ReportHistory> GetReportRunDates()
    {
        using (var uow = new UnitOfWorkSQL())
        {
            return uow.Repository<ReportHistory>()
                .Query()
                .Get()
                .Distinct()
                .ToList();
        }
    }

I've got the control displaying data, which felt like a huge win in and of itself, but I cannot figure out how to drop the timestamp in the text display of the drop down.
Thanks in advance!

A:

You can format the date when generating the SelectListItem. Change your GetReportRunDates() method to
private IEnumerable<SelectListItem> GetReportRunDates()
{
  return RenewalUnderwritingLayer.GetReportRunDates().Select(r => new SelectListItem
  {
    Text = string.Format("{0:MM/dd/yyyy}", r.RunDate),
    Value = r.RunDate
  };
}

Note if you also want to post pack just the date component (with the time equal to 00:00:00), then you can also format the Value property in the same way.


Q:

JavaScript Animation: Handling Complex Animations That Use Callbacks & Loop

I'm using Snap.svg to animate 13 SVGs. All the SVGs start from one point and animate through several other animations (through callbacks). An simplified example of my animation is described, in code, below:
var reset = function(person) {
    person.attr({transform: 't0,0', opacity: 0});
    animatePerson(person);
};

var animatePerson = function(person) {
    person.animate({opacity: 1}, 300, null,function() {
        person.animate({transform: 't100,20'}, 1000, null, function() {
            person.animate({opacity: 0}, 300, null, function() {
                reset(person);
            });
        });
    });
};

var people = [Snap('#Person_1'), Snap('#Person_2'), Snap('#Person_3'), Snap('#Person_4'), Snap('#Person_5')];

My first attempt was to map over the array and set a timeout for the first animation like so:
people.map(function(person, index) {
    setTimeout(function() {
        animatePerson(person);
    }, (300*index));
});

However this did not work as the SVGs would start to overlap/overtake each other when they looped. Then I tried to set the timeout equal to the length of time it took for one complete "lap" of the animation and divide that by the total amount of SVGs like so:
people.map(function(person, index) {
    setTimeout(function() {
        animatePerson(person);
    }, (1600/people.length));
});

Is there a way in Snap.svg or JavaScript to have the animation loop using callbacks and/or timeouts, or an I way off here?
Here is an image of the full animation I am referring to:

A:

One way I have done this, is to write a small function that takes in an element and an array of preset animations, and go through them in turn via the callback, which looks like this...
Edit: Modified slightly to be able to include a different element per animation, and example2 link below, includes the option to include a function to call each time as well.
function nextFrame ( frameArray,  whichFrame ) {
    if( whichFrame >= frameArray.length ) { return }
    frameArray[ whichFrame ].el.animate(
          frameArray[ whichFrame ].animation,
          frameArray[ whichFrame ].dur,
          frameArray[ whichFrame ].easing,
          nextFrame.bind(null,  frameArray, whichFrame + 1 )
    );
}

Then you could pass it an array of anims, like this...
var myFrames = [
    {   el: g,  animation: { transform: 'r360,150,150' }, dur: 1000, easing: mina.bounce },
    {   el: r,  animation: { transform: 't100,-100s2,3' }, dur: 1000, easing: mina.bounce },
    {   el: r,  animation: { transform: 't100,100' }, dur: 1000, easing: mina.bounce },
    {   el: g,  animation: { transform: 's2,1' }, dur: 1000, easing: mina.bounce },
    {   el: r,  animation: { transform: 's1,2' }, dur: 1000, easing: mina.bounce },
    {   el: c,  animation: { transform: 's1,1' }, dur: 1000, easing: mina.bounce }];

Then you can call it with
nextFrame( el, myFrames, 0 );

example (click run on there)
example 2 (this allows you to include a func to call as well as part of it)