text:
Q: Can someone explain how to get the minimal polynomial for this matrix? This is example 8.45 from Sheldon Axler's Linear Algebra Done Right. $T$
is the operator on $\mathbb{C}^5$ whose matrix with respect to the standard basis is:\begin{matrix}
0 & 0 & 0 & 0 & -3\\
1 & 0 & 0 & 0 & 6\\
0&1&0&0&0\\
0&0&1&0&0\\
0&0&0&1&0
\end{matrix}
Find the minimal polynomial of $T$.
The solution is supposed to be $z^5-6z+3$ but I don't understand the steps to get to this.

A: If you know about companion matrix this is obvious.
If not, you can compute the characteristic polynomial of $A$ and get $\chi_A(x)=x^5-6x+3$.  Since $A$ has no repeated eigenvalues, a fact you can easily check with the roots of $\chi'_A(x)=5x^4-6$ (or use Eisenstein criterion), the minimal polynomial coincide with characteristic polynomial.
Or you can show by direct computation that $T^4,T^3,T^2,T,I$ are linearly independent (look at where $e_1$ got sent to).  Hence the minimal polynomial must be a quintic, etc.

A: Let $e_n$ be the column vector with all $0$'s except for a $1$ in the $n$-th column from the top, for $n=1,2,3,4,5$. Then $Te_1=e_2$, $Te_2=e_3$, $Te_3=e_4$, $Te_4=e_5$, and $Te_5=-3e_1+6e_2$. Therefore,
$$
                T^5e_1=-3e_1+6Te_1 \\
                (T^5-6T+3I)e_1=0.
$$
By applying powers of $T$, you can conclude that $(T^5-6T+3I)e_k=0$ for $k=1,2,3,4,5$. $p(\lambda)=\lambda^5-6\lambda+3$ is the minimal polynomial of $T$.

A: Without loss of specificity (i.e., more generally) assume the final column has entries $c_0,\ldots,c_4$; here is how one can show that the minimal polynomial is $X^5-c_4X^4-c_3X^3-c_2X^2-c_1X-c_0$. Since the first $4$ columns of the matrix are equal to the last $4$ columns of the identity matrix $I_5$, in other words column $j$ equals the standard basis vector $e_{j+1}$ for $j=1,2,3,4$, one has (by induction if you will) $T^j(e_1)=e_{j+1}$ for those $j$ (and also for $j=0$), and the final column gives $T^5(e_1)=T(e_5)=c_0e_1+c_2e_2++c_2e_3+c_3e_4+c_4e_5$. [This is a nice point to remark that the habit of numbering things, like standard basis vectors and columns, from $1$ rather than $0$ is unfortunate.]
Now consider annihilating polynomials $P$ of $T$, namely those for which $P[T]=0$. A necessary condition for this (i.e., a weaker condition) is that $P[T](e_1)=0$. If $P$ were a nonzero polynomal of degree${}<5$, then this gives a nontrivial relation between $T^j(e_1)$ for $j=0,1,2,3,4$, but those are the standard basis vectors $e_1,e_2,e_3,e_4,e_5$ which are linearly independent; this cannot happen. On the other hand we do have (by the computation of $T^5(e_1)$) that $P[T](e_1)=0$ for $P=X^5-c_4X^4-c_3X^3-c_2X^2-c_1X-c_0$, and for no other monic polynomial of degree$~5$. So we know that the minimal polynomial of $T$ is certainly not of degree${}<5$, and if it is of degree$~5$ then it must be the mentioned polynomial.
It remains to show that $P[T]=0$ for that polynomial, in other words that $P[T](v)=0$ for any $v\in\Bbb C^5$, not just for $v=e_1$. Since the vectors $T^j(e_1)$ for $j=0,1,2,3,4$ span $\Bbb C^5$, there is a (unique) polynomial $Q$ of degree${}<5$ such that $v=Q[T](e_1)$. Then
$$P[T](v)=P[T](Q[T](e_1)) =(PQ)[T](e_1) =Q[T](P[T](e_1)) =Q[T](0)=0,$$ since $Q[T]$ is a linear map. QED.


text:
Q: How to sum specific columns while keeping the unique ID without nan So my dataframe is-
Name   ID   A B C
Sam    11   1 1 1
Sam    nan  0 1 4
Dan    12   1 4 4
Dan    nan  1 5 0
Dan    12   2 4 4
Tom    15   1 4 6

I want to create an output containing-
Name ID Total
Sam  11  8
Dan  12  25
Tom  15  11

While I do groupby Name and ID. I get Sam and Dan twice for its null ID. How do I aggregate there A,B,C and get there unique ID as there final output?

A: Here you go:
# First make dataframe with names and total scores.
df['Total'] = df['A'] + df['B'] + df['C']
df_names = pd.DataFrame(df.groupby('Name')['Total'].sum())

# Then make dataframe that has the IDs.
df_ID = pd.DataFrame(df[['Name', 'ID']].dropna())
df_ID.set_index('Name', inplace=True)

# Then add in the IDs to the dataframe with total scores.
df_names['ID'] = df_ID.drop_duplicates()

Now df_names is the final dataframe you're looking for!

A: out = (df.drop("ID", axis=1)
         .groupby(["Name", df.ID.ffill(downcast="infer")], sort=False)
         .sum()
         .sum(axis=1)
         .to_frame("Total"))

First drop the ID column (but not in-place) to ignore it in the summation, then group by the Name and the forward-filled ID and sum the in-group values. Then sum all the column values to get the total and turn it into a dataframe with column Total
to get
>>> out

         Total
Name ID
Sam  11      8
Dan  12     25
Tom  15     11

downcast=infer helps keep the IDs integer after forward-filling and sort=False keeps the order in the dataframe while grouping.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Перестал работать авто расчет стоимости и не появляется описание в конечной точке ymaps.modules.define(
    'DeliveryCalculator',
    ['util.defineClass'],
    function (provide, defineClass) {
        /**
         * @class DeliveryCalculator Расчет стоимости доставки.
         * @param {Object} map    Экземпляр карты.
         */
        function DeliveryCalculator (map) {
            this._map = map;
            this._startPoint = null;
            this._route = null;
            this._startPointBalloonContent;
            this._finishPointBalloonContent;

            map.events.add('click', this._onClick, this);
        }

        defineClass(DeliveryCalculator, {
            /**
             * Создаем начальную точку маршрута.
             * Если точка создана, то обновляем координаты.
             * @param {Number[]} position Координаты точки.
             */
            setStartPoint: function (position) {
                if (this._startPoint) {
                    this._startPoint.geometry.setCoordinates(position);
                } else {
                    // Создаем маркер с возможностью перетаскивания (опция `draggable`).
                    // По завершении перетаскивания вызываем обработчик `_onStartDragEnd`.
                    this._startPoint = new ymaps.Placemark(position, {iconContent: 'А'}, {draggable: true});
                    this._startPoint.events.add('dragend', this._onStartDragEnd, this);
                    this._map.geoObjects.add(this._startPoint);
                }
                this.geocode('start', position);
            },

            /**
             * Создаем конечную точку маршрута.
             * Если точка создана, то обновляем координаты.
             * @param {Number[]} position Координаты точки.
             */
            setFinishPoint: function (position) {
                if (this._finishPoint) {
                    this._finishPoint.geometry.setCoordinates(position);
                } else {
                    this._finishPoint = new ymaps.Placemark(position, { iconContent: 'Б' }, { draggable: true });
                    this._finishPoint.events.add('dragend', this._onFinishDragEnd, this);
                    this._map.geoObjects.add(this._finishPoint);
                }
                if (this._startPoint) {
                    this.geocode('finish', position);
                }
            },

            /**
             * Проводим обратное геокодирование (определяем адрес по координатам) для точек маршрута.
             * @param {String} pointType Тип точки: 'start' - начальная, 'finish' - конечная.
             * @param {Number[]} point Координаты точки.
             */
            geocode: function (pointType, point) {
                ymaps.geocode(point).then(function (result) {
                    // result содержит описание найденных геообъектов.
                    if (pointType == 'start') {
                        // Получаем описание первого геообъекта в списке, чтобы затем показать
                        // с описанием доставки по клику на метке.
                        this._startPointBalloonContent = result.geoObjects.get(0) &&
                            result.geoObjects.get(0).properties.get('balloonContentBody') || '';
                    } else {
                        // То же самое для конечной точки
                        this._finishPointBalloonContent = result.geoObjects.get(0) &&
                            result.geoObjects.get(0).properties.get('balloonContentBody') || '';
                    }
                    this._setupRoute();
                }, this);

            },

            /**
             *
             * @param  {Number} routeLength Длина маршрута в километрах.
             * @return {Number} Стоимость доставки.
             */
            calculate: function (routeLength) {
                // Константы.
                var DELIVERY_TARIF = 25, // Стоимость за километр.
                    MINIMUM_COST = 300, // Минимальная стоимость.

                    RASHOD_AVTO1 = 10, // Средний расход авто 10л на 100км
                    RASHOD_KM = 100, // Средний расход авто на 100км
                    PRICE_FUEL = 38; // Цена топлива

                return Math.max(routeLength * DELIVERY_TARIF, MINIMUM_COST);
            },

            /**
             * Прокладываем маршрут через заданные точки
             * и проводим расчет доставки.
             */
            _setupRoute: function () {
                // Удаляем предыдущий маршрут с карты.
                if (this._route) {
                    this._map.geoObjects.remove(this._route);
                }

                if (this._startPoint && this._finishPoint) {
                    var start = this._startPoint.geometry.getCoordinates(),
                        finish = this._finishPoint.geometry.getCoordinates(),
                        startBalloon = this._startPointBalloonContent,
                        finishBalloon = this._finishPointBalloonContent;

                    // Прокладываем маршрут через заданные точки.
                    ymaps.route([start, finish])
                        .then(function (router) {
                            var distance = Math.round(router.getLength() / 1000),
                                message = 'Расстояние: ' + distance + 'км.
' +
                                    'Стоимость доставки: %sр.
' +
                                    'Расстояние: ' + distance + 'км.
'

                            this._route = router.getPaths(); // Получаем коллекцию путей, из которых состоит маршрут.

                            this._route.options.set({ strokeWidth: 5, strokeColor: '0000ffff', opacity: 0.5 });
                            this._map.geoObjects.add(this._route); // Добавляем маршрут на карту.
                            // Задаем контент балуна для начального и конечного маркера.
                            this._startPoint.properties.set('balloonContentBody', startBalloon + message.replace('%s', this.calculate(distance)));
                            this._finishPoint.properties.set('balloonContentBody', finishBalloon + message.replace('%s', this.calculate(distance)));
                            // Открываем балун над точкой доставки.
                            // Закомментируйте, если не хотите показывать балун автоматически.
                            this._finishPoint.balloon.open();
                        }, this);

                    this._map.setBounds(this._map.geoObjects.getBounds());
                }
            },

            /**
             * Обработчик клика по карте. Получаем координаты точки на карте и создаем маркер.
             * @param  {Object} event Событие.
             */
            _onClick: function (event) {
                if (this._startPoint) {
                    this.setFinishPoint(event.get('coords'));
                } else {
                    this.setStartPoint(event.get('coords'));
                }
            },

            /**
             * Получаем координаты маркера и вызываем геокодер для начальной точки.
             */
            _onStartDragEnd: function () {
                this.geocode('start', this._startPoint.geometry.getCoordinates());
            },

            _onFinishDragEnd: function () {
                this.geocode('finish', this._finishPoint.geometry.getCoordinates());
            }
        });

        provide(DeliveryCalculator);
    }
);


text:
Q: Increasing the speed of finding an index of an item in list I'm trying to speed up a program I've written, and after importing cProfile, I see that one function takes up a massive bit of computation time.
It's this, which finds an numpy.ndarray in a list:
    def locate(arr, l ):
        for i in range(len(l)):
            if np.all(l[i] == arr):
                return i
        return -1

As the list can't be ordered etc, I can't see any way to avoid scanning the entire list. I have read some pieces on vectorisation, and I wanted to know if that could be applied here, or if there's any other way to speed this up?
Thanks

A: You probably cannot avoid walking the list but you can speed up the comparison:
Set up example:
L  = list(np.floor(np.outer(*2*(np.linspace(1,10,1000),))))
arr = L[537]

Direct method for reference:
import itertools as it

next(it.chain((i for i, a in enumerate(L) if np.all(arr==a)), (-1,)))
# 537
timeit(lambda: next(it.chain((i for i, a in enumerate(L) if np.all(arr==a)), (-1,))), number=100)
# 0.27100146701559424

Approach 1: Use np.array_equal (slower)
next(it.chain((i for i, a in enumerate(L) if np.array_equal(arr, a)), (-1,)))
# 537
timeit(lambda: next(it.chain((i for i, a in enumerate(L) if np.array_equal(arr, a)), (-1,))), number=100)
# 0.2992244770284742

Approach 2: Use void view (faster)
arr_v = arr.reshape(-1).view(f'V{arr.itemsize*arr.size}')

next(it.chain((i for i, a in enumerate(L) if arr_v==a.reshape(-1).view(f'V{a.itemsize*a.size}')), (-1,)))
# 537
timeit(lambda: next(it.chain((i for i, a in enumerate(L) if arr_v==a.reshape(-1).view(f'V{a.itemsize*a.size}')), (-1,))), number=100)
# 0.11853155982680619

A: There is a built-in python function called index() where you can use it by plugging a string in as the value and finding its index in the list.

A: So are you looking for np.where
temp_list=np.array(temp_list)
np.where(temp_list==5)
(array([1, 3, 6, 8]),)

A: How to Check if a Matrix is in a List of Matrices Python
Here the accepted answer uses np.array_equal which first checks shape, then does the all(==) test.
Another SO: Check if 2d array exists in 3d array in Python?
Searching an array for a value faster than np.where(ar==value) using fortran and f2py
Why isn't "numpy.any" lazy (short-circuiting)


text: Q: Flame under immense pressure and moderate temperature Consider the flame inside a rocket engine's pre-burner, where the pressure is truly immense (400~600 bar) but the temperature is quite mild (<1500 K), and the flame is of the premixed type. Under these conditions, the mean free path of the reacting gas molecules is very small. If one was to be able to somehow take a look at this flame, what would he see? Would the spectral characteristic of specific lines of chemiluminescence be irrelevant and the flame would look almost like a blackbody of similar temperature? The molecules would collide and redistribute the energy so often that an exited molecule seldom has the chance to radiate this energy away.


text:
Q: Python: What is the default handling of SIGTERM? What does Python do under the covers by default if it receives a SIGTERM but there is no signal handler registered for it?

A: Building on the answer of Thomas Wouters, python does not register a handler for the SIGTERM signal.  We can see this by doing:
In[23]: signal.SIG_DFL == signal.signal(signal.SIGTERM,signal.SIG_DFL)
Out[23]: True

That means that the system will take the default action.  On linux, the default action (according to the signal man page) for a SIGTERM is to terminate the process.
Terminating a process means that:

*

*the process will simply not be allocated any more time slices during which it can execute code.

*

*This means that it will not raise an exception, or call the code in try: finally: blocks, or the __exit__ method of context managers.  It will not do those things because that particular python interpreter will never get the chance to execute another instruction.

*The process's memory and other resources (open files, network sockets, etc...) will be released back to the rest of the system.

A: Nothing. Python itself does not register a signal handler for it. You can check this in the interactive interpreter:
>>> import signal
>>> signal.signal(signal.SIGTERM, signal.SIG_DFL)
0
>>> signal.SIG_DFL
0

That shows signal.signal() returning signal.SIG_DFL for signal.SIGTERM. Contrast it with signal.SIGINT, which does have a default signal handler (which raises KeyboardInterrupt):
>>> signal.signal(signal.SIGINT, signal.SIG_DFL)
<built-in function default_int_handler>

A: Look at this example:
import time

class A:
    def __init__(self):
        print("A.__init__()")

    def __del__(self):
        print("A.__del__()")

a = A()
b = A()

time.sleep(10)

Under normal circumstances, the output would be:
A.__init__()
A.__init__()
A.__del__()
A.__del__()

But if you kill it with SIGTERM you get:
A.__init__()
A.__init__()
Terminated

Thus the program does not terminate cleanly (the destructors are not called).


text:
Q: Partition function is simply temperature if possible sub system energy is continuous? Partition function is $$Z=\sum_j\exp\left(-\frac{\epsilon_j}{kT}\right)$$ a sum over all possible energy levels $\epsilon_1,\epsilon_2, ..., \epsilon_M$. There must be a finite number of choices otherwise $Z$ does not converge.
If each individual subsystem can have a range of energy level, naturally I can rewrite this to integrals: $$Z=\int_0^\infty\exp\left(-\frac\epsilon{kT}\right)\mathrm d \epsilon = kT.$$ I can get this generalization from variation of entropy (as the normalization constant) as well. Does this mean that if the subsystem can have continuous range of non-negative energy, the partition function is simply that? Or am I missing something?

A:
If each individual subsystem can have a range of energy level

I'm not sure what you mean here. The summation in the partition function applies when the energy states are discrete. When they are continuous, as is the case in most of classical stat mech$^*$, the sum is replaced by an integral. This has nothing to do with subsystems; it is merely a consequence of switching to a continuous energy spectrum.
As @alarge said, the Boltzmann factor should be weighted by the degeneracy in the discrete case or the density of states in the continuous case. Then your partition function, to within a constant factor, is
$$Z = \int \Omega\left( E\right)e^{-E/kT}\mathrm{d}E$$
However, in most cases the calculation of $\Omega\left( E\right)$ is non-trivial at best, and outright impossible at worst.
A major benefit of the canonical ensemble is that we don't actually need to calculate $\Omega\left( E\right)$ if we know how the energy depends on the degrees of freedom within the system. For this we use the Hamiltonian function, which for, e.g. a gas particle, describes the energy in terms of the position and momentum of the particle. It is then sufficient to integrate the Boltzmann factor - with the Hamiltonian replacing $E$ - over all of phase space (all possible positions and momenta), like so:
$$Z = \int e^{-H\left(q, p\right)/kT}dqdp$$
where $q$ and $p$ are the position and momentum, respectively, and constants have again been omitted for clarity.
So to answer your question, it is not sufficient to integrate the energy over all states. If you want to integrate the energy, you need to weight it with the DOS. However, I highly suggest you take the approach of summing or integrating the Hamiltonian over all degrees of freedom.
$^*$ Discrete systems are generally easier to deal with, so they are often introduced first.


text:
Q: Spark Thrift Server - Unable to start (Hive error) I'm trying to launch the Spark Thrift server (Spark 1.2) on HDP 2.2.0 with Hive 0.14 (latest HortonWorks distribution) but unfortunately I'm getting this error that is quite cryptic for me :
Exception in thread "main" java.lang.RuntimeException: java.lang.NumberFormatException: For input string: "5s"
        at org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:346)
        at org.apache.spark.sql.hive.HiveContext$$anonfun$4.apply(HiveContext.scala:235)
        at org.apache.spark.sql.hive.HiveContext$$anonfun$4.apply(HiveContext.scala:231)
        at scala.Option.orElse(Option.scala:257)
        at org.apache.spark.sql.hive.HiveContext.x$3$lzycompute(HiveContext.scala:231)
        at org.apache.spark.sql.hive.HiveContext.x$3(HiveContext.scala:229)
        at org.apache.spark.sql.hive.HiveContext.hiveconf$lzycompute(HiveContext.scala:229)
        at org.apache.spark.sql.hive.HiveContext.hiveconf(HiveContext.scala:229)
        at org.apache.spark.sql.hive.HiveContext.runHive(HiveContext.scala:292)
        at org.apache.spark.sql.hive.HiveContext.runSqlHive(HiveContext.scala:276)
        at org.apache.spark.sql.hive.HiveContext.setConf(HiveContext.scala:248)
        at org.apache.spark.sql.SQLContext$$anonfun$2.apply(SQLContext.scala:91)
        at org.apache.spark.sql.SQLContext$$anonfun$2.apply(SQLContext.scala:90)
        at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
        at scala.collection.mutable.ArrayOps$ofRef.foreach(ArrayOps.scala:108)
        at org.apache.spark.sql.SQLContext.<init>(SQLContext.scala:90)
        at org.apache.spark.sql.hive.HiveContext.<init>(HiveContext.scala:72)
        at org.apache.spark.sql.hive.thriftserver.SparkSQLEnv$.init(SparkSQLEnv.scala:51)
        at org.apache.spark.sql.hive.thriftserver.HiveThriftServer2$.main(HiveThriftServer2.scala:56)
        at org.apache.spark.sql.hive.thriftserver.HiveThriftServer2.main(HiveThriftServer2.scala)
        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:606)
        at org.apache.spark.deploy.SparkSubmit$.launch(SparkSubmit.scala:358)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:75)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.NumberFormatException: For input string: "5s"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
        at java.lang.Integer.parseInt(Integer.java:492)
        at java.lang.Integer.parseInt(Integer.java:527)
        at org.apache.hadoop.conf.Configuration.getInt(Configuration.java:1094)
        at org.apache.hadoop.hive.conf.HiveConf.getIntVar(HiveConf.java:1211)
        at org.apache.hadoop.hive.conf.HiveConf.getIntVar(HiveConf.java:1220)
        at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.<init>(RetryingMetaStoreClient.java:58)
        at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.getProxy(RetryingMetaStoreClient.java:72)
        at org.apache.hadoop.hive.ql.metadata.Hive.createMetaStoreClient(Hive.java:2453)
        at org.apache.hadoop.hive.ql.metadata.Hive.getMSC(Hive.java:2465)
        at org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:340)
        ... 26 more

Does anyone can help me fixing this issue? Same happens when I try to execute any command from the Spark shell related to Hive (like creating table, inserting data into existing one etc ..)

A: You should review your configuration.

*

*Check if you can issue commands from Hive.

*If no, look for string "5s" in hive-site.xml

A: I have faced the same BUG.
HDP2.2.4 have a wrong config file for hive
<property>
  <name>hive.metastore.client.connect.retry.delay</name>
  <value>5s</value>
</property>

should be
<value>5<values>

Hontonworks forum is very slow for user from china. So I can't post this bug to them =_="


text:
Q: how to get text of the neighbour textviews on some other textview's onclick event in dynamic table? i have textviews in table layout like this
----------------
|txt1|txt2|txt3|
----------------
|txt4|txt5|txt6|
----------------
|txt7|txt8|txt9|
----------------
|txt1|txt2|txt3|
----------------
|txt4|txt5|txt6|
----------------
|txt7|txt8|txt9|

and so on and on and on0
in this manner i am adding textviews again and again in for loop in the table layout acc to the data which is coming dynamically...
on txt7 click listener event i can get the text of the txt7 like this
((TextView)v).getText().toString();

now i need text of txt8 and txt9 text on txt7 click event
some body suggested me to do this by tagging textview
TextView uniqueTextView = (TextView)findViewById(R.id.unique_id);
TextView neighbourView = new TextView();
neighbourView.setTag(uniqueTextView);

public void onTextViewClick(TextView view) {
TextView uniqueTextView = (TextView)view.getTag();
String text = uniqueTextView.getText().toString();   }

but this for one textview... how can i get text of both textview(txt8+txt9) on txt7 click listener.... plus i need text from txt7 also....
if it is not clear then you can comment....
this is dynamic table which i am creating
TableRow tr1 = (TableRow) new TableRow(this);
TextView txt1=new TextView(this);
TextView txt2=new TextView(this);
TextView txt3=new TextView(this);
txt1.setText("Data1);
txt2.setText("Data2);
txt3.setText("Data3);
txt1.setTag(1, txt2.getText().toString());
txt1.setTag(2, txt3.getText().toString());

txt1.setOnClickListener(new View.OnClickListener()
{
     public void onClick(View v)
     {
    try
    {
          Log.i("asdasd","Yahoo");
              Toast(((TextView)v).getTag(1).toString());
              Toast(((TextView)v).getTag(2).toString());
    }
    catch(Exception e)
    {
         Log.i("Error came while getting tag of txt1", e.getMessage());
        Toast("unable to bind tag");
        }
     }
});

tr1.addView(txt1);
tr1.addView(txt2);
tr1.addView(txt3);
TableLayout tl.addView(tr1,new TableLayout.LayoutParams(layoutParams));

as i cant set txt1 in place of ((TextView)v) because it will always give text of the last tablerow's txt1
04-20 12:42:39.236: ERROR/AndroidRuntime(522): Uncaught handler: thread main exiting due to uncaught exception
04-20 12:42:39.476: ERROR/AndroidRuntime(522): java.lang.NullPointerException: println needs a message
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at android.util.Log.println(Native Method)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at android.util.Log.i(Log.java:136)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at com.connection.demotable$1.onClick(demotable.java:431)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at android.view.View.performClick(View.java:2364)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at android.view.View.onTouchEvent(View.java:4179)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at android.widget.TextView.onTouchEvent(TextView.java:6541)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at android.view.View.dispatchTouchEvent(View.java:3709)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at android.os.Looper.loop(Looper.java:123)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at android.app.ActivityThread.main(ActivityThread.java:4363)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at java.lang.reflect.Method.invokeNative(Native Method)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at java.lang.reflect.Method.invoke(Method.java:521)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
04-20 12:42:39.476: ERROR/AndroidRuntime(522):     at dalvik.system.NativeStart.main(Native Method)

A: why don't you try setTag (int key, Object tag) and getTag(int)

A: As in the example code you posted try this
txt7.setTag(1, txt8);
txt7.setTag(2, txt9);

public void onTextViewClick(TextView view) {
TextView txt8 = (TextView)view.getTag(1);
TextView txt9 = (TextView)view.getTag(2);   }

A: I have not used table layout yet. But you may can use like this
TableRow t =  (TableRow) v.getParent();
TextView t1 = (TextView) t.getChildAt(0);
TextView t2 = (TextView) t.getChildAt(1);
TextView t3 = (TextView) t.getChildAt(2);


text: Q: calculating how many lines of code in ipython notebook just for curiosity sake - is there a way to find how many lines of code you've written in your ipython notebook? I have multiple lines per box, so I can't just count the number of boxes I have...


text:
Q: Elasticsearch High CPU and RAM usage I am a newbie in this area. I have setup elasticsearch. It works fine but the cpu usage and memory used becomes very high. This is hampering the servers performance. This is my elastic search version
{
  "status" : 200,
  "name" : "Aireo",
  "cluster_name" : "elasticsearch",
  "version" : {
    "number" : "1.4.4",
    "build_hash" : "c88f77ffc81301dfa9dfd81ca2232f09588bd512",
    "build_timestamp" : "2015-02-19T13:05:36Z",
    "build_snapshot" : false,
    "lucene_version" : "4.10.3"
  },
  "tagline" : "You Know, for Search"
}

Server config:
cpu family  : 6
model       : 62
model name  : Intel(R) Xeon(R) CPU E5-2630L v2 @ 2.40GHz
stepping    : 4
microcode   : 0x1
cpu MHz     : 2399.998
cache size  : 15360 KB
MemTotal:        2049964 kB
MemFree:          122056 kB
Buffers:           77396 kB
Cached:           184528 kB
SwapCached:            0 kB
Active:          1685792 kB
Inactive:         139420 kB
Active(anon):    1569940 kB
Inactive(anon):     8332 kB
Active(file):     115852 kB
Inactive(file):   131088 kB
Unevictable:           0 kB
Mlocked:               0 kB
SwapTotal:             0 kB
SwapFree:              0 kB

System usage:
 PID  USER      PR      NI    VIRT        RES          SHR     S    %CPU     %MEM       TIME+      COMMAND
27029 elastic+  20      0     4361248     1.186g       7372    S     110.7    60.7       1037:36    java

_nodes/stats/jvm
{
   "cluster_name":"elasticsearch",
   "nodes":{
      "cYUNisljRXmeLSiMk6kY_Q":{
         "timestamp":1450761255965,
         "name":"Aireo",
         "transport_address":"inet[128.199.229.70/128.199.229.70:9300]",
         "host":"TLM",
         "ip":[
            "inet[128.199.229.70/128.199.229.70:9300]",
            "NONE"
         ],
         "jvm":{
            "timestamp":1450761255965,
            "uptime_in_millis":64493824,
            "mem":{
               "heap_used_in_bytes":1051633552,
               "heap_used_percent":99,
               "heap_committed_in_bytes":1056309248,
               "heap_max_in_bytes":1056309248,
               "non_heap_used_in_bytes":85983832,
               "non_heap_committed_in_bytes":87912448,
               "pools":{
                  "young":{
                     "used_in_bytes":139591680,
                     "max_in_bytes":139591680,
                     "peak_used_in_bytes":139591680,
                     "peak_max_in_bytes":139591680
                  },
                  "survivor":{
                     "used_in_bytes":12757624,
                     "max_in_bytes":17432576,
                     "peak_used_in_bytes":17432576,
                     "peak_max_in_bytes":17432576
                  },
                  "old":{
                     "used_in_bytes":899284872,
                     "max_in_bytes":899284992,
                     "peak_used_in_bytes":899284992,
                     "peak_max_in_bytes":899284992
                  }
               }
            },
            "threads":{
               "count":50,
               "peak_count":52
            },
            "gc":{
               "collectors":{
                  "young":{
                     "collection_count":844,
                     "collection_time_in_millis":4550
                  },
                  "old":{
                     "collection_count":20606,
                     "collection_time_in_millis":54410384
                  }
               }
            },
            "buffer_pools":{
               "direct":{
                  "count":49,
                  "used_in_bytes":6269492,
                  "total_capacity_in_bytes":6269492
               },
               "mapped":{
                  "count":1202,
                  "used_in_bytes":863065239,
                  "total_capacity_in_bytes":863065239
               }
            }
         }
      }
   }
}

I am using the default configuration in the elasticsearch xml.
Thanks in advance

A: By default, Elasticsearch contains 1 GB heap size by default.

For just about every deployment, this number is far too small. If you
  are using the default heap values, your cluster is probably configured
  incorrectly.

You need to increase your RAM or you can reduce Heap Size(if you playing with small amount of data)
Setting Heap Size


text:
Q: String between a line By some google resources I could write a program to extract the string between two specific strings. I could not print value or store the value into a variable using regular expressions. Here is my code.
prgName = InStr(vText, "Program")
sub_prgName = Mid(vText, prgName, 100)
MsgBox sub_prgName, vbInformation
Dim RegEx: Set RegEx = New RegExp
RegEx.IgnoreCase = True
RegEx.Pattern = "Program(.*)?Variant"
Set RegEx = RegEx.Execute(prgName)
MsgBox RegEx.Value, vbInformation

I want to get the string b/w Program and Variant. When try to see the output it says

Run time error 438, object doesn't support this property.

This is the value that I want to parse using RegEx:
Program

sqlplus $SOPS_MIPO_USER/$SOPS_MIPO_PASSWORD@$DB_SID @mipo_pruning.sql

Variant

A: When in doubt, read the documentation. The Execute method returns a Matches collection, so you need to iterate over that collection to get the desired result (in your case the first submatch).
For Each m In RegEx.Execute(prgName)
  MsgBox m.SubMatches(0), vbInformation
Next

Demonstration:
>>> s = "Program sqlplus $SOPS_MIPO_USER/$SOPS_MIPO_PASSWORD@$DB_SID @mipo_pruning.sql Variant N/A"
>>> Set re = New RegExp
>>> re.Pattern = "Program(.*)?Variant"
>>> re.IgnoreCase = True
>>> For Each m In re.Execute(s) : WScript.Echo m.SubMatches(0) : Next
 sqlplus $SOPS_MIPO_USER/$SOPS_MIPO_PASSWORD@$DB_SID @mipo_pruning.sql
Theoretically you could also do this without the loop:
Set m = RegEx.Execute(prgName)(0)
MsgBox m.SubMatches(0), vbInformation

However, RegEx.Execute(prgName)(0) would raise an error if the regular expression didn't find a match, so evaluating the results in a loop is the safer approach.
I'd remove the ? in your regular expression, though, because it'll make the group optional, so you're not guaranteed to have a SubMatches(0) item. Simply use Program(.*)Variant instead. If there's no text between "Program" and "Variant" you'll get a zero-length string as the first submatch. Or you could put it inside the parentheses right after the asterisk (Program(.*?)Variant) to make the match non-greedy (shortest match instead of longest match).
If your input string contains newlines you need to use [\s\S] instead of ., because the dot in regular expressions matches any character except newlines.
Demonstration:
>>> s = "Program" & vbNewLine & vbNewLine _
& "sqlplus $SOPS_MIPO_USER/$SOPS_MIPO_PASSWORD@$DB_SID @mipo_pruning.sql" _
& vbNewLine & vbNewLine & "Variant"
>>> WScript.Echo s
Program

sqlplus $SOPS_MIPO_USER/$SOPS_MIPO_PASSWORD@$DB_SID @mipo_pruning.sql

Variant
>>> Set re = New RegExp
>>> re.Pattern = "Program(.*)?Variant"
>>> re.IgnoreCase = True
>>> For Each m In re.Execute(s) : WScript.Echo m.SubMatches(0) : Next
>>> re.Pattern = "Program([\s\S]*)?Variant"
>>> For Each m In re.Execute(s) : WScript.Echo m.SubMatches(0) : Next

sqlplus $SOPS_MIPO_USER/$SOPS_MIPO_PASSWORD@$DB_SID @mipo_pruning.sql

As a side note, you shouldn't replace your regular expression object with the result of the Execute method.
Set RegEx = RegEx.Execute(prgName)    '<-- NEVER do this!

Re-using variables is a no-no, so don't do it.

A: .Execute returns a collection of Match objects. This collection has a .Count but no .Value property. You can use MsgBox RegEx(0).Value to get the .Value of the first match.
Evidence:
>> sInp = "XXXProgramYYYVariantZZZ"
>> Set r = New RegExp
>> r.Pattern = "Program(.*?)Variant"
>> WScript.Echo r.Execute(sInp)(0).Value
>> WScript.Echo r.Execute(sInp)(0).SubMatches(0)
>>
ProgramYYYVariant
YYY

You should publish your input(s) and expected result(s).


text:
Q: Where is binary search used in practice? Every programmer is taught that binary search is a good, fast way to search an ordered list of data. There are many toy textbook examples of using binary search, but what about in real programming: where is binary search actually used in real-life programs?

A: Binary search is a good and fast way!
Before the arrival of STL and .NET framework, etc, you rather often could bump into situations where you needed to roll your own customized collection classes. Whenever a sorted array would be a feasible place of storing the data, binary search would be the way of locating entries in that array.
I'm quite sure binary search is in widespread use today as well, although it is taken care of "under the hood" by the library for your convenience.

A: I've implemented binary searches in BTree implementations.
The BTree search algorithms were used for finding the next node block to read but, within the 4K block itself (which contained a number of keys based on the key size), binary search was used for find either the record number (for a leaf node) or the next block (for a non-leaf node).
Blindingly fast compared to sequential search since, like balanced binary trees, you remove half the remaining search space with every check.

A: I once implemented it (without even knowing that this was indeed binary search) for a GUI control showing two-dimensional data in a graph. Clicking with the mouse should set the data cursor to the point with the closest x value. When dealing with large numbers of points (several 1000, this was way back when x86 was only beginning to get over 100 MHz CPU frequency) this was not really usable interactively - I was doing a linear search from the start. After some thinking it occurred to me that I could approach this in a divide and conquer fashion. Took me some time to get it working under all edge cases.
It was only some time later that I learned that this is indeed a fundamental CS algorithm...

A: One example is the stl set.  The underlying data structure is a balanced binary search tree which supports look-up, insertion, and deletion in O(log n) due to binary search.
Another example is an integer division algorithm that runs in log time.

A: We still use it heavily in our code to search thousands of ACLS many thousands of times a second.  It's useful because the ACLs are static once they come in from file, and we can suffer the expense of growing the array as we add to it at bootup.  Blazingly fast once its running too.
When you can search a 255 element array in at most 7 compare/jumps (511 in 8, 1023 in 9, etc) you can see that binary search is about as fast as you can get.

A: Well, binary search is now used in 99% of 3D games and applications. Space is divided into a tree structure and a binary search is used to retrieve which subdivisions to display according to a 3D position and camera.
One of its first greatest showcase was Doom. Binary trees and associated search enhanced the rendering.

A: Answering your question with hands-on example.
In R programming language there is a package data.table. It is known from C-implemented, short syntax, high performance extension for data transformation. It uses binary search. Even without binary search it scales better than competitors.
You can find benchmark vs python pandas and vs R dplyr in project wiki grouping 2E9 - random order data.
There is also nice benchmark vs databases vs bigdata benchm-databases.
In recent data.table version (1.9.6) binary search was extended and now can be used as index on any atomic column.
I just found a nice summary with which I totally agree - see.

Anyone doing R comparisons should use data.table instead of data.frame. More so for benchmarks. data.table is the best data structure/query language I have found in my career. It's leading the way in The R world, and in my way, in all the data-focused languages.

So yes, binary search is being used and world is much better place thanks to it.

A: Binary search is used everywhere. Take any sorted collection from any language library (Java, .NET, C++ STL and so on) and they all will use (or have the option to use) binary search to find values. While true that you have to implement it rarely, you still have to understand the principles behind it to take advantage of it.

A: Binary search can be used to access ordered data quickly when memory space is tight. Suppose you want to store a set of 100.000 32-bit integers in a searchable, ordered data structure but you are not going to change the set often. You can trivially store the integers in a sorted array of 400.000 bytes, and you can use binary search to access it fast. But if you put them e.g. into a B-tree, RB-tree or whatever "more dynamic" data structure, you start to incur memory overhead. To illustrate, storing the integers in any kind of tree where you have left child and right child pointers would make you consume at least 1.200.000 bytes of memory (assuming 32-bit memory architecture). Sure, there are optimizations you can do, but that's how it works in general.
Because it is very slow to update an ordered array (doing insertions or deletions), binary search is not useful when the array changes often.
Here some practical examples where I have used binary search:

*

*Implementing a "switch() ... case:" construct in a virtual machine where the case labels are individual integers. If you have 100 cases, you can find the correct entry in 6 to 7 steps using binary search, where as sequence of conditional branches takes on average 50 comparisons.

*Doing fast substring lookup using suffix arrays, which contain all the suffixes of the set of searchable strings in lexiographic ordering (I wanted to conserve memory and keep the implementation simple)

*Finding numerical solutions to an equation (when you are lazy and do not mind to implement Newton's method)

A: Binary search can be used to debug with Git. It's called git bisect.

A: Every programmer needs to know how to use binary search when debugging.
When you have a program, and you know that a bug is visible at a particular point
during the execution of the program, you can use binary search to pin-point the
place where it actually happens. This can be much faster than single-stepping through
large parts of the code.

A: Amongst other places, I have an interpreter with a table of command names and a pointer to the function to interpret that command.  There are about 60 commands.  It would not be incredibly onerous to use a linear search - but I use a binary search.

A: Semiconductor test programs used for measuring digital timing or analog levels make extensive use of binary search. Automatic Test Equipment (ATE) from Advantest, Teradyne, Verigy and the like can be thought of as truth table blasters, applying input logic and verifying output states of a digital part.
Think of a simple gate, with the input logic changing at time = 0 of each cycle, and transitioning X ns after the  input logic changes. If you strobe the output before T=X,the logic does not match expected value. Strobe later than time T=X, and the logic does match expected value. Binary search is used to find the threshold between the latest value that  the logic does not match, and the earliest part where it does.(A Teradyne FLEX system resolves timing to 39pS resolution, other testers are comparable). That's a simple way to measure transition time. Same technique can be used to solve for setup time, hold time, operable power supply levels, power supply vs. delay,etc.
Any kind of microprocessor, memory, FPGA, logic, and many analog mixed signal circuits use binary search in test and characterization.
-- mike

A: I had a program that iterated through a collection to perform some calculations.  I thought that this was inefficient so I sorted the collection and then used a single binary search to find an item of interest.  I returned this item and its matching neighbours.  I had in-effect filtered the collection.
Doing this was actually slower than iterating the entire collection and fishing out matching items.
I continued to add items to the collection knowing that the sorting and searching performance would eventually catch up with the iteration.  It took a collection of about 600 objects until the speed was identical.  1000 objects had a clear performance benefit.
I would also consider the type of data you are working with, the duplicates and spread.  This will have an effect on the sorting and searching.
My answer is to try both methods and time them.

A: It's the basis for hg bisect

A: Binary sort is useful in adjusting fonts to size of text with constant dimension of textbox

A: Finding roots of an equation is probably one of those very easy things you want to do with a very easy algorithm like binary search.

A: Delphi uses can enjoy binary search while searching string in sorted TStringList.

A: I believe that the .NET SortedDictionary uses a binary tree behind the scenes (much like the STL map)... so a binary search is used to access elements in the SortedDictionary

A: Python'slist.sort() method uses Timsort which (AFAIK) uses binary search to locate the positions of elements.

A: Binary search offers a feature that many readymade map/dictionary implementations don't: finding non-exact matches.
For example, I've used binary search to implement geotagging of photos based on GPS logs: put all GPS waypoints in an array sorted by timestamp, and use binary search to identify the waypoint that lies closest in time to each photo's timestamp.

A: If you have a set of elements to find in an array you can either search for each of them linearly or sort the array and then use binary search with the same comparison predicate. The latter is much faster.


text:
Q: android : roundedImageView with VectorDrawables I am getting error while setting Vector Drawables to RoundedImageView. I am clear with error I am getting, its because I am trying to cast a drawable to BitmapDrawable but it should be VectorDrawable (If I am not wrong), So can anyone suggest me the way to handle any type of images whether it is jpg, png or vector.
RoundedImageView.java:
public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
    }

    public RoundedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap(); // line no 43
        Bitmap bitmap = b.copy(Config.ARGB_8888, true);

        int w = getWidth(), h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;
        if (bmp.getWidth() != radius || bmp.getHeight() != radius)
            sbmp = Bitmap.createScaledBitmap(bmp, radius, radius, false);
        else
            sbmp = bmp;
        Bitmap output = Bitmap.createBitmap(sbmp.getWidth(), sbmp.getHeight(),
                Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xffa19774;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, sbmp.getWidth(), sbmp.getHeight());

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor("#BAB399"));
        canvas.drawCircle(sbmp.getWidth() / 2 + 0.7f,
                sbmp.getHeight() / 2 + 0.7f, sbmp.getWidth() / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

My Error Log:
01-05 16:12:55.474 29943-29943/com.knowaguy.app E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.knowaguy.app, PID: 29943
                                                                    java.lang.ClassCastException: android.graphics.drawable.VectorDrawable cannot be cast to android.graphics.drawable.BitmapDrawable
at com.knowaguy.app.customViews.RoundedImageView.onDraw(RoundedImageView.java:43)
at android.view.View.draw(View.java:16178)
at android.view.View.updateDisplayListIfDirty(View.java:15174)
at android.view.View.draw(View.java:15948)
at android.view.ViewGroup.drawChild(ViewGroup.java:3609)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3399)
at android.view.View.draw(View.java:16181)
at android.view.View.updateDisplayListIfDirty(View.java:15174)
at android.view.View.draw(View.java:15948)
at android.view.ViewGroup.drawChild(ViewGroup.java:3609)
at android.support.v7.widget.RecyclerView.drawChild(RecyclerView.java:3588)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3399)
at android.view.View.draw(View.java:16181)
at android.support.v7.widget.RecyclerView.draw(RecyclerView.java:3097)
at android.view.View.updateDisplayListIfDirty(View.java:15174)
at android.view.View.draw(View.java:15948)
at android.view.ViewGroup.drawChild(ViewGroup.java:3609)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3399)
at android.view.View.updateDisplayListIfDirty(View.java:15169)
at android.view.View.draw(View.java:15948)
at android.view.ViewGroup.drawChild(ViewGroup.java:3609)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3399)
at android.view.View.updateDisplayListIfDirty(View.java:15169)
at android.view.View.draw(View.java:15948)
at android.view.ViewGroup.drawChild(ViewGroup.java:3609)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3399)
at android.view.View.updateDisplayListIfDirty(View.java:15169)
at android.view.View.draw(View.java:15948)
at android.view.ViewGroup.drawChild(ViewGroup.java:3609)
at android.support.v4.widget.DrawerLayout.drawChild(DrawerLayout.java:1229)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3399)
at android.view.View.draw(View.java:16181)
at android.view.View.updateDisplayListIfDirty(View.java:15174)
at android.view.View.draw(View.java:15948)
at android.view.ViewGroup.drawChild(ViewGroup.java:3609)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3399)
at android.view.View.updateDisplayListIfDirty(View.java:15169)
at android.view.View.draw(View.java:15948)
at android.view.ViewGroup.drawChild(ViewGroup.java:3609)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3399)
at android.view.View.updateDisplayListIfDirty(View.java:15169)
at android.view.View.draw(View.java:15948)
at android.view.ViewGroup.drawChild(ViewGroup.java:3609)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3399)
at android.view.View.updateDisplayListIfDirty(View.java:15169)
at android.view.View.draw(View.java:15948)
at android.view.ViewGroup.drawChild(ViewGroup.java:3609)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3399)
at android.view.View.updateDisplayListIfDirty(View.java:15169)
at android.view.View.draw(View.java:15948)
at android.view.ViewGroup.drawChild(ViewGroup.java:3609)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3399)
at android.view.View.draw(View.java:16181)
at com.android.internal.policy.PhoneWindow$DecorView.draw(PhoneWindow.java:2690)
at android.view.View.updateDisplayListIfDirty(View.java:15174)
at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:281)
at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:287)
at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:322)
at android.view.ViewRootImpl.draw(ViewRootImpl.java:2615)
at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2434)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2067)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Chore

A: There may be an alternate approach too but I am not sure it will be efficient, You can convert your VectorDrawable to Bitmap since the method getBitmapDrawable() on a non instance of BitmapDrwable will throw exception( as you see in your case).
Use the following method to obtain a bitmap from drawable -
private Bitmap getBitmap(int drawableId) {
    Drawable vectorDrawable;
    if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.LOLLIPOP){
        vectorDrawable = getResources().getDrawable(drawableId,null);
    }else {
        vectorDrawable = getResources().getDrawable(drawableId);
    }
    int h = vectorDrawable.getIntrinsicHeight();
    int w = vectorDrawable.getIntrinsicWidth();

    //Setting a default height in pixel if intrinsinc height or width is not found , eg in case of a shape drawable
    h=h>0?h:96;
    w=w>0?w:96;

    vectorDrawable.setBounds(0, 0, w, h);
    Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bm);
    vectorDrawable.draw(canvas);
    return bm;
}

A: I'm posting this answer, which I found elsewhere on stackoverflow, in order to show Sanjeet an alternate solution that I mentioned. Because the min API is so high this way, I don't claim that it is the best solution.
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private Bitmap _getBitmap(Context c, int svg_id) {
    Drawable drawable = ContextCompat.getDrawable(c, svg_id);
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable) drawable).getBitmap();
    } else if (drawable instanceof VectorDrawable) {
        return _getBitmap((VectorDrawable) drawable);
    } else {
        throw new IllegalArgumentException("unsupported drawable type");
    }
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static Bitmap _getBitmap(VectorDrawable vectorDrawable) {
    Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
            vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    vectorDrawable.draw(canvas);
    return bitmap;
}


text:
Q: VS Code Python debugger would not start with Python extension 2022.Xx.xx although latest 2021 (2021.12.1559732655) works. Starting regular run works When starting a python script in debug mode from VS code nothing happens. I do not see any command being lunched in terminal.
If I start the script without debugging it starts fine.
I read on another thread somewhere that choosing an older Python extension like 2021.12.1559732655 would fix it and indeed it does but I would like to use the latest version of Python extension.
Anyone has any idea what broke in the new extensions starting with 2022.. basically anything with 2022 will not do anything when attempting to start the script in debug.
I am running remotely from a windows using ssh on a centos7 with python 2.7 and python 3.6. Not sure if that matters.
I tried starting python scripts from Visual Studio code in debug mode
VS code does  not do anything.
Tried modifying the config , restart , switching back to python 2.7 without  result..
The only thing that works is reverting to a version pre 2022

A: Seems that I got my answer on ghithub. The debugger will not work with versions lower than Python 3.7.
For anything other than Python 3.7+ (like Python 2.6 )  use the 2021.12 version of the vs code  python extension.
https://github.com/microsoft/vscode-python/issues/19559#issuecomment-1358494296


text:
Q: How to send Server Region in Embed Discord JS v13? I have a Server Info command which worked in v12 but I updated to v13. In v12 when I send the Command it Responds with the correct region but in v13 when I send the command, responds at server region with undefined, help!
This is server info command:
const Discord = require('discord.js');

module.exports = {
    name: "serverinfo",
    aliases: ["si"],
    description: "Shows all Info about the Server!",
    execute: async (message, args, client) => {

        let region;
        switch (message.guild.region) {
            case "europe":
                region = ' europe';
                break;
            case "russia":
                region = ' russia';
                break;
            case "us-east":
                region = ' us-east'
                break;
            case "us-west":
                region = ' us-west';
                break;
            case "us-south":
                region = ' us-south'
                break;
            case "us-central":
                region = ' us-central'
                break;
        }

        const embed = new Discord.MessageEmbed()
            .setThumbnail(message.guild.iconURL({dynamic : true}))
            .setColor('#dd6fb9')
            .setTitle(`**Bot Command**`)
            .setFooter("@" + message.author.tag, message.author.displayAvatarURL({dynamic : true}))
            .addFields(

                {
                    name: `Region: `,
                    value: `${region}`,
                    inline: true
                }

        await message.channel.send( { embeds: [embed] }).then(setTimeout(() => message.delete())).then(msg =>{
            setTimeout(() => msg.delete(), 120000)});
    },
};

A: A guild no longer has the attribute region. You can however get the preferredLocale of the server:
const Discord = require('discord.js');

module.exports = {
    name: "serverinfo",
    aliases: ["si"],
    description: "Shows all Info about the Server!",
    execute: async (message, args, client) => {

        const embed = new Discord.MessageEmbed()
            .setThumbnail(message.guild.iconURL({dynamic : true}))
            .setColor('#dd6fb9')
            .setTitle(`**Bot Command**`)
            .setFooter("@" + message.author.tag, message.author.displayAvatarURL({dynamic : true}))
            .addFields(

                {
                    name: `Region: `,
                    value: `${message.guild.preferredLocale}`,
                    inline: true
                }

        await message.channel.send( { embeds: [embed] }).then(setTimeout(() => message.delete())).then(msg =>{
            setTimeout(() => msg.delete(), 120000)});
    },
};


text:
Q: How exactly do I use Assetic's Twig extension? I'm (trying to) use Assetic with Twig and Slim (so, without Symfony).  I think I've figured out the basics of creating an AssetCollection, but I'm not really clear how to link this collection in my templates.
$fm = new FilterManager();

$factory = new AssetFactory('');
$factory->setDebug(true);
$factory->setFilterManager($fm);

$app->css = $factory->createAsset([
    'assets://css/bootstrap-3.3.1.css',
    'assets://css/bootstrap-custom.css',
    'assets://css/paper.css'
], [
    // Filters here
]);

If I do something like echo $app->css->dump();, it correctly prints out all my CSS.  Great, but how do I hook this into Twig?
The example given in the project README leaves me with more questions than I started with:
{% stylesheets '/path/to/sass/main.sass' filter='sass,?yui_css' output='css/all.css' %}
    <link href="{{ asset_url }}" type="text/css" rel="stylesheet" />
{% endstylesheets %}

What the heck is /path/to/sass/main.sass?  I thought I was declaring my assets via $factory->createAsset.  The documentation goes on to say:

When the extension is in debug mode, this same tag will render multiple link elements, one for each asset referenced by the css/src/*.sass glob...

I don't see anything about css/src/*.sass anywhere else in the README.  What are they talking about?
Finally, I see this at the bottom of the README:
<?php

use Assetic\AssetWriter;
use Assetic\Extension\Twig\TwigFormulaLoader;
use Assetic\Extension\Twig\TwigResource;
use Assetic\Factory\LazyAssetManager;

$am = new LazyAssetManager($factory);

// enable loading assets from twig templates
$am->setLoader('twig', new TwigFormulaLoader($twig));

// loop through all your templates
foreach ($templates as $template) {
    $resource = new TwigResource($twigLoader, $template);
    $am->addResource($resource, 'twig');
}

$writer = new AssetWriter('/path/to/web');
$writer->writeManagerAssets($am);

This seems to me like something I would run once in a build step ("looping through all my templates").  But, I thought Assetic also would support on-demand filtering (and caching) of assets.  I obviously don't want to loop through all my templates on every request.  Shouldn't the relevant calls to writeManagerAssets be automatically triggered by the Twig extension?
Any help would be greatly appreciated.


text:
Q: allready have search filter table js code - works fine, simply would like to have highlighed text result. any ideas anyone? HTML
<input id="myInput" type="text" onkeyup="ContactsearchFX()"
       placeholder="Search Titles">
    *

JAVASCRIPT
window.onload = function() {
   var rows = document.querySelectorAll('tr');

   for (var i = 0; i < rows.length; i++) {
     rows[i].style.display = 'none';
   }
}

function ContactsearchFX() {
  var input, filter, table, tr, td, i;

  input = document.getElementById("myInput");

  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i
 -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";

      }
    }
  }

   var rows = document.querySelectorAll('tr');

   if (input.value.length == 0) {
    for (var i = 0; i < rows.length; i++) {
      rows[i].style.display = 'none';
    }
  }
}

Have trawled the web with no result. New to js so any help would be very appreciated.
Is the a simple way of adding a few lines of code?
Would be great.

A: I guess what would be great is if just the actual text match in a specified column but on all the rows of that column.
If that makes any sense.


text:
Q: Configure mockito to print actual argument values in verification error messages When describing failed verification, by default Mockito prints only call sites where interactions happened. Like this:
    Wanted but not invoked:
    proxyListener.foundTemplateParam(
        "fooBar2",
        isNull(),
        isNull()
    );
    -> at        foo.ProxyHandlerTest.testThatImplicitParamsScannedCorrectly(ProxyHandlerTest.java:136)

    However, there were other interactions with this mock:
    -> at foo.ProxyHandler.<init>(ProxyHandler.java:99)
    -> at foo.ProxyHandler.<init>        (ProxyHandler.java:100)
    -> at foo.ProxyHandler.scanForParamSetters(ProxyHandler.java:222)
    -> at foo.ProxyHandler.<init>(ProxyHandler.java:102)
    -> at foo.ProxyHandler.<init>(ProxyHandler.java:104)

That's useful information but I would also like to see what arguments where passed during those interactions. Is there a way to achieve this?
P. S. I know about mocking with withSettings().verboseLogging(). But it's too verbose and is printed to stdout instead of adding this info to assertion error message.
Update:
Mockito 1.9.0 doesn't support customization of exception error messages out of the box (I just checked their sources).

A: the safest place to do that is an answer that prints arguments and return the given value.
You could then write something like :
given(some.callWith(arg1, arg2)).will(printArgsAndReturn("some value"));

where printArgsAndReturn("some value") actually returns your custom answer.


text:
Q: FTP UPLOADS CONFIGURATIONS Warning: ftp_put(): Can't open that file: Is a directory in * on line 183
Warning: ftp_put(): Can't open that file: Is a directory in * on line 185
183 line: if (ftp_put($ftp_conn_id, "/".$dir . "/$nameimage/", $ftp_temp_img, FTP_BINARY)) {
185 line: if (ftp_put($ftp_conn_id, "/".$dirthumb . "/$nameimage/", $ftp_temp_thumb, FTP_BINARY)) {
Who could it be bad? How would it be possible to correct the work?

A: change
 if (ftp_put($ftp_conn_id, "/".$dir . "/$nameimage/", $ftp_temp_img, FTP_BINARY)) {

Into
 if (ftp_put($ftp_conn_id, "/".$dir . "/$nameimage", $ftp_temp_img, FTP_BINARY)) {


text:
Q: How do I redirect to different page depending on the HOSTNAME .htacces with a Rewrite Condition/Rule I have a site: www.asdf.com and an alias of www.fdsa.com
How can I check the HOSTNAME in the .htaccess and redirect them to different pages?
I know it's something along the lines of this:
RewriteRule (%{HTTP_HOST})^(.*)$ http://www.gunslot.com/$2 [L,R=301]

Basically how do I do an equivalent of this in the .htaccess (pseudo code)
if(hostname == "asdf") redirect to asdf.com/hello.html
if(hostname == "fdsa") redirect to asdf.com/goodbye.html

A: Not 100% clear what your trying to achieve but this answer's what you have asked.
.htaccess
RewriteCond %{HTTP_HOST} ^asdf\.com
RewriteRule ^(.*)$ http://asdf.com/hello.html [NC,L]

RewriteCond %{HTTP_HOST} ^fdsa\.com
RewriteRule ^(.*)$ http://asdf.com/goodbye.htm [NC,L]

A: If you want to redirect any request to asdf domain to hello.html on asdf, and any request to fdsa to goodbye.html add the following to your .htaccess file in the root of your domain.
RewriteEngine On
RewriteBase /
#Redirect any asdf domain or subdomain
RewriteCond %{HTTP_HOST} ^(.+\.)?asdf\.com$ [NC]
RewriteCond %{REQUEST_URI} !^/(hello|goodbye)\.html$ [NC]
RewriteRule . http://asdf.com/hello.html [L,R]

#Redirect any fdsa domain or subdomain
RewriteCond %{HTTP_HOST} ^(.+\.)?fdsa\.com$ [NC]
RewriteRule . http://asdf.com/goodbye.htm [L,R]


text:
Q: ValueError: could not convert string to float: −0,5063291139 This is part of large csv file ( I show you only first column):
0
0
0
−0,5063291139
0,5063291139
0
0
0,6666666667

I am getting only data from first column. When I am trying to covert these to float:
with open("GOLD.csv") as f:
    reader = csv.reader(f ,delimiter=",")
    for row in reader:
        print float(row[0])

I get:
ValueError: could not convert string to float: −0,5063291139

Where is the problem?

A: Use . instead of , in the numbers. Change the line into
print float(str_replace(",",".",row[0]))

or what you like best to change the comma into a dot.


text:
Q: Problem with successive async functions in Angular getEnrolledPlayers should fetch an array of 'player' objects from the database and then pass it to the matchMaking function. However, it doesn't get passed correctly.
I tried adding observables, playing around with subscriptions
initializeEvent(eventId: string) {
  const enrolledPlayers: PlayerStat[] = [];
  this.getEnrolledPlayers(eventId)
    .subscribe((playerIds: string[]) => {
      for (const playerId of playerIds) {
        this.dataService.fetchSinglePlayer(playerId)
          .subscribe((playerStat: PlayerStat) => enrolledPlayers.push(playerStat));
      }
      this.matchMaking(enrolledPlayers);
    });
}

When I call these series of asynchronous functions, enrolledPlayers[] is calculated correctly (array of 7 elements), but it doesn't get called to the matchMaking() function correctly. I assume it's because of asynchronous runtime.

A: Yes. It's definitely an issue caused because of the time difference in which the inner subscription resolves a value.
I'd suggest using a forkJoin and waiting on getting all the values resolved before calling matchMaking.
Give this a try:
initializeEvent(eventId: string) {
  const enrolledPlayers: PlayerStat[] = [];
  this.getEnrolledPlayers(eventId)
    .subscribe((playerIds: string[]) => {
      const playerInfos$ = playerIds.map(playerId => this.dataService.fetchSinglePlayer(playerId));
      forkJoin(...playerInfos$)
        .subscribe(enrolledPlayers: PlayerStat[] => this.matchMaking(enrolledPlayers));
    });
}

Or with one subscribe
initializeEvent(eventId: string) {
  const enrolledPlayers: PlayerStat[] = [];
  this.getEnrolledPlayers(eventId)
    .take(1)
    .switchMap((playerIds: string[]) => {
      const playerInfos$ = playerIds.map(playerId => this.dataService.fetchSinglePlayer(playerId).take(1));
      return forkJoin(...playerInfos$);
    })
   .tap(this.matchMaking)
    .subscribe();
}

A: this is a nested subscribe anti pattern... you never nest subscribes, this is how it should look using higher order operators:
initializeEvent(eventId: string) {
  this.getEnrolledPlayers(eventId)
    .pipe(
      switchMap(playerIds =>
         forkJoin(playerIds.map(playerId => this.dataService.fetchSinglePlayer(playerId)))
      )
    ).subscribe((enrolledPlayers) =>
      this.matchMaking(enrolledPlayers)
    );
}

use switchMap to switch into a new observable and then forkJoin to run many observables in parrallel


text:
Q: Paypal adaptive payment not showing shipping cost Is there a way to show shipping cost once user is redirected to paypal?
I tried with setPaymentOption but no help.
Here is my code-
This function is generating the payKey
function process_payment($JobId,$company_email,$file_id,$printer_id,$cost){
    require('/includes/assets/paypal_config/config.php');
    require('admin/config/rs_server.php');

  //  $secondryReceiverQuery = "UPDATE 3d_job_info set pay_key = '".$PayPalResult['PayKey']."'  WHERE job_id ='$JobId'";

  //  $jobInsertQrrRes = mysqli_query($DB_CONN,$jobInsertQrr);
 //  $cost =$cost+10;
$primary_amt = ((12/100)*$cost) ;
$secondary_amt = $cost - $primary_amt;

// Create PayPal object.
       $PayPalConfig = array(
           'Sandbox' => $sandbox,
           'DeveloperAccountEmail' => $developer_account_email,
           'ApplicationID' => $application_id,
           'DeviceID' => $device_id,
           'IPAddress' => $_SERVER['REMOTE_ADDR'],
           'APIUsername' => $api_username,
           'APIPassword' => $api_password,
           'APISignature' => $api_signature,
           'APISubject' => $api_subject,
           'PrintHeaders' => $print_headers,
           'LogResults' => $log_results,
           'LogPath' => $log_path,
       );

       $PayPal = new  Adaptive($PayPalConfig);

       // Prepare request arrays
       $PayRequestFields = array(
           'ActionType' => 'PAY_PRIMARY', // Required.  Whether the request pays the receiver or whether the request is set up to create a payment request, but not fulfill the payment until the ExecutePayment is called.  Values are:  PAY, CREATE, PAY_PRIMARY
           'CancelURL' => $domain."index.php?t=cancel_payment&jobid=$JobId",// Required.  The URL to which the sender's browser is redirected if the sender cancels the approval for the payment after logging in to paypal.com.  1024 char max.
           'CurrencyCode' => 'USD', // Required.  3 character currency code.
           'FeesPayer' => 'PRIMARYRECEIVER',// The payer of the fees.lol  Values are:  SENDER, PRIMARYRECEIVER, EACHRECEIVER, SECONDARYONLY
           'IPNNotificationURL' => '', // The URL to which you want all IPN messages for this payment to be sent.  1024 char max.
           'Memo' => 'This transection is from localhost', // A note associated with the payment (text, not HTML).  1000 char max
           'Pin' => '', // The sener's personal id number, which was specified when the sender signed up for the preapproval
           'PreapprovalKey' => '',// The key associated with a preapproval for this payment.  The preapproval is required if this is a preapproved payment.
           'ReturnURL' => $domain."index.php?t=payment_success&jobid=$JobId", // Required.  The URL to which the sener"s browser is redirected after approvaing a payment on paypal.com.  1024 char max.
           'ReverseAllParallelPaymentsOnError' => '',// Whether to reverse paralel payments if an error occurs with a payment.  Values are:  TRUE, FALSE
           'SenderEmail' => '',// Sender's email address.  127 char max.
           'TrackingID' => '',// Unique ID that you specify to track the payment.  127 char max.
       );

       $ClientDetailsFields = array(
           'CustomerID' => '45', // Your ID for the sender  127 char max.
           'CustomerType' => 'type', // Your ID of the type of customer.  127 char max.
           'GeoLocation' => '',// Sender's geographic location
           'Model' => 'zxc', // A sub-identification of the application.  127 char max.
           'PartnerName' => 'zxc'   // Your organization's name or ID
       );

       $FundingTypes = array('ECHECK', 'BALANCE', 'CREDITCARD');// Funding constrainigs require advanced permissions levels.

       $Receivers = array();
       $Receiver = array(
           'Amount' =>$cost,// Required.  Amount to be paid to the receiver.
           'Email' => 'payment@creiterate.com', // Receiver's email address. 127 char max.
           'InvoiceID' => '', // The invoice number for the payment.  127 char max.
           'PaymentType' => 'GOODS', // Transaction type.  Values are:  GOODS, SERVICE, PERSONAL, CASHADVANCE, DIGITALGOODS
           'PaymentSubType' => '', // The transaction subtype for the payment.
           'AccountID' => '',
           'Phone' => array('CountryCode' => '', 'PhoneNumber' => '', 'Extension' => ''), // Receiver's phone number.   Numbers only.
           'Primary' => 'true'  // Whether this receiver is the primary receiver.  Values are boolean:  TRUE, FALSE
       );
       array_push($Receivers,$Receiver);

       $Receiver = array(
           'Amount' => $secondary_amt,// Required.  Amount to be paid to the receiver.
           'Email' => $company_email,                                               // Receiver's email address. 127 char max.
           'InvoiceID' => '',// The invoice number for the payment.  127 char max.
           'PaymentType' => '',// Transaction type.  Values are:  GOODS, SERVICE, PERSONAL, CASHADVANCE, DIGITALGOODS
           'PaymentSubType' => '',// The transaction subtype for the payment.
           'AccountID' => '',
           'Phone' => array('CountryCode' => '', 'PhoneNumber' => '', 'Extension' => ''), // Receiver's phone number.   Numbers only.
           'Primary' => 'false'// Whether this receiver is the primary receiver.  Values are boolean:  TRUE, FALSE
       );
      array_push($Receivers,$Receiver);

       $SenderIdentifierFields = array(
          'UseCredentials' => TRUE// If TRUE, use credentials to identify the sender.  Default is false.
       );

       $AccountIdentifierFields = array(
           'Email' => $_SESSION['loggin_info']['email_address'],// Sender's email address.  127 char max.
           'Phone' => array('CountryCode' => '', 'PhoneNumber' => '', 'Extension' => '')// Sender's phone number.  Numbers only.
       );

       $PayPalRequestData = array(
           'PayRequestFields' => $PayRequestFields,
           'ClientDetailsFields' => $ClientDetailsFields,
        //  'CreateInvoiceFields' => $CreateInvoiceFields,
           //'FundingTypes' => $FundingTypes,
           'Receivers' => $Receivers,
           'SenderIdentifierFields' => $SenderIdentifierFields,
           'AccountIdentifierFields' => $AccountIdentifierFields
       );

       // Pass data into class for processing with PayPal and load the response array into $PayPalResult
       $PayPalResult = $PayPal->Pay($PayPalRequestData);

//Before redirecting setting the pay option here
 setPaymentOption($PayPalResult['PayKey'],$PayPal,$cost);
    header("Location: ". $PayPalResult['RedirectURL']);

}

This is my set payment option function.
function setPaymentOption($PayKey,$PayPal,$cost){
require('/../assets/paypal_config/config.php');
require('/admin/config/rs_server.php');
// Create PayPal object.
$PayPalConfig = array(
    'Sandbox' => $sandbox,
    'DeveloperAccountEmail' => $developer_account_email,
    'ApplicationID' => $application_id,
    'DeviceID' => $device_id,
    'IPAddress' => $_SERVER['REMOTE_ADDR'],
    'APIUsername' => $api_username,
    'APIPassword' => $api_password,
    'APISignature' => $api_signature,
    'APISubject' => $api_subject,
    'PrintHeaders' => $print_headers,
    'LogResults' => $log_results,
    'LogPath' => $log_path,
    );

   //  $PayPal = new  Adaptive($PayPalConfig);

// Prepare request arrays
$SPOFields = array(
    'PayKey' => $PayKey,                            // Required.  The pay key that identifies the payment for which you want to set payment options.
    'ShippingAddressID' => ''                   // Sender's shipping address ID.
    );

$DisplayOptions = array(
'EmailHeaderImageURL' => '',            // The URL of the image that displays in the header of customer emails.  1,024 char max.  Image dimensions:  43 x 240
'EmailMarketingImageURL' => 'http://www.angelleye.com/images/email_marketing_image.jpg',        // The URL of the image that displays in the customer emails.  1,024 char max.  Image dimensions:  80 x 530
'HeaderImageURL' => 'http://www.angelleye.com/header_image.jpg',                // The URL of the image that displays in the header of a payment page.  1,024 char max.  Image dimensions:  750 x 90
'BusinessName' => 'Test business'                   // The business name to display.  128 char max.
);

$InstitutionCustomer = array(
'CountryCode' => 'US',              // Required.  2 char code of the home country of the end user.
'DisplayName' => 'Tester Testerson',                // Required.  The full name of the consumer as known by the institution.  200 char max.
'InstitutionCustomerEmail' => 'payment@creiterate.com ',    // The email address of the consumer.  127 char max.
'FirstName' => 'Tester',                    // Required.  The first name of the consumer.  64 char max.
'LastName' => 'Testerson',                  // Required.  The last name of the consumer.  64 char max.
'InstitutionCustomerID' => '12345',         // Required.  The unique ID assigned to the consumer by the institution.  64 char max.
'InstitutionID' => '6V8R7B4KPS22E'              // Required.  The unique ID assigned to the institution.  64 char max.
);

$SenderOptions = array(
    'RequireShippingAddressSelection' => '' // Boolean.  If true, require the sender to select a shipping address during the embedded payment flow.  Default is false.
  );

// Begin loop to populate receiver options.
$ReceiverOptions = array();
$ReceiverOption = array(
        'Description' => 'Test Hello',                  // A description you want to associate with the payment.  1000 char max.
        'CustomID' => ''                        // An external reference number you want to associate with the payment.  1000 char max.
);
 $cost =$cost-10;
$InvoiceData = array(
        'TotalTax' => '',                           // Total tax associated with the payment.
        'TotalShipping' => '10'                         // Total shipping associated with the payment.
);

$InvoiceItems = array();
$InvoiceItem = array(
        'Name' => 'Widget ABC',                                 // Name of item.
        'Identifier' => '',                         // External reference to item or item ID.
        'Price' => $cost,                               // Total of line item.
        'ItemPrice' => $cost,                           // Price of an individual item.
        'ItemCount' => '1'                          // Item QTY
);
array_push($InvoiceItems,$InvoiceItem);

$PayPalRequestData = array(
                'SPOFields' => $SPOFields,
                'DisplayOptions' => $DisplayOptions,
                 'InstitutionCustomer' => $InstitutionCustomer,
                'SenderOptions' => $SenderOptions,
                'ReceiverOptions' => $ReceiverOptions
                );

// Pass data into class for processing with PayPal and load the response array into $PayPalResult
$PayPalResult = $PayPal->SetPaymentOptions($PayPalRequestData);

}


text:
Q: Return multiple values from 1 column I have a ResponseText column which contains the responses of users and another column called QuestionID which uniquely identifies each question. What I am working with is this:
|  QuestionID  |  ResponseText  |
---------------------------------
|      32      |     Billson    |  <- First Name
|      33      |     Thorn      |  <- Last Name
|      34      |   0422949333   |  <- Ph Number
|      35      |  bt@thorn.com  |  <- Email

I want to display the ResponseText in seperate columns depending on the QuestionID like this (QuestionID 33 will always be last name, etc):
|  FName   |  LName   |  Ph Number   |  Email      |
----------------------------------------------------
| Billson  |  Thorn   |  0422949333  | bt@thorn.com|

Right now, I have
SELECT dbo.ResponseInstance.ResponseText as 'FName'
FROM dbo.ResponseInstance
WHERE dbo.ResponseInstance.QuestionID = '32'
UNION
SELECT dbo.ResponseInstance.ResponseText as 'LName'
FROM dbo.ResponseInstance
WHERE dbo.ResponseInstance.QuestionID = '33'
UNION
SELECT dbo.ResponseInstance.ResponseText as 'Phone'
FROM dbo.ResponseInstance
WHERE dbo.ResponseInstance.QuestionID = '34'
UNION
SELECT dbo.ResponseInstance.ResponseText as 'Email'
FROM dbo.ResponseInstance
WHERE dbo.ResponseInstance.QuestionID = '35'

However this returns one column named FName. Is what I am trying to do even possible?

A: You can do this using a conditional aggregate:
SELECT
    FName = MAX(CASE WHEN QuestionID = 32 THEN ResponseText END),
    LName = MAX(CASE WHEN QuestionID = 33 THEN ResponseText END),
    [Ph Number] = MAX(CASE WHEN QuestionID = 34 THEN ResponseText END),
    Email = MAX(CASE WHEN QuestionID = 35 THEN ResponseText END)
FROM ResponseInstance

EDIT:
As per Eric's comment below, you need a column that identifies the person answering the question. For illustration purposes, let's say we have a PersonID column on ResponseInstance.
SAMPLE DATA
CREATE TABLE ResponseInstance(
    PersonID    INT,
    QuestionID  INT,
    ResponseText VARCHAR(50),
)
INSERT INTO ResponseInstance VALUES
(1, 32, 'Billson'),
(1, 33, 'Thorn'),
(1, 34, '0422949333'),
(1, 35, 'bt@thorn.com'),
(2, 32, 'John'),
(2, 33, 'Doe'),
(2, 34, '999999999'),
(2, 35, 'johndoe@email.com')

Again you can still use conditional aggregate but this time, you need to group them by PersonID.
SELECT
    PersonID,
    FName = MAX(CASE WHEN QuestionID = 32 THEN ResponseText END),
    LName = MAX(CASE WHEN QuestionID = 33 THEN ResponseText END),
    [Ph Number] = MAX(CASE WHEN QuestionID = 34 THEN ResponseText END),
    Email = MAX(CASE WHEN QuestionID = 35 THEN ResponseText END)
FROM ResponseInstance
GROUP BY PersonID

RESULT
PersonID    FName       LName       Ph Number       Email
--------- ------------ ----------- --------------- ----------------------
1           Billson     Thorn       0422949333      bt@thorn.com
2           John        Doe         999999999       johndoe@email.com


text:
Q: Link text doesn't disapear when hovered on I have a set of  boxes with background images on them and have centred with text in them. When you hover on the box the image zoom and animation is working as it should, but the text is only disappears when you hover directly on it not the box itself.
My Code

* {
  box-sizing: border-box;
}

body {
  background-color: rgb(236, 237, 229);
}

.wrapper {
  max-width: 960px;
  padding: 50px 50px;
  max-width: 1200px;
  text-align: center;
  margin: 40px auto;
}

.parent {
  overflow: hidden;
  display: inline-block;
  cursor: pointer;
  width: 430px;
  height: 300px;
  margin: 0 20px 60px 20px;
}

.child {
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  transform: scale(1.2);
  width: 100%;
  height: 100%;
  transition: all .5s;
  display: flex;
}

.child a {
  font-size: 1.2rem;
  font-family: 'Open Sans', sans-serif;
  letter-spacing: .4em;
  overflow: hidden;
  cursor: pointer;
  text-decoration: none;
  text-transform: uppercase;
  margin: auto;
  color: #fff;
  border: 2px solid;
  text-shadow: 2px 4px 3px rgba(0, 0, 0, 0.6);
  padding: 5px;
  font-weight: 900;
}

.child a:hover {
  opacity: 0;
}

.child:hover {
  transform: scale(1);
}

      Boats

      Hats

      Coffee & flowers

      Crystals

I am new to programming and the only solution that I came to was to make .child a an inline-block element and then take the border off and apply the padding. However that looked messy and the text was displayed wrongly.

A: .child:hover a {
   opacity: 0;
}

If you want to text to disappear when you hover over the box, change your selector to .child:hover a. This selects any  tag within a .child element that is being hovered over.
Adjusted behavior.

A: You have to make
.child a:hover {
    opacity: 1;
}


text:
Q: Can someone please tell me why I am getting HTTP Status 406 from Spring Can someone please tell me why I am getting HTTP Status 406 from Spring?  I am trying to make spring return some json code and I am getting back a 406 status..
Here is my controller code:
@RequestMapping(value = "/", method = RequestMethod.GET)
@ResponseBody
public  User getDisplayDefault(ModelMap model) {
      return new User("user name", "userid");
}

now here is my javaconfig:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.xxxx.mvc.web"})
public class WebMVCConfiguration extends WebMvcConfigurerAdapter
{

    private static final Logger logger = LoggerFactory.getLogger(WebMVCConfiguration.class);

    @Bean
    public ViewResolver resolver()
    {
        UrlBasedViewResolver url = new UrlBasedViewResolver();
        url.setPrefix("/views/");
        url.setViewClass(JstlView.class);
        url.setSuffix(".jsp");
        return url;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        logger.debug("setting up resource handlers");
        registry.addResourceHandler("/resources/").addResourceLocations("/resources/**");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
    {
        logger.debug("configureDefaultServletHandling");
        configurer.enable();
    }

    @Bean
    public SimpleMappingExceptionResolver simpleMappingExceptionResolver()
    {
        SimpleMappingExceptionResolver b = new SimpleMappingExceptionResolver();

        Properties mappings = new Properties();
        mappings.put("org.springframework.web.servlet.PageNotFound", "p404");
        mappings.put("org.springframework.dao.DataAccessException", "dataAccessFailure");
        mappings.put("org.springframework.transaction.TransactionException", "dataAccessFailure");
        b.setExceptionMappings(mappings);
        return b;
    }
}

so I really don't understand why my json is not coming back

A: Do you have Jackson/Jackson2 libs on your classpath? If not Spring will create no message converters. From the docs:

*

*MappingJackson2HttpMessageConverter (or MappingJacksonHttpMessageConverter) converts to/from JSON — added if Jackson 2 (or Jackson) is present on the classpath.


text:
Q: How to sort array by highest number arraydata = [
     ["bob", 56],
     ["Jan", 12],
     ["Foo", -83]
]

I want o get the name and number by the highest number display.
output:
bob
56

I tried to print(max(arraydata))
But that did not work. Any suggestions?
i'm using python

A: You can just use a key in pythons' max:
max(arraydata, key=lambda x: x[1])
#['bob', 56]

Note that by feeding max the whole nested list, the first ordering criteria will be the first elements in the sublists, and hence ordering will be lexicographical.
Which is why bob comes first (also coincidentally):
max(arraydata)
# ['bob', 56]

This is explained with:
[ord(i[0]) for i in ["bob", "Jan", "Foo"]]
# [98, 74, 70]

A: If you just want the highest you can do:
max(arraydata, key=lambda x: x[1])
#['bob', 56]

If you need several of the top, you can sort as well:
sorted(arraydata, key=lambda x: x[1], reverse=True)
#[['bob', 56], ['Jan', 12], ['Foo', -83]]

A: yata answer is ok, but if you want to sort arraydata list by highest number, try this:
from operator import itemgetter
a.sort(key=itemgetter(1), reverse=True)
print(a[0])
#['bob', 56]

Always the highest number is on zero index if you use reverse True.


text:
Q: Ruby on Rails 5 - Duplicate "Delete" links This is the picture of my problem ---> Duplicate Delete Links Picture
I have a comment with two delete links.
This is the order of how I'm rendering the comment form and the comments from partials:

Comments

<%= render 'comments/form' %>
<%= render @recipe.comments %>

This is the code for _form.html.erb
<%= form_for([@recipe, @recipe.comments.build]) do |f| %>

<%= f.label 'Comment' %>
 <%= f.text_area :comment %>

<%= f.submit 'Post' %>

<% end %>

This is the code for _comment.html.erb

<%= comment.name %>

<%= comment.comment %>

     <%= link_to 'Delete', [comment.recipe, comment], method: :delete,
           data: { confirm: 'Are you sure want to delete this comment?' } %>

The first delete link have the extension: /recipes/10/comments/1 (1 is the comment id #)
Also, when I hover over the second delete link has the extension: /recipes/10/comment
The difference between is that the second delete link's extension doesn't have a comment id
I know that by switching the order of

Comments

    <%= render 'comments/form' %>
    <%= render @recipe.comments %>

to

Comments

    <%= render @recipe.comments %>
    <%= render 'comments/form' %>

would solve my problem, but I want the form to come before the comments.
EDIT:
The second delete link isn't actually a "second" delete link. It's a delete link for a null object. I still don't know how to get rid of it though.

A: Try this. Set an order to your comments. Like this:

Comments

<%= render 'comments/form' %>
<%= render @recipe.comments.order(created_at: :DESC) %>

That should fix your problem. I've had the same issue and it worked for me.

A: If you know for sure it's nil object, why don't you add a trigger. I mean we can check the object whether it's nil or not before rendering.


text:
Q: How can I replace com.sun.tools.javac.file.BaseFileObject? I'm trying to update a Java 7 project to Java 11, but I can't find a replacement for BaseFileObject
It's used in a scripting engine in a server for Aion, a MMORPG : https://github.com/AionGermany/aion-germany/blob/master/AL-Commons/src/com/aionemu/commons/scripting/impl/javacompiler/BinaryClass.java
If you want some example of the scripts used, they're all here : https://github.com/AionGermany/aion-germany/tree/master/AL-Game/data/scripts/system/handlers
Did Oracle put a neat replacement for it, or they just removed it entirely ?


text:
Q: Meteor Cordova Print plugin I am developing a Point of sale (POS) for my store. And I am developing a Meteor app that will connect to the POS receipt printer. But as you know you cant simply use window.print().
I read but didnt understand the Meteor documentation about this, and I have several questions about it. (https://guide.meteor.com/mobile.html#using-plugins)
I have installed the katzer/cordova-plugin-printer (https://github.com/katzer/cordova-plugin-printer). And know here comes the questions.
1.-  Once installed, I create a file outside the server and client folder and insert a statement such as

if (Meteor.isCordova) {
  console.log("Printed only in mobile Cordova apps");
}

and then do I simply add the following line?

    if (Meteor.isCordova) {
document.addEventListener('deviceready', function () {
    // cordova.plugins.printer is now available
}, false);
    }

2.- If this is correct, Do I create a Meteor Method in the server or in Meteor.isCordova? to call the following example.

var page = '
Hello Document
';

cordova.plugins.printer.print(page, 'Document.html');

3.- Should I use server side rendering to create the

var page = '
Hello Document
';

part.
Thank you

A: To answer your points:

*

*Meteor.startup is run when the device or browser is ready (it's equivalent to what you are doing).

*Create a method in the client code -  Put the check in the button click method. Something like the code block at the end

*Server side rendering won't apply as you are printing from the browser

if (Meteor.isCordova) {
        Meteor.call("myPrintMethod",other-info);
    } else {
        alert("Sorry, I can only print from the device"
    }


text:
Q: Imagettfbbox and imagettftext Hey all i am wondering where i am missing the size of the textbox where the text is inside?
$img = imagecreatefromjpeg("Desert.jpg"); //http://s7.postimage.org/ceb440itn/Desert.jpg
$width = imagesx($img);
$height = imagesy($img);

$new_width = $width;
$new_height = $height;

$tmp_img = imagecreatetruecolor($new_width, $new_height);
imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Create some colors
$black = imagecolorallocate($tmp_img, 65, 173, 196);
// Define Font
$font = 'ARIAL.TTF';
// The text to draw
$text = 'This is a test here here blah';
//font size
$size = 75;
// Compute size of text and get the x and y for centering the text into the image
$box = imagettfbbox( $size, 0, $font, $text );
$x = 5;//($width - $box[2]) / 2 - 5;
$y = 75;//($height - $box[5]) / 2;

// Add some shadow to the text
imagettftext($tmp_img, $size, 0, $x+1, $y-1, $grey, $font, $text);

// Add the text
imagettftext($tmp_img, $size, 0, $x, $y, $black, $font, $text);

imagejpeg($tmp_img, "testing.jpg", 100);

imagedestroy($img);
imagedestroy($tmp_img);

The output image looks like this:
--------------------------
|This is a test here here|blah
|                        |
|                        |--Image
|                      --+----Inside image
|                        |
--------------------------

Notice it does not contain the word blah after here *within* the image itself.
This is what it should look like:
--------------------------
|This is a test here here|
|          blah          |
|                        |--Image
|                      --+----Inside image
|                        |
--------------------------

Where am i missing where it defines the size of the textbox?

A: Using a minimum number of edits, I get an undefined var for $grey.  The output image is here  http://www.laprbass.com/RAY_junk/testing.jpg
So my next question is, eh?  I don't have the Arial font.  Is this what you're seeing?

$desert = 'http://s7.postimage.org/ceb440itn/Desert.jpg';

$img = imagecreatefromjpeg($desert); //http://s7.postimage.org/ceb440itn/Desert.jpg
$width = imagesx($img);
$height = imagesy($img);

$new_width = $width;
$new_height = $height;

$tmp_img = imagecreatetruecolor($new_width, $new_height);
imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Create some colors
$black = imagecolorallocate($tmp_img, 65, 173, 196);

// Define Font
$font = 'ARIAL.TTF';
$font = 'fonts/verdana.ttf';

// The text to draw
$text = 'This is a test here here blah';

//font size
$size = 22;

// Compute size of text and get the x and y for centering the text into the image
$box = imagettfbbox( $size, 0, $font, $text );
$x = 5;//($width - $box[2]) / 2 - 5;
$y = 75;//($height - $box[5]) / 2;

// Add some shadow to the text
imagettftext($tmp_img, $size, 0, $x+1, $y-1, $grey, $font, $text);

// Add the text
imagettftext($tmp_img, $size, 0, $x, $y, $black, $font, $text);

imagejpeg($tmp_img, "RAY_junk/testing.jpg", 100);

imagedestroy($img);
imagedestroy($tmp_img);


text:
Q: CSS: Responsive parent div estoy teniendo problemas con el div padre "box", lo que quiero es que el contenido de este div padre sea responsive, quiero que box tenga un margen a la derecha de 20px y que el contenido tenga un width de 100% y se adapte dependiendo del tamano del navegador, en mi codigo estoy haciendo el intento pero cuando el navegador es mas pequeño, este pasa del div sin respetar el margen que he dejado.
Gracias de antemano a toda la comunidad, entiendo que el problema podria ser el contenido que contiene div con position absolute, pero si cambio estos div, afectaria mi contenido, que es emular un input con div.
<!DOCTYPE html>

    Contraseña