text:
Q: Unable to Update XAML TextBlock Text Binding I have a TextBlock in XAML that's bound to a property called EditsWarning:
<TextBlock DockPanel.Dock="Top" Text="{Binding EditsWarning, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Style="{DynamicResource Esri_TextBlockRegular}" HorizontalAlignment="Left" FontSize="14" FontWeight="DemiBold" VerticalAlignment="Center" Margin="10,0,10,5" TextWrapping="WrapWithOverflow"/>

The Definition for the EditsWarning Property is here:
public string EditsWarning
{
    get { return editsWarningMessage; }

    set
    {
        SetProperty(ref editsWarningMessage, value, () => this.EditsWarning);
    }
}

The EditsWarning Property is set to an instance of a class like this:
        editsWarning = new OutstandingEditsTextBlock();
        editsWarningMessage = editsWarning.EditsWarningMessage.ToString();

And the OutstandingEditsTextBlock class is here, and implements INotifyPropertyChanged
internal class OutstandingEditsTextBlock : INotifyPropertyChanged
{
    private string editsWarning;

    public OutstandingEditsTextBlock()
    {
        if (Project.Current.HasEdits)
        {
            this.editsWarning = "This session/version has outstanding edits.";
        }
        else
        {
            this.editsWarning = string.Empty;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public string EditsWarningMessage
    {
        get { return this.editsWarning; }

        set
        {
            this.editsWarning = value;
            this.OnPropertyChanged("EditsWarningMessage");
        }
    }

    public void OnPropertyChanged(string propertyName)
    {
        this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

I noticed that I can get it to display either value, however, I can never get it to update in the same debugging session. In fact, it looks like the setter for the public property is never hit.
Can someone please help me figure out what I'm doing wrong?
Thank you.


text:
Q: How to get classes incrementally compiled by SBT? The result of compile task in sbt is of type Analysis.
I want to find all java.lang.Classes that are compiled in last compilation.
Is that possible at all?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Comparing with EVERY distinct value listed in another table in MySql I have the following two tables
Table: Customer
Cust_ID    FName
-------    -----
1          X
2          Y
3          Z

Table: Account
Acct_Number    Cust_ID    Acct_Type
-----------    -------    ---------
1001           1          savings
1002           1          capital
1003           2          savings
1004           2          capital
1005           2          vip
1006           3          capital
1007           3          vip

There are three different types of account in Account table, (savings, capital and vip), I want to find the customer who have an account of every type which is listed in Account relation(without using any aggregate operator).That is, in this case, Y will qualify, as he is the only one who has all types of account.
I got a suggestion to try the following, which is not working:
SELECT c.FName, c.Cust_ID FROM Customer AS c
JOIN Account AS a1 ON c.Cust_ID = a1.Cust_ID
JOIN Account AS a2 ON c.Cust_ID = a2.Cust_ID
WHERE a1.Acct_Type <> a2.Acct_Type;

The above query is giving the customer who has account in two distinct type, not all. Helps are highly appreciated.

A: here's a query using not exists
select c.* from customer c
where not exists (
    select acct_type from account a2
    where acct_type not in (
        select distinct acct_type
        from account a3 where a3.Cust_ID = c.Cust_ID
    )
)

A: What you want is relational division:
forall x:p(x)

but this is not possible to express in sql so you have to rewrite it to:
not exists x : not p(x)

in other words, for which customers does it not exists an accounttype such that the account does not have it. Something like:
SELECT c.FName, c.Cust_ID
FROM Customer AS c
WHERE NOT EXISTS (
    select distinct Acct_Type
    from Account t
    where not exists (
        select 1 from Account as a
        where a.cust_id = c.cust_id
          and a.Acct_Type = t. Acct_Type
    )
);

Edit: did not notice that aggregates was disallowed

A: EDIT: If the Acct_Type values are not previously known, the following query can be used to get the desired results. Obviously, it is much more tedious than using aggregation operations.
SELECT c.*
FROM Customer AS c
INNER JOIN
(
    SELECT DISTINCT
        all_combinations.Cust_ID
    FROM Account Acct
    RIGHT JOIN
    (
        SELECT
            c.Cust_ID,
            a.Acct_Type
        FROM Customer AS c
        CROSS JOIN
        (SELECT DISTINCT Acct_Type FROM Account) AS a
    ) all_combinations
    ON Acct.Cust_ID = all_combinations.Cust_ID AND Acct.Acct_Type = all_combinations.Acct_Type
    WHERE Acct.Cust_ID IS NOT NULL
) all_acct_types
ON c.Cust_ID = all_acct_types.Cust_ID;


text:
Q: Contour plot equivalent to Wolfram Alpha's I'm trying to create a contour plot for a very specific function. The contour plot I've obtained through ggplot2 is quite similar to Wolfram Alpha's plot, although I'm not getting the same "grid-like" (white stripes) behavior as in the latter source.
How could I get similar white stripes like those if I'm not sure what those values are? Should I increase the amount of points?

library(tidyverse)

v <- function(r, q){
  value <- pmax(0, 3 * q - 1 + r - 3*r*q)^2 +
    pmax(0, r - 3 * r * q)^2 +
    pmax(0, -2 + 2*r + 2*q - 2*r*q)^2+
    pmax(0, 2*q - 3*r*q)^2
  return(value)
}

r <- q <- seq(0, 1, 0.001)
vertices <- expand_grid(r, q)

vertices %>% mutate(v = v(r, q)) %>%
  ggplot(aes(x = r, y = q, z = v)) +
  geom_contour_filled()


text:
Q: What does $ \prod_{i = 2}^{ n-1} \frac{1}{i}$ converge to? What does $ \prod_{i = 2}^{ n-1} \frac{1}{i}$ converge to?
It boils down to $\frac{1}{2} * \frac{1}{3} * \frac{1}{4} * ... * \frac{1}{n-1}$
But is there a direct formula that gives me the same answer?

A: By the squeeze theorem
$$0\le \prod_{i=2}^{n-1}\frac1i=\frac1{(n-1)!}\le \frac1{n-1}\xrightarrow{n\to\infty}0$$
we get easily the result.


text:
Q: remove redundancy in a file based on two fields, using awk I'm trying to remove duplicate lines in a very large file (~100,000 records) according to the values of the first two columns without taking into account their order, and then print those fields + the other columns.
So, from this input:
A B XX XX
A C XX XX
B A XX XX
B D XX XX
B E XX XX
C A XX XX

I'd like to have:
A B XX XX
A C XX XX
B D XX XX
B E XX XX

(That is, I want to remove 'B A' and 'C A' because they already appear in the opposite order; I don't care about what's in the next columns but I want to print it too)
I've the impression that this should be easy to do with awk + arrays, but I can't come with a solution.
So far, I'm tinkering with this:
awk '
NR == FNR {
h[$1] = $2
next
}
$1 in h {
print h[$1],$2}' input.txt

I'm storing the second column in an array indexed by the first (h), and then check if there are occurrences of the first field in the stored array. Then, print the line. But something's wrong and I have no output.
I'm sorry because my code is not helpful at all but I'm kind of stuck with this.
Do you have any ideas?
Thanks a lot!

A: Just keep track of the things that appear on the two formats:
$ awk '!seen[$1,$2]++ && !seen[$2,$1]++' file
A B XX XX
A C XX XX
B D XX XX
B E XX XX

Which is equivalent to awk '!(seen[$1,$2]++ || seen[$2,$1]++)' file.
Note it is also equivalent to not having ++ the second expression (see comments):
awk '!seen[$1,$2]++ && !seen[$2,$1]' file

Explanation
The typical approach to print unique lines is:
awk '!seen[$0]++' file

This creates an array seen[] whose indexes are the lines that have appeared so far. So if it is new, seen[$0] is 0 and gets incremented to 1. But previously it is printed because the expression ! var ++ evaluates ! var first (and in awk, True triggers the action of printing the current line). When the line has been seen already, seen[$0] has a positive value, so !seen[$0] is false and doesn't trigger the printing action.
In your case you want to keep track of what appeared, no matter the order, so what I am doing is to store the indexes in both possible positions.

A: use as below
$awk '{if( $1$2 in a == 0 && $2$1 in a == 0 ) a[$1$2]=$0; } END{ for(i in a)print a[i]; }' input.txt

Explanation:
command is storing the record in array (a) with array key as combination of first and second field (i.e $1$2 and $2$1) is not already present in array. Once complete file is read then print the array (a).
# ($1$2 in a) => checks if there is any key with $1$2 in array a
# if it's not present then it return 0
# and if both combination $1$2 and $2$1 are not present then store the record in array a
if( $1$2 in a == 0 && $2$1 in a == 0 ) a[$1$2]=$0;

# below print the array a (which stores complete unique record) at the end
END{ for(i in a) print a[i]; }'


text:
Q: android.support.v7.appCompactActivity is not supported Not supported library
,
I had downloaded all the sdk tools in android studio ....but android.support.v7.appcompactactivity library is not set in dependencies.if i try to set its generate error.and i had already set theme

A: Avoid using + with the version. Use the exact version name then download and sync.

A: try downgrading your
 buildToolsVersion "24.0.0"

to
buildToolsVersion "23.0.0"


text:
Q: 'No such file or directory' error - tried a bunch of different ways (Python) I have a set of CSV's inside a folder and I need to perform the same thing on each of the CSV, so I have written a code-snip that looks as follows:
import pandas as pd

PROJECT = r'~/Dropbox/Work/1. Data/'
DATA = '4. Data from AWS/2. Domains/'

for filename in os.listdir(os.path.join(PROJECT, DATA)):
    if filename.endswith(".csv"):
        print(filename)
        continue
    else:
        continue

and I get the error - No such file or directory: ~/Dropbox/Work/1. Data/4. Data from AWS/2. Domains/
However, when I try this, file1 = pd.read_csv(os.path.join(PROJECT, DATA, "youtube_links.csv")), the file opens without a problem. I have more than 3000 files, so loop is the easiest/safest way to calculate the things I want to calculate. I have included filename = os.fsdecode(filename) inside the loop and before the if statement, same error.
Strangely enough, this code was working perfectly a month ago. I am not sure how to solve this. Any help is appreciated.


text:
Q: Boolean operations for 3D objects I want to get a 3D object by Boolean operation, but I cannot find the information that I need to do this. How do I get something like the animation below?

This is my code:
(*Corpo Principal*)
orig = {0, 0, 0};
diam1 = 50;
r1 = diam1/2;
comp = 200;

(*Furo*)
diam2 = 15;
r2 = diam2/2;

(*Rasgo*)
altRasgo = 30;
largRasgo = 15;

Graphics3D[{Cylinder[{orig, {comp, 0, 0}}, r1],Cylinder[{{altRasgo/2, 0, -r1}, {altRasgo/2, 0, r1}}, r2],Cuboid[{0, -r1, -7.5}, {30, r1, 7.5}]}]

A: With the new in version 12.1 OpenCascadeLink you get very crisp corners:
Needs["OpenCascadeLink`"]
Needs["NDSolve`FEM`"]

(*Corpo Principal*)
orig = {0, 0, 0};
diam1 = 50;
r1 = diam1/2;
comp = 200;

(*Furo*)
diam2 = 15;
r2 = diam2/2;

(*Rasgo*)
altRasgo = 30;
largRasgo = 15;
reg = {Cylinder[{orig, {comp, 0, 0}}, r1],
  Cylinder[{{altRasgo/2, 0, -r1}, {altRasgo/2, 0, r1}}, r2],
  Cuboid[{0, -r1, -7.5}, {30, r1, 7.5}]}; rr =
 RegionDifference[RegionDifference[reg[[1]], reg[[2]]], reg[[3]]];
ocr = OpenCascadeShapeBooleanRegion[rr];
bmesh = OpenCascadeShapeSurfaceMeshToBoundaryMesh[ocr,
   "ShapeSurfaceMeshOptions" -> {"LinearDeflection" -> 0.5}];

groups = bmesh["BoundaryElementMarkerUnion"];
temp = Most[Range[0, 1, 1/(Length[groups])]];
colors = ColorData["BrightBands"][#] & /@ temp;
bmesh["Wireframe"["MeshElementStyle" -> FaceForm /@ colors]]

A: Let's split the components:
reg = {Cylinder[{orig, {comp, 0, 0}}, r1],
Cylinder[{{altRasgo/2, 0, -r1}, {altRasgo/2, 0, r1}}, r2],
Cuboid[{0, -r1, -7.5}, {30, r1, 7.5}]};

and use RegionDifference twice:
rr = RegionDifference[RegionDifference[reg[[1]], reg[[2]]], reg[[3]]];

Then you can
RegionPlot3D[rr, PlotPoints -> 100]

A: Directly with regions:
comp = 200;
altRasgo = 30;
r1 = 25;
r2 = 7.5;

region1 = (comp > x > 0 && y^2 + z^2 < r1^2);
region2 = (((x - altRasgo/2)^2 + y^2) < r2^2 && r1 > z > -r1);
region3 = (0 < x < 30 && -r1 < y < r1 && -7.5 < z < 7.5);
RegionPlot3D[
 region1 && ! region2 && ! region3, {x, 0, comp}, {y, -comp/2,
  comp/2}, {z, -comp/2, comp/2}, Mesh -> None, PlotPoints -> 50,
 PlotStyle -> Darker[Gray]]

Generation higher quality model:
r = DiscretizeRegion[
  ImplicitRegion[
   region, {x, y, z}], {{0, comp}, {-comp/2, comp/2}, {-comp/2,
    comp/2}}, Method -> "RegionPlot3D", MaxCellMeasure -> 10];
rr = GraphicsComplex[MeshCoordinates@#, MeshCells[#, 2]] &@r;
Graphics3D[{EdgeForm[], Darker[Gray], rr}, Lighting -> "Neutral",
 Boxed -> False]


text:
Q: Boruvka MST Algorithm Help me please with Boruvka algorithm for creating a minnimum-spanning tree. I wrote code of an algorithm looking on example given by Sedgwick but apparently had done a bunch of nonsense, because the algorithm never goes out of the loop. Tell me please where I have done mistakes and how to fix them, I'll be very grateful. Code below.
PS. sorry for my english:)
public class Boruvka
{
    private Edge[] mst;
    /**
     * Edges not yet discarded and not yet in the MST
     */
    private Edge[] wannabes;
    /**
     * Each component's nearest neighbor with find component numbers as indices
     */
    private Edge[] neighbors;
    /**
     * Graph representation on which we are searching for MST
     */
    private Graph g;
    /**
     *
     */
    private UnionFind uf;
    // constructors and methods
    /**
     * constructor
     * @param G Graph
     */
    public Boruvka(Graph G) {
        this.g = G;
    }
    /**
     * Boruvka's algorithm
     *
     *
     * @return minimal spanning tree - edges that form it
     */

    public Edge[] BoruvkaMSTalg()
    {
        Edge hlpEdge = new Edge(g.getMaxWeight(), 0, 0);
        this.uf = new UnionFind(g.getCountVerteces());
        this.wannabes = new Edge[this.g.getCountEdges()];

         /**
         * Get all edges from the graph G to the array edges
         */
        for (int i=0; i < g.getCountEdges(); i++)
            this.wannabes[i] = g.getEdgeAt(i);

        this.neighbors = new Edge[this.g.getCountVerteces()];
        this.mst = new Edge[this.g.getCountVerteces()+1];

        /**
         * index, used to store those edges being saved for the next phase
         */
        int nxtPhase;
        int k=1;

        for (int i=this.g.getCountEdges(); i!=0; i=nxtPhase)
        {
            int l, m, n;

            for (int o=0; o<this.g.getCountVerteces(); o++)
                this.neighbors[o] = hlpEdge;

            for (n=0, nxtPhase=0; n<i; n++) {
                Edge e = this.wannabes[n];
                l = this.uf.find(e.getSVIndex()-1);
                m = this.uf.find(e.getDVIndex()-1);

                if ( l==m )
                    continue;
                if ( e.getWeight() < this.neighbors[l].getWeight() )
                    this.neighbors[l] = e;
                if ( e.getWeight() < this.neighbors[m].getWeight() )
                    this.neighbors[m] = e;

                this.wannabes[nxtPhase++] = e;
            }

            for (n=0; n<this.g.getCountVerteces(); n++)
                if ( this.neighbors[n] != hlpEdge ) {
                    l = this.neighbors[n].getSVIndex();
                    m = this.neighbors[n].getDVIndex();

                    if ( !this.uf.find(l,m) ) {
                        this.uf.unite(l,m);
                        this.mst[k++] = this.neighbors[n];
                    }
                }
        }
        System.out.println("MST by Boruvka successful");
        return this.mst;
    }
}

I wrote this code looking at code given by Sedgwick in his "Algorithms in java. Part 5 : Graph Algorithm". And here is his code:
class GraphMST
{ private UF uf;
  private Edge[] a, b, mst;
  GraphMST(Graph G)
  { Edge z = new Edge(0, 0, maxWT);
    uf = new UF(G.V());
    a = GraphUtilities.edges(G);
    b = new Edge[G.V()]; mst = new Edge[G.V()+1];
    int N, k = 1;
    for (int E = G.E(); E != 0; E = N)
      { int h, i, j;
        for (int t = 0; t < G.V(); t++) b[t] = z;
        for (h = 0, N = 0; h < E; h++)
           { Edge e = a[h];
             i = uf.find(e.v()); j = uf.find(e.w());
             if (i == j) continue;
             if (e.wt() < b[i].wt()) b[i] = e;
             if (e.wt() < b[j].wt()) b[j] = e;
             a[N++] = e;
           }
        for (h = 0; h < G.V(); h++)
         if (b[h] != z)
          if (!uf.find(i = b[h].v(), j = b[h].w()))
            { uf.unite(i, j); mst[k++] = b[h]; }
      }
  }
}

Help me please to find differences between it's and mine and to fix them.
PS. i'm sorry for my english.

A: Here's a start.
Consider the for loop with this control statement:
for (int i=this.g.getCountEdges(); i!=0; i=nxtPhase)

The only way out of this loop is for i to be 0. The only place that i gets changed is by the loop advancing statement
i = nxtPhase

The only place that nxtPhase gets changed is here
this.wannabes[nxtPhase++] = e;

So as written, the only way out of the loop is for nxtPhase to go through all possible int values (I don't know the default overflow behaviour of Java so don't know what will actually happen when it gets to 2^32-1). This is probably not what you intend.


text:
Q: HBase Zookeeper Close Connection I'm trying to make a simple Web Service that runs on Apache Tomcat and has only one operation thate makes a HBase table scan.
Here is how i get the config:
Configuration config = HBaseConfiguration.create();
config.set("hbase.zookeeper.quorum", "hdp-node");

Htable table = new HTable(config, "myTable");

... scanner ...

scanner.close()
table.close()

The problem is that a connection to Zookeeper stays open and when i reach to a certain number of connedtions , Zookeeper begins to discard.
How can I close my Zookeeper connection after i make the scan?
Thanks

A: Connections to HBase and ZooKeeper are managed for you by the static HConnectionManager object.  This object is a map of Configuration (really HBaseConfiguration) objects to HConnection objects.
The HConnectionManager allows you to clean up connections for a configuration instance by calling its deleteConnection method.
So, if you want to force close your connections, you can just add the following line to the bottom of your code segment:
//free resources and close connections
HConnectionManager.deleteConnection(config,true);

However...
The HBase API is designed to multiplex client transactions over a single HConnection, and as long as multiple instances of HTable share the same Configuration object, they will use the same HConnection.  This saves all of the connection setup and tear down overhead for repeated transactions.
What does this mean?
It means that if possible, you really want to limit the number of instances of HBaseConfiguration per process, even if they are shared among multiple threads.  However, keep in mind that instances of HBaseConfiguration are not thread safe, so they shouldn't be modified by multiple threads.

A: I had a similar problem. The way I solved it was to make the Configuration object static. By that way there should only be one connection (per jvm).

A: What version of ZooKeeper are you running? It could well be that you are hitting issue 846.
Try upgrading ZooKeeper to 3.3.2 or later.


text:
Q: Magento 2.1.9 override catalog rule form I need to make some changes in catalog_rule_form.xml based on Magento_CatalogRule/view/adminhtml/ui_component/catalog_rule_form.xml
I tried to override this file in custom module and place new file in view/adminhtml/ui_component/catalog_rule_form.xml
Module has sequence declaration in module.xml like this:
    <sequence>
        <module name="Magento_CatalogRule"/>
    </sequence>

does not work.
Also i tried to place it in app/design/adminhtml/Vendor/Theme/Magento_CatalogRule/ui_component/catalog_rule_form.xml
same result.
Does anyone could help me with this. How can i override this form?


text:
Q: Hibernate JPA check for a conflict when generating IDs I am using a postgresql database table which may have inserts with the ID set manually by the user, or need an ID generated using hibernate.
This may lead to the occurrence of generating an ID which has already been inserted into the database manually. Is there any way hibernate can check for collisions between the generated ID and existing IDs?

A: Hibernate cannot check that, because the sequence is allocated by the database. You could either:

*

*assign negative numbers for manually inserted IDs

*use UUID instead of sequences


text:
Q: Hilbert Matrix and Approximation Theory I was reading about the Hilbert matrix and Cauchy determinants:
\[  \det \left[ \frac{1}{i+j-1} \right]_{i,j} \]
By guessing where this determinant is $0$ or $\infty$ we can guess the right formula.  In Wikipedia, I found this problem:

"Assume that $I = [a, b]$ is a real interval. Is it then possible to find a non-zero
  polynomial $P$ with integral coefficients, such that the integral $\int_a^b P(x)^2\, dx$
  is smaller than any given bound $\varepsilon > 0$, taken arbitrarily small?"
To answer this question, Hilbert derives an exact formula for the determinant of the
  Hilbert matrices and investigates their asymptotics. He concludes that the answer to his
  question is positive if the length $b − a$ of the interval is smaller than $4$.

I'm asking for a reference / proof to this exercise.  I think you can expand $P$ in Legendre polynomials, or use the Gram determinant.
In general, why is this matrix related to approximation theory?

A: In the generically titled, Ein Beitrag zur Theorie des Legendre'schen Polynoms Hilbert says integral  $\int_a^b P(x)^2 dx $ defines quaratic form over the space of polynomials of degree $\leq n$.
Over $[0,1]$ the determinant in the basis $\{ 1, x, x^2, \dots, x^n \}$ is:
\[  D_{[a,b]} = \int_{[a,b]^n} x_1^{n-1}x_2^{n-2}\dots x_{n-2}^2 x_{n-1} \prod_{i < j}(x_i - x_j)^2 d\mathbf{x} = \left( \frac{b-a}{2} \right)^{n^2} D \]
Usually Legendre polynomials are defined over [0,1], but you can do a change of variables.  In that basis the quadratic form is diagonalized:
\[ \int_a^b P(x)^2 \, dx = \frac{2}{2n-1}b_1^2 + \frac{2}{2n-3} b_2^2 + \dots ,  \]
where we expand in Legendre polynomials $P(x) = b_1 p_1(x) + b_2 p_2(x) + \dots . $ You are finding the determinant of this change of variables:
\[ \left| \begin{array}{cccc} 1 & \frac{1}{2} & \dots & \frac{1}{n} \\\\
\frac{1}{2} & \frac{1}{3} & \dots & \frac{1}{n+1} \\\\
\vdots & & & \vdots \\\\
\frac{1}{n} & \frac{1}{n+1} & \dots  & \frac{1}{2n+1}
\end{array}\right| = \frac{\left[1^{n-1}2^{n-2}\dots (n-2)^2(n-1)\right]^4}{1^{2n-1}2^{2n-2}\dots (2n-2)^2(2n-1)} .\]
The discriminant of this quadratic form to be proportional to $ \left(\frac{b-a}{4}\right)^n$ which tends to 0 for $b-a < 4$.
Polynomials with integer coefficients form an lattice in the space of polynomials.  For this discriminant to tend to 0, there must be polynomials with arbitrarily small norm.

I still find this result counterintuitive... We can find explicit examples, when $|a|,|b|<1$
\[  \int_{a}^b x^{2n} \, dx = \frac{b^{2n+1}-a^{2n+1}}{2n+1} \]
but not sure about $a=0,b=2$, for example.


text:
Q: dynamically specify string interpolation for variable in place of column or property value entity framework c# Here dynamic_Column variable is not showing a value same as static_Column
Please help me solve the below problem if you can help?
var customerList = _context.customers.ToList();

for(var i = 0; i <= 5; i++)
{
    var colName = customerList[0].name;//value =id

    var static_Column = customerList[i].id;
    var dynamic_Column = $"{customerList[i]}.{colName}";

    Console.WriteLine(static_Column);
    Console.WriteLine(dynamic_Column);
}

A: I followed [dynamic-linq.net], It helped me to fix my problem.


text:
Q: Create and populate a column with value chosen from a specific date per group I have a dataframe with multiple groups (location, animal, color) for instance.
I want to create a new column FY_19 such that for all Year 2020 rows, I can see the corresonding group's full year 2019 value (which is readily available in the 2019_YTD column matching Date = 2019-12-01)
Current DF

Location Animal Color Date       2019_YTD
Asia     Dog    Blue  2019-06-01    20
Asia     Dog    Red   2019-06-01    30
Africa    Cat   Blue  2019-06-01    20
Africa    Dog    Red   2019-06-01    30
Asia     Dog    Blue  2019-12-01    30
Asia     Dog    Red   2019-12-01    50
Africa    Cat   Blue  2019-12-01    60
Africa    Dog    Red   2019-12-01    55
Asia     Dog    Blue  2020-06-01
Asia     Dog    Red   2020-06-01
Africa    Cat   Blue  2020-06-01
Africa    Dog    Red   2020-06-01
Asia     Dog    Blue  2020-12-01
Asia     Dog    Red   2020-12-01
Africa    Cat   Blue  2020-12-01
Africa    Dog    Red   2020-12-01

Desired DF
Location Animal Color Date       2019_YTD    FY19
Asia     Dog    Blue  2019-06-01    20
Asia     Dog    Red   2019-06-01    30
Africa    Cat   Blue  2019-06-01    20
Africa    Dog    Red   2019-06-01    30
Asia     Dog    Blue  2019-12-01    30
Asia     Dog    Red   2019-12-01    50
Africa    Cat   Blue  2019-12-01    60
Africa    Dog    Red   2019-12-01    55
Asia     Dog    Blue  2020-06-01            30
Asia     Dog    Red   2020-06-01            50
Africa    Cat   Blue  2020-06-01            60
Africa    Dog    Red   2020-06-01           55
Asia     Dog    Blue  2020-12-01            30
Asia     Dog    Red   2020-12-01            50
Africa    Cat   Blue  2020-12-01            60
Africa    Dog    Red   2020-12-01           55

A: Use DataFrame.merge only filtered rows and then replace values to missing if no 2020 year:
df = pd.DataFrame({'Location': ['Asia', 'Asia', 'Africa', 'Africa', 'Asia', 'Asia', 'Africa', 'Africa', 'Asia', 'Asia', 'Africa', 'Africa', 'Asia', 'Asia', 'Africa', 'Africa'], 'Animal': ['Dog', 'Dog', 'Cat', 'Dog', 'Dog', 'Dog', 'Cat', 'Dog', 'Dog', 'Dog', 'Cat', 'Dog', 'Dog', 'Dog', 'Cat', 'Dog'], 'Color': ['Blue', 'Red', 'Blue', 'Red', 'Blue', 'Red', 'Blue', 'Red', 'Blue', 'Red', 'Blue', 'Red', 'Blue', 'Red', 'Blue', 'Red'],
                   'Date': [pd.Timestamp('2019-06-01 00:00:00'), pd.Timestamp('2019-06-01 00:00:00'), pd.Timestamp('2019-06-01 00:00:00'), pd.Timestamp('2019-06-01 00:00:00'), pd.Timestamp('2019-12-01 00:00:00'), pd.Timestamp('2019-12-01 00:00:00'), pd.Timestamp('2019-12-01 00:00:00'), pd.Timestamp('2019-12-01 00:00:00'), pd.Timestamp('2020-06-01 00:00:00'), pd.Timestamp('2020-06-01 00:00:00'), pd.Timestamp('2020-06-01 00:00:00'), pd.Timestamp('2020-06-01 00:00:00'), pd.Timestamp('2020-12-01 00:00:00'), pd.Timestamp('2020-12-01 00:00:00'), pd.Timestamp('2020-12-01 00:00:00'), pd.Timestamp('2020-12-01 00:00:00')],
                   '2019_YTD': [20.0, 30.0, 20.0, 30.0, 30.0, 50.0, 60.0, 55.0, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]})

print (df)
   Location Animal Color       Date  2019_YTD
0      Asia    Dog  Blue 2019-06-01      20.0
1      Asia    Dog   Red 2019-06-01      30.0
2    Africa    Cat  Blue 2019-06-01      20.0
3    Africa    Dog   Red 2019-06-01      30.0
4      Asia    Dog  Blue 2019-12-01      30.0
5      Asia    Dog   Red 2019-12-01      50.0
6    Africa    Cat  Blue 2019-12-01      60.0
7    Africa    Dog   Red 2019-12-01      55.0
8      Asia    Dog  Blue 2020-06-01       NaN
9      Asia    Dog   Red 2020-06-01       NaN
10   Africa    Cat  Blue 2020-06-01       NaN
11   Africa    Dog   Red 2020-06-01       NaN
12     Asia    Dog  Blue 2020-12-01       NaN
13     Asia    Dog   Red 2020-12-01       NaN
14   Africa    Cat  Blue 2020-12-01       NaN
15   Africa    Dog   Red 2020-12-01       NaN

cols = ['Location','Animal','Color','2019_YTD']
df1 = df.loc[df['Date'] == '2019-12-01', cols].rename(columns={'2019_YTD':'FY19'})
print (df1)
  Location Animal Color  FY19
4     Asia    Dog  Blue  30.0
5     Asia    Dog   Red  50.0
6   Africa    Cat  Blue  60.0
7   Africa    Dog   Red  55.0

df = df.merge(df1, how='left')
print (df)
   Location Animal Color       Date  2019_YTD  FY19
0      Asia    Dog  Blue 2019-06-01      20.0  30.0
1      Asia    Dog   Red 2019-06-01      30.0  50.0
2    Africa    Cat  Blue 2019-06-01      20.0  60.0
3    Africa    Dog   Red 2019-06-01      30.0  55.0
4      Asia    Dog  Blue 2019-12-01      30.0  30.0
5      Asia    Dog   Red 2019-12-01      50.0  50.0
6    Africa    Cat  Blue 2019-12-01      60.0  60.0
7    Africa    Dog   Red 2019-12-01      55.0  55.0
8      Asia    Dog  Blue 2020-06-01       NaN  30.0
9      Asia    Dog   Red 2020-06-01       NaN  50.0
10   Africa    Cat  Blue 2020-06-01       NaN  60.0
11   Africa    Dog   Red 2020-06-01       NaN  55.0
12     Asia    Dog  Blue 2020-12-01       NaN  30.0
13     Asia    Dog   Red 2020-12-01       NaN  50.0
14   Africa    Cat  Blue 2020-12-01       NaN  60.0
15   Africa    Dog   Red 2020-12-01       NaN  55.0

print (df['Date'].dt.year == 2020)
0     False
1     False
2     False
3     False
4     False
5     False
6     False
7     False
8      True
9      True
10     True
11     True
12     True
13     True
14     True
15     True
Name: Date, dtype: bool

df['FY19'] = df['FY19'].where(df['Date'].dt.year == 2020)
print (df)
   Location Animal Color       Date  2019_YTD  FY19
0      Asia    Dog  Blue 2019-06-01      20.0   NaN
1      Asia    Dog   Red 2019-06-01      30.0   NaN
2    Africa    Cat  Blue 2019-06-01      20.0   NaN
3    Africa    Dog   Red 2019-06-01      30.0   NaN
4      Asia    Dog  Blue 2019-12-01      30.0   NaN
5      Asia    Dog   Red 2019-12-01      50.0   NaN
6    Africa    Cat  Blue 2019-12-01      60.0   NaN
7    Africa    Dog   Red 2019-12-01      55.0   NaN
8      Asia    Dog  Blue 2020-06-01       NaN  30.0
9      Asia    Dog   Red 2020-06-01       NaN  50.0
10   Africa    Cat  Blue 2020-06-01       NaN  60.0
11   Africa    Dog   Red 2020-06-01       NaN  55.0
12     Asia    Dog  Blue 2020-12-01       NaN  30.0
13     Asia    Dog   Red 2020-12-01       NaN  50.0
14   Africa    Cat  Blue 2020-12-01       NaN  60.0
15   Africa    Dog   Red 2020-12-01       NaN  55.0


text:
Q: C# UnitTest void static method I'm trying to make an unit test for a logger in an application.
For example I need to test the method Logger.info("some message"), but this method is static and return void.
Searching on Google I understand that I have to use Moq but am unable to implement that on the UnitTest class.
The Logger constructor does not have an argument and in x.Debug I have an error that says that I can't access
from instance reference.
Is there a way to implement UnitTest without editing the production code?
[TestClass()]
public class LoggerTests
{
    [TestMethod()]
    public void DebugTest()
    {
        var mock = new Mock<Logger>();
        mock.Setup(x => x.Debug(It.IsAny<string>());
        new Logger(mock.Object).AddLog("testing");
        mock.VerifyAll;
    }
}

Program.cs
private static void ConfigureLogger()
{
    Logger.AddLog(new NLogAppender());
    Logger.Level = TraceLevel.Verbose;
    Logger.Info("Configured Logger");
}

Logger.cs
public class Logger
{
    public static readonly List<IAppender> loggings = new List<IAppender>();

    public static void AddLog(IAppender appender)
    {
        loggings.Add(appender);
    }

    public static TraceLevel Level { get; set; }

    static Logger()
    {
        Level = TraceLevel.Verbose;
    }

    public static void Info(string message)
    {
        LogMessage(message);
    }
}

NlogAppender.cs
public class NLogAppender : IAppender
{
    public NLog.Logger logger;

    public NLogAppender()
    {
        logger = LogManager.GetLogger(nameof(NLogAppender));
    }

    public void AddLog(string str)
    {
    }
}

IAppender.cs
public interface IAppender
{
    void AddLog(string str);
}

A: You can't mock a static class, and you shouldn't mock the class/system under test.
Add a mock appender to the logger:
// Arrange
var logString = "test-info"

var appenderMock = new Mock<IAppender>();

appenderMock.Setup(a => a.AddLog(logString));

Logger.AddLog(appenderMock.Object);

// Act
Logger.Info(logString);

// Assert
// TODO: exactly once
appenderMock.VerifyAll();

Note this static class may persist data between tests causing unexpected results, consult your test framework for configuring this.
Apart from that, you usually don't want to roll your own logging infrastructure, there's lots of things you can do wrong and why reinvent the wheel? Plenty of ILogger(<T>) implementations around.


text:
Q: Common Lisp: Recursive "is-equal" function - results are incorrect I'm having trouble developing a recursive function that will see if two list's are equal to each other, including looking at the sub list's. So far I have:
(defun are-equal2 (X Y)
(cond
    ((null X) nil)
    ((and (listp (first X)) (listp (first Y)))
        (are-equal2 (first X) (first Y))
    )
    ((eq (first X) (first Y))
        T
    )
)
)

It seems to work sometimes. for example (are-equal2 '((A) B) '((A) B)) returns T and (are-equal2 '((A) B) '(A B)) returns nil. but (are-equal2 '(F (A G) B) '(F (T G) B)) returns T..... I think it might have to do with my last conditional. I'm not sure how to re-work it though.
Never mind lol. Did some tinkering waiting for a reply and got it. Did a bunch of nested if statements. Code:
(defun are-equal2 (X Y)
    (if (and (listp (first X)) (listp (first Y)))
        (are-equal2 (first X) (first Y))
        (if (and (eq (first X) (first Y)))
            (if (and (endp (rest X)) (endp (rest Y)))
                T
                (are-equal2 (rest X) (rest Y))
            )
            nil
        )
    )

)

A: I don't think you can get away with a tail-recursive version here.
I am afraid you will have to think of your arguments as trees, not sequences.
E.g.,
(defun are-equal (x y &key (test #'eql))
  (or (funcall test x y)
      (and (consp x)
           (consp y)
           (are-equal (car x) (car y))
           (are-equal (cdr x) (cdr y)))))

This compares leaves using eql by default (cf. Rules about Test Functions), as opposed to eq in your example:
(are-equal '((1) a) '((1) a))
==> T
(are-equal '((1) a) '((1) b))
==> NIL
(are-equal '((1) a) '((2) a))
==> NIL
(are-equal '(("1") a) '(("1") a))
==> NIL


text:
Q: How to inject factory in angular boostrap modal's controller? I want to create dialog box for confirmation on Submit button. So I am using angular ui bootstrap.
This is my main controller code:
FrontEnd.controller('PostViewController',function($scope,$stateParams,PostFactory, $modal){

    $scope.openConfirm = function(size) {

            var modalInstance = $modal.open({
                animation: true,
                templateUrl: 'ConfirmDialog.html',
                controller: 'ConfirmDialogController',
                size: size,
                resolve: {
                    form: function () {
                            return $scope.form;
                        },
                    //tried with this line as well, but could not resolve error
                    PostFactory: "PostFactory"
                }
            });

            modalInstance.result.then(function (response) {
                $scope.isSurveySubmitted = true;
                $scope.message = response.message;

                //$scope.selected = selectedItem;
              }, function () {
                console.log('Modal dismissed at: ');
            });
    };
});

This is my ConfirmDialogController:
FrontEnd.controller('ConfirmDialogController', function($scope, $http, $modalInstance, form, PostFactory){

    $scope.ok = function () {

        PostFactory.SubmitSurvey(form).success(function(response){
            $modalInstance.close(response);
        }).success(function(response){
            $modalInstance.close(response);
        });
    };

    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
});

Modal opens properly without error. When I click on cancel button it closes modal As I expected. But when I click on Ok, it calls $scope.ok() but throws error in console with message PostFactory is undefined.
So what to do? Thanks for help.

A: I think you can use the scope field in $modalInstance.open()
set the factory as a property on a new scope
var scope = $scope.$new();
scope.factory = PostFactory;
$modalInstance.open({
    // other stuff
    scope: scope
});

Then reference the $scope.factory in yoou modal's controller.
not sure if it will mess anything else up, worth a try though.


text:
Q: launchDaemon choose shared file location that doesn't require full disk access I've got an mach-o executable that runs from launchDaemon plist file, and is communicating with other processes using unix domain socket. The file that backs this socket created in /tmp.
However, this cause the executable to fail reading the file unless given full disk access.
I'd like to find a location for the socket file, which is shared to all processes and doesn't require full disk access. the executable reside in /Library/Application Support/myProj/bin/exec_file
is there such location ? Perhaps can i use the same location of the executable itself ?


text:
Q: Is it possible to hard-link local git submodule repositories? We currently have a fairly large git repository with submodules (about 10GB), and cloning it from the server takes quite some time. I want to keep a local copy in our project directory and use it as the origin for builds. The project directory is stored on an NFS-mounted drive.
Git makes hard links to the original repository when cloning with --local or just /path/to/repo, but it does not seem to make hard links for the submodule repos. I would have expected
git clone --local --recursive /path/to/origin mycopy

to create hard links for all repos. Can I tell git to use hard links for the submodules too?

A: I don't think this can be done with a buildin command, but you can modify the .gitmodules file before the git submodule init (or equivalent) command and restore the original later:
git clone --local /path/to/origin mycopy
sed -i '/path = /{h;s,.* = ,,;x};/url = /{s, = .*, = /path/to/origin,;G;s,\n,,}' mycopy/.gitmodules
git -C mycopy submodule update --init
git -C mycopy checkout -- .gitmodules


text:
Q: I got error to casting data from index to process "Object of class mysqli_result could not be converted to int in" i got error casting in calculation square distance
i have to make simple sql program but i got problem in casting data

if (isset($_POST['hitung'])) {
  $sql = "select * from tb_keterangan";
  $result = $conn->query($sql);
     while ($row = $result->fetch_assoc()) {
    $d_modal            =$conn->query("select modal from tb_keterangan");
    $d_lahan            =$conn->query("select lahan from tb_keterangan");
    $d_indukan          =$conn->query("select jumlah_indukan from tb_keterangan");
    $d_produksi         =$conn->query("select jumlah_produksi from tb_keterangan");
    $d_keterangan       =$conn->query("select keterangan from tb_keterangan");

    $modal        =$_POST['modal'];
    $lahan        =$_POST['lahan'];
    $indukan      =$_POST['j_indukan'];
    $produksi     =$_POST['produksi'];
    $ket          =$_POST['keterangan'];

    $h_modal      =($d_modal - (int)$row['modal']);
    $h_lahan      =((int)$d_lahan - (int)$lahan);
    $h_indukan    =((int)$d_indukan - (int)$indukan);
    $h_produksi   =((int)$d_produksi - (int)$produksi);
    // $h_ket        =($d_keterangan - $ket);

    //pangkat
    $p_modal      =pow($h_modal,2);
    $p_lahan      =pow($h_lahan,2);
    $p_indukan    =pow($h_indukan,2);
    $p_produksi   =pow($h_produksi,2);
    // $p_ket        =pow($h_ket,2);

    $square_distance = $p_modal+$p_lahan+$p_indukan+$p_produksi;
    ?>

but the result calculation is appear

A: '$d_modal            =$conn->query("select modal from tb_keterangan");
These are query variable which you are converting into (int) but you need to get the result from these variables as they are object returned by mysqli query.
Use mysqli_fetch functions and then convert it into int


text:
Q: Shouldn't 2147483648 + 2147483648 + 2147483648 be -2147483648? I'm using MSVC 2019, and I'm testing something.
Thanks to lots of people, now I get this prints 0 :
long long a = 2147483648 + 2147483648;
printf("%lld\n", a);

So this time, I thought like 'what if I add 2147483648 for 3 times?', and I did.
I thought that the result must be -2147483648, because 2147483648 + 2147483648 + 2147483648 is equal to 0 + 2147483648, and 0 and 2147483648 is int value, so it's gonna be -2147483648
In simple terms, I thought that the previous code is equal to this:
long long a = (int)2147483648;
printf("%lld\n", a);

But it didn't work. Here's the code what I wrote:
long long a = 2147483648 + 2147483648 + 2147483648;
printf("%lld\n", a);

The result is 2147483648, and I don't know why.
Now I'm getting dizzy LOL
What did I do wrong?
p.s. the file's name is tmp.c

A: In C, following C99 rules since long long did not come out until then:
2147483648 is not a 32-bit int.  It is a 64-bit integer as 2147483648 is not in the int32_t positive range.
-2147483648 is not a 32-bit int.  It is a 64-bit integer as 2147483648 is not in the int32_t positive range either, the - is applied after the constant type is formed.
The expected math output is the sum with 64-bit math.

int main(void) {
  long long a = 2147483648 + 2147483648;
  printf("%lld\n", a);
  a = 2147483648 + 2147483648 + 2147483648;
  printf("%lld\n", a);
  return 0;
}

Output
4294967296
6442450944

OP reports:

Well, the output for me is 0 and 2147483648 when I copied your code.

OP is perhaps using a C89 compiler with long long extensions.  visual-studio-2019 is not fully C99 compliant. Example Does Visual Studio 2017 fully support C99?.
In that case:
C89 uses different rules e.g.:
2147483648 is not a 32-bit int.  It is a 32-bit unsigned long
2147483648 + 2147483648 is unsigned overflow and well defined to sum to 0.
2147483648 + 2147483648 + 2147483648, as 32-bit unsigned long math is a 32-bit unsigned long 2147483648.
Assigning 32-bit unsigned long 2147483648 to a long long is the same value, different type.

Moral of the story: Consider starting computation with the desired end type.
With the below code, the type on the left does not influence the addition on the right.  This is the same problem as Why (not) write 1,000,000,000 as 1000*1000*1000?

long long a = 2147483648 + 2147483648 + 2147483648;

Alternatives:
long long a = (long long) 2147483648 + 2147483648 + 2147483648;

long long a = 0LL + 2147483648 + 2147483648 + 2147483648;

long long a = 2147483648;
a += 2147483648;
a += 2147483648;


text:
Q: Вывод результата MySQL-запроса с помощью PHP - как лучше? Есть к примеру таблица:
id  | col_1 | col_2
1   |   a   |   c
2   |   d   |   b
3   |   v   |   n
4   |   b   |   h
5   |   b   |   a
... и т.д.

Нужно сделать такой вывод:
<div> 1, 5 </div> <!-- все id где в col-1 OR в col-2 есть "a" -->
<div> 5, 12 </div> <!-- все id где в col-1 есть "а" AND в col-2 есть "b" OR в col-1 есть "b" AND в col-2 есть "a"  -->
<div> 2, 4, 5 </div> <!-- все id где в col-1 OR в col-2 есть "b" -->

Вот  так это делаю я:
$div1_q = mysqli_query("SELECT id FROM table WHERE col_1='a' OR col_2='a'");
$div2_q = mysqli_query("SELECT id FROM table WHERE col_1='a' AND col_2='b' OR col_1='b' AND col_2='a'");
$div3_q = mysqli_query("SELECT id FROM table WHERE col_1='b' OR col_2='b'");

$div1 ='';
$div2 ='';
$div3 ='';
while($div1_r = mysqli_fetch_assoc($div1_q)) {
    $div1 .= $div1_r['id'];
}
while($div2_r = mysqli_fetch_assoc($div2_q)) {
    $div2 .= $div2_r['id'];
}
while($div3_r = mysqli_fetch_assoc($div3_q)) {
    $div3 .= $div3_r['id'];
}

Кому не составит труда, подскажите пожалуйста, есть ли лучшее решение? Пример запроса и хоть немного php =)

A: Использовать union:
$query = mysqli_query($conn,
    "(SELECT id, 1 FROM test WHERE col_1='a' OR col_2='a')
        UNION ALL
     (SELECT id, 2 FROM test WHERE col_1='a' AND col_2='b' OR col_1='b' AND col_2='a')
        UNION ALL
     (SELECT id, 3 FROM test WHERE col_1='b' OR col_2='b')");

$div1 = '';
$div2 = '';
$div3 = '';

while($row = mysqli_fetch_assoc($query))
{
    if($row['1'] == 1)
    {
        $div1 .= $row['id'];
    }
    else if($row['1'] == 2)
    {
        $div2 .= $row['id'];
    }
    else if($row['1'] == 3)
    {
        $div3 .= $row['id'];
    }
}


text:
Q: ASP.NET HTML Encoded Data-Bind and br tag I'm trying to encode data that is to be displayed on a separate page (.aspx) after a user submits a form with their information and questions.  There are both text input and textarea fields that the user can fill out.
I'm using the <%#: %> expression to place this data on the page since it does the HTML encoding, but have run into an issue with the encoding also encoding the br tags as text instead of actual line breaks.
Is there a way to make it so that the br tags still cause a line break, but leave everything else encoded using this method?
Example of user input:
Hi

This is what should be responded with.

Here is an example of the code that places it on the page:

<%#: ((DiscussionThread.Discussion)Container.DataItem).Text %>

What it currently displays on the page:
Hi

This is what should be responded with.

Thanks in advanced!

A: Don't know, will it help you in your case or no, but I always use next way:
string forInput = yourTextBoxID.Text.ToString().Replace(Environment.NewLine, "%NL%");
string forOutput = forInput.Replace("%NL%", Environment.NewLine);

If in forOutput Environment.NewLine will not work, change it to

%NL% it is just a identificator, u may change to anything else.


text:
Q: Get names of all keys in the collection using Mongolite I've been trying to figure out how to create a list in R with all of the keys in a collection using Mongolite, but I can't seem to find any examples online. I've been  looking at the following Thread (Get names of all keys in the collection) but all of the answers seem to be concerning Python or command line scripting.
If I use the iterate function, db$iterate()$one(), on my database, I am able to return a single entry from the collection that has all of the keys, but it also includes all of the associated values from the database.
If I had to guess, the way to do it would be using the run() command, but I'm not sure where to start.
Thoughts?

A: I think I might have  found an answer to my own question. I think that one way to do it (albeit slightly janky) would be to return a find() query of the whole collection, but limit the number of rows return to 5-10, similar to the head() funciton in R, and load that into a temporary data.frame. Then once that is loaded, it is relatively easy to strip out the column headings using R's built in functions and save that as its own list for later use.


text:
Q: Segmentation fault using strcpy I have some troubles when using strcpy to copy an array of string inside a double pointer with allocated memory, but i can't understand why i get segmentation fault even if i have previously allocated memory.
Here is the code:
#include <stdio.h>
#include <string.h>

typedef struct Students {
    int q_exams;
    char **done_exams;

}Students;

int main() {

Students a;
int i;
char support[30];

printf("how many exams have you done ?\n");
scanf("%d",&(a.q_exams));
 a.done_exams=malloc(sizeof(char*)*a.q_exams);
if(a.done_exams==NULL)
  {
    printf("out of memory\n");
    return 0;
  }
for(i=0;i<a.q_exams;i++)
  {
    printf("Insert the name of the exam\n");
    scanf("%28s",support);
    a.done_exams[i]=malloc(strlen(support)+1);
    if(a.done_exams[i]==NULL)
    {
      printf("out of memory\n");
      return 0;
    }
    strcpy(a.done_exams[i][0],support);
    fflush(stdin);
  }

  return 0;
}

A: You need to pass an address of the initial character to strcpy, either like this
strcpy(&a.done_exams[i][0],support);
//     ^
//  Add an ampersand

or equivalently like this:
strcpy(a.done_exams[i] , support);
//                    ^
// Remove the second index

Currently, your code passes the value* of the initial character, rather than its address.
* The value is undefined at the time as well, but it is not the primary cause, because you should not be passing value at all.

A: This code is fixed
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct Students {
    int q_exams;
    char **done_exams;
} Students;

int main()
{
    Students a;
    int i;
    char support[49];

    printf("how many exams have you done ?\n");
    scanf("%d",&(a.q_exams));

    a.done_exams = malloc(sizeof(char*) * a.q_exams);
    if(a.done_exams==NULL)
    {
        printf("out of memory\n");
        return 0;
    }

    for(i = 0 ; i < a.q_exams ; i++)
    {
        printf("Insert the name of the exam\n");
        scanf("%48s",support);

        a.done_exams[i] = malloc(strlen(support)+1);
        if(a.done_exams[i] == NULL)
        {
            printf("out of memory\n");
            return 0;
        }
        strcpy(a.done_exams[i]/*[0]*/, support);
        /*     ^                 ^- this is wrong
         *     + pass the address to the array not the first element value
         *
         * if you had warnings turned on you would have seen this
         */
        fflush(stdin);
    }

    return 0;
}

notice that
scanf("%48s", support);

requires
char support[49];

which is also fixed in the code.

A: The
strcpy(a.done_exams[i][0],support);

should be
strcpy(a.done_exams[i],support);

or
strcpy(&a.done_exams[i][0],support);

My advice would be to always compile with compiler warnings turned on. My compiler (gcc) does a very good job of catching the problem and telling you exactly what needs to be done to fix it:
test.c:37:12: warning: incompatible integer to pointer conversion passing 'char' to
              parameter of type 'char *'; take the address with & [-Wint-conversion]
    strcpy(a.done_exams[i][0],support);
           ^~~~~~~~~~~~~~~~~~
           &

P.S. You are also missing some #includes:
#include <stdlib.h>
#include <string.h>

A: See the man page of strcpy().
The first argument should be of type char *.
As per your code, the argument [a.done_exams[i][0]] is of type char. You need to pass a char * [starting address of the destination] actually.
Change your code to
strcpy(a.done_exams[i],support);


text:
Q: How to call sqlite3_open (passing opaque pointers by reference) As an exercise, I'm trying to create a wrapper for sqlite3.  I've got the bridging header set up, and I can see the tool tips for the sqlite3 functions, but I can't figure out how to call sqlite3_open
sqlite3.h contains the following definitions of sqlite3 and sqlite3_open:
typedef struct sqlite3 sqlite3;

SQLITE_API int sqlite3_open(
  const char *filename,   /* Database filename (UTF-8) */
  sqlite3 **ppDb          /* OUT: SQLite db handle */
);

Which means that sqlite3_open takes as a trailing parameter a pointer to a pointer to an anonymous structure, which seems clear enough in the tooltip:
func sqlite3_open(filename: CString, ppDb: CMutablePointer<COpaquePointer>) -> CInt

Knowing that CMutablePointer means to pass in &T, the closest I've come is:
class Database {
    var handle:COpaquePointer

    init(file:String) {
        let error = sqlite3_open(file as CString, &handle)
    }

    deinit {
        sqlite3_close(handle)
    }
}

There's no error on the sqlite3_close line, so I think I'm at least close, but the sqlite3_open line yields:
Cannot convert the expression's type 'CInt' to type '$T9'

Any clues on how to do this?
Please, no answers that say to use FMDB or other Objective-C based interfaces.  As I said, this is at least partially an exercise in figuring out how to use C libraries from swift.

A: The problem is not with the handle parameter, but with the string conversion.  The following works…
class Database {
    var handle: COpaquePointer = nil

    init(file: NSString) {
        let error = sqlite3_open(file.cStringUsingEncoding(NSUTF8StringEncoding), &handle)
    }
}

I'm unsure as to why the 'as CString' doesn't work.

A: When you add #import <sqlite3.h> into Bridging-Header, the sqlite3 C/C++ API will be 'translated' into  native swift function. So, the sqlite3_open will be like below.
func sqlite3_open(file:String, inout ppdb:COpaquePointer) -> Int

And you can call this function with "String" type parameter instead of "CString". The swift compiler will translate "String" into UTF8 String data stream automatically.
let error = sqlite3_open(filePath, &db)


text:
Q: Is there any 'virtual browser' in PHP? HI,
I want to extract data from a website but it uses some strange javascript so I can't get the job done with cURL. I want to know is there anything like virtual browser which opens up the page and I can initiate click on some buttons?
If not is there any executable program to achieve this task via command line?

A: You have a few options:
Is there a PHP equivalent of Perl's WWW::Mechanize?
This one looks like it would fit the bill: ScriptableBrowser -  http://www.lastcraft.com/browser_documentation.php
EDIT- I see that you need a virtual browser with Javascript support.. I found a few options for Ruby and Python, but nothing in PHP.
Maybe you will have to drive this part of the application from a different language, or write it yourself. Or look into something like Selenium, there might be a way to use it for what you need.
More info:
How do I use Mechanize to process JavaScript?
http://pypi.python.org/pypi/DOMForm/0.0.1a/


text:
Q: What is the cost of a container? I usually use the same image for a docker volume container as the container that is going to use it. For example,
dbdata:
    image: mysql
    command: echo 'DVC for MySQL'
db:
    image: mysql
    volumes_from:
        - mysql
    …

Tiny DVCs using images like tianon/true are another approach. Since I don't have to pull another image, I'm pretty confident my approach uses marginally less bandwidth. But what are the downsides of my approach? You have to unpack the entire MySQL container, sure, but disk is cheap and we don't start any heavy processes; just echo, right? Does it make any practical difference in terms of machine resources and bandwidth if I recycle the main image for its DVC, or fetch a dedicated DVC type image? How can I assess this?

A: That tianon/dockerfiles/Dockerfile is from 2 years ago, at a time when you actually had to run a container, to use it as data volume container.
But since docker 1.8, you don't need to run a data volume container anymore.
You can just docker create it.
More recently, you docker volume create it: no image needed. No cost in process or bandwidth for a DVC.
So there is no cost in term of process anymore for a data volume container.


text:
Q: How can I upload the first name, last name, job and profile picture of the user? Please Help me
I want to know how to upload the first name, last name, job, date of birth and a picture of the user in Flutter Null Safety
this is my signup
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:newlivenullsaf/pages/login.dart';

class Signup extends StatefulWidget {
  @override
  State<Signup> createState() => _SignupState();
}

class _SignupState extends State<Signup> {
  final _formkey = GlobalKey<FormState>();
  var email = '';
  var password = '';
  var confirmPassword = '';
  @override
  void dispose() {
    emailController.dispose();
    passwordController.dispose();
    confirmPasswordController.dispose();

    super.dispose();
  }

  bool isLoading = false;
  final nameController = TextEditingController();
  final emailController = TextEditingController();
  final passwordController = TextEditingController();
  final confirmPasswordController = TextEditingController();
  registeration() async {
    if (password == confirmPassword) {
      try {
        UserCredential userCredential = await FirebaseAuth.instance
            .createUserWithEmailAndPassword(email: email, password: password);
        print(UserCredential);
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            backgroundColor: Colors.blueGrey,
            content: Text(
              'Registerd Successfully. Please Sign In ',
              style: TextStyle(fontSize: 20.0),
            ),
          ),
        );
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => const LoginPage(),
          ),
        );
      } on FirebaseAuthException catch (error) {
        if (error.code == 'week-password') {
          print('Password is too week');
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              backgroundColor: Colors.blueGrey,
              content: Text(
                'Password is too week ',
                style: TextStyle(fontSize: 20.0, color: Colors.amberAccent),
              ),
            ),
          );
        } else if (error.code == 'email-already-in-use') {
          print('Account is already exists');
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              backgroundColor: Colors.blueGrey,
              content: Text(
                'Account is already exists ',
                style: TextStyle(fontSize: 20.0, color: Colors.amberAccent),
              ),
            ),
          );
        }
      }
    } else {
      print('Password and Confirm Password does not match ');
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          backgroundColor: Colors.blueGrey,
          content: Text(
            'Password and Confirm Password does not match ',
            style: TextStyle(fontSize: 20.0, color: Colors.amberAccent),
          ),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;

    return Scaffold(
      backgroundColor: Colors.white,
      body: isLoading
          ? Center(
              child: Container(
                height: size.height / 20,
                width: size.height / 20,
                child: CircularProgressIndicator(),
              ),
            )
          : Form(
              key: _formkey,
              child: Padding(
                padding: const EdgeInsets.symmetric(
                    vertical: 20.0, horizontal: 20.0),
                child: ListView(
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(30.0),
                      child: Image.asset('images/signup.png'),
                    ),
                    Container(
                      margin: const EdgeInsets.symmetric(vertical: 10.0),
                      child: TextFormField(
                          autofocus: false,
                          decoration: const InputDecoration(
                            labelText: 'Name:',
                            labelStyle: TextStyle(fontSize: 20.0),
                            border: OutlineInputBorder(),
                            errorStyle: TextStyle(
                                color: Colors.black26, fontSize: 15.0),
                          ),
                          controller: nameController,
                          validator: (value) {
                            if (value == null || value.isNotEmpty) {
                              return 'Please Enter Your Name';
                            }
                            if (value.length > 4) {
                              return (' Name(Max. 4 Character)');
                            }

                            return null;
                          }),
                    ),
                    Container(
                      margin: const EdgeInsets.symmetric(vertical: 10.0),
                      child: TextFormField(
                          autofocus: false,
                          decoration: const InputDecoration(
                            labelText: 'Last Name:',
                            labelStyle: TextStyle(fontSize: 20.0),
                            border: OutlineInputBorder(),
                            errorStyle: TextStyle(
                                color: Colors.black26, fontSize: 15.0),
                          ),
                          controller: nameController,
                          validator: (value) {
                            if (value == null || value.isNotEmpty) {
                              return 'Please Enter Your Last Name';
                            }
                            if (value.length > 4) {
                              return ('Last Name(Max. 4 Character)');
                            }

                            return null;
                          }),
                    ),
                    Container(
                      margin: const EdgeInsets.symmetric(vertical: 10.0),
                      child: TextFormField(
                        autofocus: false,
                        decoration: const InputDecoration(
                          labelText: 'Email:',
                          labelStyle: TextStyle(fontSize: 20.0),
                          border: OutlineInputBorder(),
                          errorStyle:
                              TextStyle(color: Colors.black26, fontSize: 15.0),
                        ),
                        controller: emailController,
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return 'Please Enter Email';
                          } else if (!value.contains('@')) {
                            return 'Please Enter Valid Email';
                          }
                          return null;
                        },
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.symmetric(vertical: 10.0),
                      child: TextFormField(
                        autofocus: false,
                        obscureText: true,
                        decoration: const InputDecoration(
                          labelText: ' Password',
                          labelStyle: TextStyle(fontSize: 20.0),
                          border: OutlineInputBorder(),
                          errorStyle:
                              TextStyle(color: Colors.black26, fontSize: 15.0),
                        ),
                        controller: passwordController,
                        validator: (value) {
                          if (value == null ||
                              value.isEmpty ||
                              value.length < 6 ||
                              value.length > 14) {
                            return 'Please Enter Password';
                          }
                          return null;
                        },
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.symmetric(vertical: 10.0),
                      child: TextFormField(
                        autofocus: false,
                        obscureText: true,
                        decoration: const InputDecoration(
                          labelText: 'Confirm Password',
                          labelStyle: TextStyle(fontSize: 20.0),
                          border: OutlineInputBorder(),
                          errorStyle:
                              TextStyle(color: Colors.black26, fontSize: 15.0),
                        ),
                        controller: confirmPasswordController,
                        validator: (value) {
                          if (value == null ||
                              value.isEmpty ||
                              value.length < 6 ||
                              value.length > 14) {
                            return 'Please Confirm Password';
                          }
                          return null;
                        },
                      ),
                    ),
                    const SizedBox(
                      height: 10.0,
                    ),
                    Container(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          ElevatedButton(
                            onPressed: () {
                              if (_formkey.currentState!.validate()) {
                                setState(() {
                                  email = emailController.text;
                                  password = passwordController.text;
                                  confirmPassword =
                                      confirmPasswordController.text;
                                });
                                registeration();
                              }
                            },
                            child: const Text(
                              'Signup ',
                              style: TextStyle(fontSize: 18.0),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          const Text('Already Have An Account ?'),
                          TextButton(
                            onPressed: () {
                              Navigator.pushReplacement(
                                context,
                                PageRouteBuilder(
                                  pageBuilder:
                                      (context, animation1, animation2) =>
                                          const LoginPage(),
                                  transitionDuration:
                                      const Duration(seconds: 0),
                                ),
                              );
                            },
                            child: const Text('Login'),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
    );
  }
}

this is my main
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:newlivenullsaf/pages/login.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final Future<FirebaseApp> _initialization = Firebase.initializeApp();
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _initialization,
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          print('something wrong');
        }
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'Flutter email & password',
          theme: ThemeData(primarySwatch: Colors.blue),
          home: const LoginPage(),
        );
      },
    );
  }
}

this is my login
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:newlivenullsaf/pages/forget_password.dart';
import 'package:newlivenullsaf/pages/signup.dart';
import 'package:newlivenullsaf/pages/user_main.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _formKey = GlobalKey<FormState>();
  var email = "";
  var password = "";
  final emailController = TextEditingController();
  final passwordController = TextEditingController();
  userLogin() async {
    try {
      await FirebaseAuth.instance
          .signInWithEmailAndPassword(email: email, password: password);
      Navigator.pushReplacement(
          context, MaterialPageRoute(builder: (context) => const UserMain()));
    } on FirebaseAuthException catch (error) {
      if (error.code == ' user-not-found') {
        print('No user found for that email ');
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            backgroundColor: Colors.blueGrey,
            content: Text(
              'No user found for that email',
              style: TextStyle(
                fontSize: 18.0,
                color: Colors.amber,
              ),
            ),
          ),
        );
      } else if (error.code == 'wrong-password') {
        print('wrong password provided by the user');
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            backgroundColor: Colors.blueGrey,
            content: Text(
              'wrong password provided by the user',
              style: TextStyle(
                fontSize: 18.0,
                color: Colors.amber,
              ),
            ),
          ),
        );
      }
    }
  }

  @override
  void dispose() {
    emailController.dispose();
    passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Form(
        key: _formKey,
        child: Padding(
          padding: const EdgeInsets.symmetric(vertical: 40.0, horizontal: 20.0),
          child: ListView(
            children: [
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Image.asset('images/login.jpg'),
              ),
              Container(
                margin: const EdgeInsets.symmetric(vertical: 10.0),
                child: TextFormField(
                    autofocus: false,
                    decoration: const InputDecoration(
                      labelText: 'Email:',
                      labelStyle: TextStyle(fontSize: 20.0),
                      border: OutlineInputBorder(),
                      errorStyle:
                          TextStyle(color: Colors.black26, fontSize: 15.0),
                    ),
                    controller: emailController,
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return 'Please Enter Email';
                      } else if (!value.contains('@')) {
                        return 'Please Enter Valid Email';
                      }
                      return null;
                    }),
              ),
              Container(
                margin: const EdgeInsets.symmetric(vertical: 10.0),
                child: TextFormField(
                  autofocus: false,
                  obscureText: true,
                  decoration: const InputDecoration(
                    labelText: 'Password',
                    labelStyle: TextStyle(fontSize: 20.0),
                    border: OutlineInputBorder(),
                    errorStyle:
                        TextStyle(color: Colors.black26, fontSize: 15.0),
                  ),
                  controller: passwordController,
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Please Enter Password';
                    }
                    return null;
                  },
                ),
              ),
              Container(
                margin: const EdgeInsets.symmetric(vertical: 20.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    ElevatedButton(
                      onPressed: () {
                        if (_formKey.currentState!.validate()) {
                          setState(() {
                            email = emailController.text;
                            password = passwordController.text;
                          });
                          userLogin();
                        }
                      },
                      child: const Text(
                        'Login',
                        style: TextStyle(fontSize: 18.0),
                      ),
                    ),
                    TextButton(
                      onPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => ForgotPass(),
                          ),
                        );
                      },
                      child: const Text(
                        'Forget Password ?',
                        style: TextStyle(
                          fontSize: 12.0,
                        ),
                      ),
                    )
                  ],
                ),
              ),
              Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Text('Do Not Have Account ?'),
                    TextButton(
                      onPressed: () {
                        Navigator.pushAndRemoveUntil(
                            context,
                            PageRouteBuilder(
                              pageBuilder: (context, a, b) => Signup(),
                              transitionDuration: const Duration(seconds: 0),
                            ),
                            (route) => false);
                      },
                      child: const Text('Signup'),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Iused these packages
firebase_core: ^1.5.0
firebase_auth: ^3.0.2

I searched a lot and found a lot of codes and This code is the best I've found
please i need help quickly

A: I think you have to add (keep the auth like it is) cloud firestore and set a doc for each user contains his name , last name , job , profile pic etc...
so every user will have doc on cloud firestore and user on Auth
some sources :
to set the user in singUp page :
https://petercoding.com/firebase/2020/04/04/using-cloud-firestore-in-flutter/


text:
Q: Publish .NET Code application to Arvixe Host I have a ASP.NET Core with Blazor website and I want to deploy it to Arvixe host. The website is very simple and contains only UI elements no database required. I published the website to a local file system and uploaded it using FTP to the Plesk.
When I am visiting the website, I receive this error:

500 - Internal server error. There is a problem with the resource you
  are looking for, and it cannot be displayed.

I have tried to run it on the IIS and I received more details:

Configuration The configuration file cannot be read due to
  insufficient permissions.

I tried to add IIS_IUSRS to the group and users for web.config but I am not able to find it because I am using a windows 10 connected to active directory.
Besides, I still don't know how to solve this problem at Arvixe. Does anyone know tips might help?

A: 500 internal error is generic issue. Please kindly check the error message on the server and paste it here. Make sure that your provider has installed .net core bundled on their server and here are tutorial about publsih .net core using plesk https://windowswebhostingreview.com/how-to-publish-using-web-deploy-with-plesk-control-panel/. It should be working fine.

A: You need to give Full Trust permission (Read-Write-Execute) to your application folder and also to Application Pool and also check if the Runtime version supported by Arvixe matches with your Asp.net Core version.
Also enable the logs in web.config file by setting stdoutLogEnabled="true" to get detailed error so that you can investigate more about the error.


text:
Q: Retrieving element in an ArrayList Adapter I have created a listview that has an image and a button - I am using ArrayAdapter to view the items in the listview.
When I click on the button I would like to get the details of the item clicked.
So I tried the following:
pd = productList.get(position);

Where productList is ArrayList<ProductDetails> productList;
getproductdetailsbutton is a button in productListadapter extends ArrayAdapter<ProductDetails>
holder.getproductdetailsbutton.setOnClickListener(new View.OnClickListener()
{
     @Override
     public void onClick(View v) {

            String productID = pd.getProductID();
            String productName = pd. getProductName();

            Log.d("Value", " Product Details " + productID + " " + productName);
        }
 });

When I click the button from the first item, I get details of the last item displayed on the screen in the log.
How do I get the details of clicked item for that position?
Thanks!
UPDATE: getVIEW Code:
@Override
    public View getView(final int position, View convertView, final ViewGroup parent)
    {

        Typeface tf = Typeface.createFromAsset(contextValue.getAssets(), fontPath);
        Typeface tf2 = Typeface.createFromAsset(contextValue.getAssets(), fontPath2);

        ViewHolder holder = null;

        if (convertView == null)
        {

            convertView = vi.inflate(R.layout.product_details_items, null);

            holder = new ViewHolder();
            holder.image = (ImageView) convertView.findViewById(R.id.productimage);
            holder.productgetdetails = (Button) convertView.findViewById(R.id.productgetdetails);
            holder.productgetdetails.setTag(position);

            holder.productgetdetails.setTypeface(tf2);

            convertView.setTag(holder);

            ProductDetails pd = productList.get(position);

            if (pinexist.equalsIgnoreCase(contextValue.getString(R.string.pinexistvalue)))
            {
                Log.d("Value"," - ID " + pd.getProductID());

                if (logdb.checkproductDetailsExists(pd.getProductID()) == 0)
                {
                    holder.productgetdetails.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v)
                        {
                            Log.e("Value", " = FINAL" + productList.get(position).getProductID());
                        }
                    });
                }
                else
                {
                    holder.productgetdetails.setText(contextValue.getString(R.string.nodata));
                }

            }
            else
            {
                //DO NOTHING
            }
        }
        else
        {
            holder = (ViewHolder) convertView.getTag();
        }

        ProductDetails pd = productList.get(position);

        Glide.with(getContext().getApplicationContext())
                .load(pd.getProduct_image())
                .placeholder(R.drawable.placeholder)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(holder.image);

        return convertView;
    }

A: I guess(actually I'm confident), you must be declaring pd as global variable, which gets updated by last item displayed, try to move pd into getView() and mark it as final so you can use it inside onclick as in
public void getView(){
   final ProductDetails pd = productList.get(position);
   // your code for click
}

A: When inflating your layout to view in Adapter
you can set the OnClickListener on the button
public View getView(int position,View view,ViewGroup parent) {
        LayoutInflater inflater=context.getLayoutInflater();
        View rowView=inflater.inflate(R.layout.list_layout, null,true);
        final Product pd = pdList.get(position);
        //....
        Button btn= (Button) = rowView.findViewById(R.id.getproductdetailsbutton);
        btn.setOnClickListener(new View.OnClickListener()
        {
             @Override
             public void onClick(View v) {

                    String productID = pd.getProductID();
                    String productName = pd.getProductName();

                    Log.d("Value", " Product Details " + productID + " " + productName);
                }
         });
        //..

        return rowView;

    };

Or you can handle ListView OnItemClickListener


text:
Q: How can I change the charset incoming from Java servlet using JavaScript? I have this servlet at http://localhost.com.br:8080/servlet/apps.ctr.HTMLCtr?p1=getCtr. It returns a JSON by the way.
When I try to get data via JavaScript/jQuery the ã and ç characters turn into a black diamond with a question mark in the center: �
I thought there was something misconfigured in my server side, but if I try to reach it with my Chrome browser I get the data, such as:
"Liberação de Registro",
"Mar 28, 2016"

I thought this was related to the client side encoding, so I tried the options available at http://api.jquery.com/jQuery.ajax/#toptions:
var s = 'http://localhost.com.br:8080/servlet/apps.ctr.HTMLCtr?';
$.ajaxSetup({
    scriptCharset: "utf-8",
    contentType: "application/json;charset=utf-8"
});

$.getJSON(s,function(result){
    console.log(result);
});

I tried changing the charset to ISO-8859-1 or even ISO-8859-15 and running the above code on Chrome's console, but nothing has changed.
What am I missing here?
EDIT: This is not a duplicated of How to set encoding in .getJSON JQuery because that question is related to sending information to the servlet, my question is about getting the information from the servlet. Also, the solutions provided on that question on using $.ajaxSetup did not solve my issue.
EDIT2: The Response Header from Chrome:
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Pragma: no-cache
Cache-Control: max-stale=0
Expires: Wed, 31 Dec 1969 23:59:59 GMT
Content-Length: 224
Date: Thu, 14 Apr 2016 16:58:26 GMT

Also posting the HTML (I'm excluding the <body> part):
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page import="br.com.project1.usuario.Usuario"%>
<html>
  <head>
    <title>CbrCpt</title>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <link rel="stylesheet" href="/js/jquery-ui-1.11.1.custom/jquery-ui.css" />
    <link rel="stylesheet" href="/css/dataTables.jqueryui.css" />
    <link rel="stylesheet" href="css/bootstrap.css" />
    <link rel="stylesheet" href="css/default.css" />
    <link rel="stylesheet" href="/js/bootstrap-datepicker-1.5.0/css/bootstrap-datepicker3.min.css" />
    <link rel="stylesheet" href="css/jquery.dataTables.min.css" />
    <link rel="stylesheet" href="css/responsive.dataTables.min.css" />
  </head>
  <body>
  </body>
  <script type='text/javascript' src='/js/jquery/jquery-1.10.2.min.js'></script>
  <script type='text/javascript' src='js/bootstrap.min.js'></script>
  <script type='text/javascript' src='/js/jquery-ui-1.11.1.custom/jquery-ui.js'></script>
  <script type='text/javascript' src='/js/accounting.min.js'></script>
  <script type='text/javascript' src='/js/jquery.jqdock.min.js'></script>
  <script type='text/javascript' src='js/datepicker-pt-BR.js'></script>
  <script type='text/javascript' src='js/moment-with-locales.js'></script>
  <script type='text/javascript' src='js/jquery.dataTables.min.js'></script>
  <script type='text/javascript' src='js/dataTables.responsive.min.js'></script>
  <script type='text/javascript' src='js/jquery.maskedinput.js'></script>
  <script type='text/javascript' src='js/cbrcpt.js'></script>
</html>

EDIT3: When opening the response on the Chrome console, the information has the correct characters.


text:
Q: Type Mismatch Run-Time error 13 I have successfully run this macro before and now I am receiving a Mismatch error.
The macro copies all rows from a Data Tab (data-raw) where Col S = Cell D1 (on a different tab). Then pastes special values to a third tab (Rec01).
D1, formatted as General with Text data (name)
Col S, formatted as General, all formulas, displaying a name.
Sub CopyRowToRec01()
Dim LastRowData, LastRowRec01 As Long
Dim i As Long
Application.ScreenUpdating = False
LastRowData = Worksheets("data-raw-Comb").Range("A" & Rows.Count).End(xlUp).Row
With Worksheets("data-raw-Comb")
    For i = 2 To LastRowData Step 1
        If Cells(i, "S").Value = Worksheets("data-lookuptable").Range("D1") Then
            LastRowRec01 = Worksheets("Rec01").Range("A" & Rows.Count).End(xlUp).Row
            Rows(i).Copy
            Worksheets("Rec01").Range("A" & LastRowRec01 + 1).PasteSpecial Paste:=xlPasteValues
        End If
    Next i
End With
    Application.ScreenUpdating = True
End Sub

Running same version of Excel.
Any insight would be greatly appreciated.
DD

A:  If Cells(i, "S").Value = Worksheets("data-lookuptable").Range("D1") Then

Thank you every for your responses. I am not sure what changed from last time, but I had to change the .Value to .Text. Now it is running again, all data being pulled.
Sorry to bother.
Thanks again


text:
Q: Postgresql does not detect duplicate name when declaring a parameter or variable with the same name in a function I use the PG 13.1 version, I do not know if this is a bug or is the default behavior, have the following example
DROP FUNCTION IF EXISTS test;
CREATE OR REPLACE FUNCTION test(
    v1 int,
    v2 float
) RETURNS boolean AS
$$
DECLARE
    v1 int;
    v2 float;
BEGIN
    RAISE INFO 'v1 => %, v2 => %', v1, v2;
    RETURN true;
END;
$$
LANGUAGE plpgsql;

SELECT test(10,20);

Showing
INFO:  v1 => <NULL>, v2 => <NULL>

Successfully run. Total query runtime: 79 msec.
1 rows affected.

Could someone please explain why Postgres does not detect the "duplicate name" error?
Obviously the result it shows is that of the variables of the DECLARE section

A: As indicated by @Gordon you are running across Postgres's scooping rules. Variables created as parameters have (for lack of a better term) Functional scope while those within the block have (again for lack of a better term) Block scope. When references without qualification, the reference is always to the most resent definition, even within nested blocks.  Try the following; the values assigned are irreverent just notice results and where variable defined:
create or replace
function test(
               v1 int
             , v2 float
             )
 returns boolean
language plpgsql
as $$
declare                 -- an outer block
    v1 int = 18;
    v2 float = 45.55;
begin
    declare            -- a nested inner block
        v1 text := 'Same name, different type';
        v2 date := now()::date;
    begin
        raise info 'Inner Block: v1 => %, v2 => %', v1, v2;
    end;

    raise info 'Outer Block: v1 => %, v2 => %', v1, v2;
    raise info 'Function Parameters: v1 => %, v2 => %', test.v1, test.v2; -- Qualified
    return true;
end;
$$;


text:
Q: Netty ObjectDecoder throws java.io.StreamCorruptedException: unexpected end of block data I've an unusual problem that's causing me to tear my hair out. I have a Netty Client/Server setup. The server sends a command object to the client. The client then sends each of the binary commands found in the command object to a device attached to it's local serial port. The answers to each command ( a binary string) is stored within the command object and when all the commands have been executed, the command object is returned to the server. So I'm using the ObjectEncoder and ObjectDecoder in both my client and Server pipelines.
I have one specific, repeatable case where the server throws "java.io.StreamCorruptedException: unexpected end of block data" (stack trace below) when a specific command object is returned to the server. I'm using Netty 3.2.7-Final on both the server and client and I'm using Oracle Java 1.7.0_02 on both client and server.
What is really doing my head in is that if I run the client & server locally under Windows 7, then the job runs correctly. If I run the server remotely on a Debian Linux system then the specific job runs correctly. However, when ever I run the server on a Linux CentOS 6 system, the job fails every time with the exception. (The client has to run in a Windows environment)
Any suggestions as to how to debug this further would be very welcome. I've looked at extending ObjectEncoder so I can dump the serialized object to disk to see what is being put on the wire but I can't work out how to get the contents of the ChannelBuffer returned by the encode method.
java.io.StreamCorruptedException: unexpected end of block data
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1369)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1964)
    at java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:498)
    at java.lang.Throwable.readObject(Throwable.java:913)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:991)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1866)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1771)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1347)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1964)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1888)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1771)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1347)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
    at java.util.ArrayList.readObject(ArrayList.java:733)
    at sun.reflect.GeneratedMethodAccessor70.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:991)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1866)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1771)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1347)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1964)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1888)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1771)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1347)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
    at org.jboss.netty.handler.codec.serialization.ObjectDecoder.decode(ObjectDecoder.java:129)
    at org.jboss.netty.handler.codec.frame.FrameDecoder.callDecode(FrameDecoder.java:282)
    at org.jboss.netty.handler.codec.frame.FrameDecoder.messageReceived(FrameDecoder.java:214)
    at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:274)
    at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:261)
    at org.jboss.netty.channel.socket.nio.NioWorker.read(NioWorker.java:351)
    at org.jboss.netty.channel.socket.nio.NioWorker.processSelectedKeys(NioWorker.java:282)
    at org.jboss.netty.channel.socket.nio.NioWorker.run(NioWorker.java:202)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)

A: Since the problem occurs while decoding,
You can hex-dump of the received channel buffer to a log before decoding and analyse it later. You have to have your own version of the ObjectDecoder like
    @Override
protected Object decode(
        ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {

    ChannelBuffer frame = (ChannelBuffer) super.decode(ctx, channel, buffer);
    if (frame == null) {
        return null;
    }

    logger.debug("Hex dump of object frame [" + ChannelBuffers.hexDump(frame) + "]");

    return new CompactObjectInputStream(
            new ChannelBufferInputStream(frame), classResolver).readObject();
}


text:
Q: jsonp.java.net: how to build with maven How do I use maven to build ?
I got code from JSON Processing and as I'm not familiar with maven I have (almost) no clue how to build the API and implementation jar file.

A: Usually you do:
mvn clean install

You can use also verify instead of install if you don't want to put the code in the local repo. Or package if you don't want to do package verifications.
The resulting package can be found in the target directories (only one if there is single module, multiple if there are multiple ones).
But sometimes projects have their own build procedures and enable certain profiles (with -P switch) or system properties (with -D switch) so it is best to consult the project README or similar.