text:
Q: What is the probability of getting TTHH before HHH in repeated fair coin toss? We have a fair coin and it is being tossed until either HHH or TTHH appear. What is the probability of getting TTHH before HHH? I know that the answer is $7/12 \approx 0.583$ but I am not getting why this is the answer. Also, this is counter-intuitive. Shouldn't the probability of getting the pattern HHH be larger than the probability of getting the pattern TTHH since, after four tosses, we can only have one TTHH pattern while we have 3 HHH patterns?
My attempt: I have drawn the probability tree for 4 consecutive coin tosses. Here, we have three patterns (HHHH, HHHT, THHH) that have HHH and one pattern that has TTHH. So, intuitively it should be that the probability of getting TTHH before HHH is less than 1/4 while the probability of getting HHH before TTHH should be 3/4. But this answer is wrong. Correct answer is Pr.(getting TTHH before HHH) = 7/12. I made a python code to estimate this result attached below. It shows the correct answer. But how to make sense of this result? How to get the close form answer of 7/12 without estimating?
Python code for estimating:
import random as rd
cHHH = 0
cTTHH = 0
m = 10000
for i in range(0,m):
  num = str(rd.randint(0,1))
  while ( (num[-4:] != "0011") and (num[-3:] != "111") ):
    num = num + str(rd.randint(0,1))
    if num[-3:] == "111":
      cHHH += 1
      break
    if num[-4:] == "0011":
      cTTHH += 1
      break

p = cTTHH / m
q = cHHH / m
print("Probability of getting TTHH before HHH: ", p)
print("Probability of getting HHH before TTHH: ", q)

#Output:
Probability of getting TTHH before HHH:  0.5793
Probability of getting HHH before TTHH:  0.4207

A: I would have guessed that this question is essentially a duplicate, but I wasn't able to find a question with an answer that applies to this particular problem.
We can reformulate this problem using a Markov chain: Explicitly we're looking to compute the probabilities $\Bbb P(HHH), \Bbb P(TTHH)$ that the Markov chain settles into absorbing states corresponding respectively to $HHH$ and $TTHH$ occurring first.
The (eight) states are the possible stages of progress toward one of the two goal sequences ($HHH$, $TTHH$).
The transient states are:

*

*$\emptyset$: the initial state,

*$HT$: sequence ends in $HT$ (includes the sequence $T$)

*$HTH$ (includes $H$, $TH$)

*$TT$

*$HTHH$ (includes $HH$, $THH$)

*$TTH$
The absorbing states are:

*

*$HHH$: sequence ends in the goal $HHH$

*$TTHH$: sequence ends in the goal $TTHH$
In each state transient state there are two possible next states, corresponding to flipping $H$ and $T$ next, respectively, both of which thus have probability $\frac{1}{2}$. Explicitly, the transition matrix of the Markov chain, with respect to the above ordering of states, is
$$
P=\left(
\begin{array}{cccccc|cc}
\cdot & \frac{1}{2} & \frac{1}{2} & \cdot & \cdot & \cdot & \cdot & \cdot \\
\cdot & \cdot & \frac{1}{2} & \frac{1}{2} & \cdot & \cdot & \cdot & \cdot \\
\cdot & \frac{1}{2} & \cdot & \cdot & \frac{1}{2} & \cdot & \cdot & \cdot \\
\cdot & \cdot & \cdot & \frac{1}{2} & \cdot & \frac{1}{2} & \cdot & \cdot \\
\cdot & \frac{1}{2} & \cdot & \cdot & \cdot & \cdot & \frac{1}{2} & \cdot \\
\cdot & \frac{1}{2} & \cdot & \cdot & \cdot & \cdot & \cdot & \frac{1}{2} \\
\hline
& & & & & & 1 & \cdot \\
& & & & & & \cdot & 1 \\
\end{array}
\right) .$$
Since the absorbing states are at the end of our list, the above matrix is in a preferred form: The upper-left block, call it $Q$, specifies the transitions between transient states, and the upper-right block, call it $R$, specifies those from transient states to absorbing states.
By construction, if we start in the $i$th transient state the probability of settling in the $j$th absorbing state is the $(i, j)$-entry $B_{ij}$ of $B := N R$, where $N := (I - Q)^{-1}$ is the so-called fundamental matrix of the Markov chain. Since we start in the initial state, $\emptyset$, it's enough to compute $B_{11}$, i.e., the probability that the sequence $HHH$ occurs first, and $B_{12}$, i.e., the probability that $TTHH$ occurs first; since there are only $2$ absorbing states, $B_{12} = 1 - B_{11}$, and so it's enough to compute $$\Bbb P(HHH) = B_{11} = \sum_{k=1}^6 N_{1k} R_{k1} .$$ The only nonzero entry in the first column of $R$ is $R_{51} = \frac{1}{2}$, so $\Bbb P(HHH) = N_{15} R_{51} = \frac{1}{2} N_{15}$, and using Cramer's Rule we can compute $N_{15} = \frac{5}{6}$ without computing the other entries of $N$. Substituting yields the claimed probabilities:
$$\Bbb P(HHH) = \frac{5}{12} \qquad \textrm{and} \qquad \Bbb P(TTHH) = \frac{7}{12} .$$

A: We can imagine infinitely repeating the experiment by flipping an infinite number of coins, parsing the flips into frames of i.i.d. sizes $X_1, X_2, X_3, ...$, where in each frame we imagine "starting over" the experiment, and each frame independently ends with TTHH with probability $p$ and HHH with probability $1-p$.  Let $E[X]=E[X_i]$ for all $i \in \{1, 2, 3, ...\}$.  Then by renewal theory:
\begin{align}
&\frac{p}{E[X]} = (1/2)^4\\
&\frac{(1-p)+(1/2)+(1/2)^2}{E[X]} = (1/2)^3
\end{align}
The left-hand-side of the first equation is the reward per unit time  if we get a reward of 1 for every frame that ends with TTHH.  The right-hand-side of the first equation uses the observation that we can only get TTHH at the end of frames, and the expected number of occurrences of TTHH in $n$ coin flips is exactly $(1/2)^4(n-3)$, so the total reward per unit time must be $(1/2)^4$.
The right-hand-side of the second equation uses the observation that the expected number of occurrences of HHH in $n$ coin flips is exactly $(1/2)^3(n-2)$, so the number of occurrences of HHH per unit time (including those that appear in between frame boundaries) is $(1/2)^3$.   The left-hand-side of the second equation gives a reward at the end of each frame for each occurrence of HHH caused by that frame, where one occurrence is caused if we end with HHH (which happens with probability $1-p$), one "extra" occurrence in between frame boundaries is caused if we flip H after the frame (with prob $1/2$), a final "extra" occurrence in between frame boundaries is caused if we flip HH after the frame (with prob $(1/2)^2$).
Removing $E[X]$ from these two equations gives the equation from my above comment:
$$\boxed{[(1-p)+(1/2)+(1/2)^2](1/p)(1/2)^4 = (1/2)^3 \implies p=7/12}$$
Substituting $p=7/12$ back into the first equation gives
$E[X] = 2^4p = \frac{28}{3}\approx 9.33333$.

A: Here is a partial answer which explains why an apparently counterintuitive  result may be more likely than you first imagine.
If you don't get the pattern HHH in the first three throws or TTHH in the first four, then the first time HHH occurs will either have the last five throws TTHHH or HTHHH, which are clearly equally likely. In the first of these, TTHH wins. And since TTHH can appear without HHH making an appearance, well...
So if you get beyond the fourth throw, TTHH will win more than half of the time.

A: This can be easily done using First Step Analysis
Naming the starting state (before any toss) as $s$,
states for $TTHH$ as $a_1,a_2,a_3,a_4$ respectively,
and states for $HHH$ as $b_1,b_2,b_3$
Tracing movements and writing the equations for the probability that $TTHH$ wins,
$\displaylines{s=\frac12a_1+\frac12b_1\\ a_1=\frac12a_2+\frac12b_1,\quad\quad a_2=\frac12a_2+\frac12a_3,\quad\quad a_3=\frac12*1+\frac12a_1,\\ b_1=\frac12b_2+\frac12a_1,\quad\quad b_2=\frac12*0+\frac12a_1}$
This yields the probability that $TTHH$ wins, $s = \dfrac7{12}$

A: Here's an outline for solving this problem exactly:

*

*Formulate the problem as a Markov chain. You will have one state for each word over T, H which is a prefix of either HHH or TTHH (including the empty word, which stands for the initial state), for a total of 8 states. The two final states will have a probability $1$ loop, as the system never leaves those states. For all other states, you will have exactly two possible transitions, each with probability $1/2$, depending on the result of the next flip.

*Put the transition table of the Markov chain in matrix form $M$ so that given a vector $v$ of probabilities of being in each of the $8$ states, $M \cdot v$ will tell you the probabilities after one more flip.

*Take $v_0$ as the unit vector with a $1$ on the position corresponding to the initial state and $0$ elsewhere. With this, $M^n \cdot v_0$ will give you the probabilities after $n$ flips. Compute this value for a few small values of $n$ (preferably put this in Python to avoid mistakes; you can also factor out $1/2$, the rest will be only integers and you don't have to worry about precision). From that, guess the formula for $M^n \cdot v_0$ in terms of $n$ and prove it by induction.

*Compute the limit $lim_{n \to \infty} M^n \cdot v_0$. This will hold the answer to your problem. For verification, the limit should have probability $0$ for all non-final states.


text:
Q: how to temporarily disable a package in a project from compiling in Java EE IDE How can I temporarily disable a package in a project from compiling in Java EE IDE?
The package has some source files that I want to prevent from compiling temporarily.

A: If it is eclipse, try -
Project properties -> Java Build Path -> Source -> Excluded

A: If it is in another project, just right click on the project and select close project, you can easily re-open it when you need it back.
If it is in the same project, go to properties->Java Build Path->Source->Excluded. You can shift up and down easily and set priorities. Hope that help.

A: To disable a class/package in Eclipse:

*

*Right click the class file/package;

*Hover over "Build Path";

*Then click "Exclude";

*Done.

It's about the same to enable a class/package in Eclipse:

*

*Right click the class file/package;

*Hover over "Build Path";

*Then click "Include";

*Done.

redpajama_set_name: RedPajamaStackExchange


text:
Q: AngularJS trying to add a class to multiple values if it is true on ng-repeat I am having a hard time finding any resources on this matter and I was hoping somebody could help me.
I am currently pulling information from a DB and using AngularJS to do a ng-repeat based on specific filters.

    {{data.name}}
    {{data.id}}
    {{data.status}}

Based on this I am trying to add a class to change the background of {{data.status}} based on what is returned.  Could I possibly get an example of
 if data.status=="TEST" then add class "alert-success"
 else if data.status=="NEW" then add class "alert-info"
 else if data.status=="JUNK" then add class "alert-danger"
 else ""

and so on.  Thank you ahead of time.
Just so you can see what my current controller looks like
app.controller('test', function ($scope, $http, $timeout) {
$http.get('ajax/test.php').success(function(data){
    $scope.list = data;
    $scope.currentPage = 1; //current page
    $scope.entryLimit = 100; //max no of items to display in a page
    $scope.filteredItems = $scope.list.length; //Initially for no filter
    $scope.totalItems = $scope.list.length;
});
$scope.setPage = function(pageNo) {
    $scope.currentPage = pageNo;
};
$scope.filter = function() {
    $timeout(function() {
        $scope.filteredItems = $scope.filtered.length;
    }, 10);
};
$scope.sort_by = function(predicate) {
    $scope.predicate = predicate;
    $scope.reverse = !$scope.reverse;
};

});

A: AngularJS comes with a built-in directive called ng-class, which does exactly what you are looking for. Applied to your example request:

    {{data.name}}
    {{data.id}}
    {{data.status}}</td


text:
Q: Windows installation error for postgresql. Error in make command I am new to postgresql. I want to install postgresql through source code in windows. I am using MinGW and msys for installation. Configure command is working fine with me. When i execute make command I am getting errors. Would any one please help me to rectify these errors.
[gcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -O2 -I../../../../src/include -I./src/include/port/win32 -DEXEC_BACKEND  -I/home/roopteja.itha/openssl/include -I/home/roopteja.itha/uuid "-I../../../../src/include/port/win32" -DBUILDING_DLL  -c -o spgtextproc.o spgtextproc.c
In file included from ../../../../src/include/c.h:101:0,
                 from ../../../../src/include/postgres.h:47,
                 from spgtextproc.c:40:
../../../../src/include/pg_config_os.h:333:18: error: unknown type name '_locale_t'
 #define locale_t _locale_t
                  ^
../../../../src/include/utils/pg_locale.h:69:9: note: in expansion of macro 'locale_t'
 typedef locale_t pg_locale_t;
         ^~~~~~~~
make[4]: *** [spgtextproc.o] Error 1
make[4]: Leaving directory `/home/roopteja.itha/postgresql-9.5.10/src/backend/access/spgist'
make[3]: *** [spgist-recursive] Error 2
make[3]: Leaving directory `/home/roopteja.itha/postgresql-9.5.10/src/backend/access'
make[2]: *** [access-recursive] Error 2
make[2]: Leaving directory `/home/roopteja.itha/postgresql-9.5.10/src/backend'
make[1]: *** [all-backend-recurse] Error 2
make[1]: Leaving directory `/home/roopteja.itha/postgresql-9.5.10/src'
make: *** [all-src-recurse] Error 2]

I am not able resolve this issue. Would anyone suggest necessary implementations.

A: The 'locale_t' type is defined in xlocale.h. The pg_locale.h has a condition before including xlocale.h One of the conditions might not be satisfied, so your xlocale.h is not included yet. Something like this.
#ifndef _PG_LOCALE_
#define _PG_LOCALE_

#if defined(LOCALE_T_IN_XLOCALE) || defined(WCSTOMBS_L_IN_XLOCALE)
#include <xlocale.h>
#endif
#ifdef USE_ICU
#include <unicode/ucol.h>
#endif


text:
Q: Function that takes a char array as a parameter There is a function I want to use that takes char str[] as a parameter. I want to call the function giving a string input.
void someFunction (char str[]) {
    /* ... */
}

// Works.
someFunction("1010101");

// Does not work.
string someString;
someFunction(someString);

How can I get the second call to work?
EDIT: I cannot change the function's input parameters.

A: Depends on the nature of the string manipulations. If you read but don't write the string, change the prototype to const char str[] and use someString.c_str(), like others are suggesting.
If you change the characters but not the length of the string, use &*someString.begin().
If you extend/truncate the string, it's easier to pass a string& and work in terms of the string object. Less trouble, honestly.

A: You should be able to do:
someFunction(const_cast<char*>(someString.c_str()));

Although I'm not sure what will happen if str gets modified.
It's probably best if you just modify the original function to take a different parameter type.

A: What you want for std::string is void someFunction(std::string& str);
There's a reason for the issue -- a std::string's data is not guaranteed to be contiguous memory (at least, before C++11). Therefore, manipulating its buffer as a contiguous allocation (char[]) is a very bad idea.
casting away the const of std::string::c_str() is also a bad idea. One immediate problem you may face is that a std::string implementation may share backing string allocations with other std::string instances (copy-on-write), and you will end up modifying the values of other std::strings. Of course, there are many other bad things that could go wrong in their own implementation-defined ways -- the standard left this very flexible for the implementors of standard libraries.

EDIT: I cannot change the function's input parameters.

Use a std::vector instead.

A: You could have your function take a std::string instead:
void someFunction (std::string &str) {


text:
Q: Why are there no final interfaces in Java? Extending an interface simply adds additional operations to be defined in any implementors and cannot break any existing implementations (unlike extending a class).  But it can change (EDIT 3 WHICH CONSTANTS) and hence the PERCIEVED value of constants (EDIT 2 AS SEEN BY THE IMPLEMENTATION CLASSES).
For instance, the following:
interface A {
  int TEST = 6;
}

interface B extends A {
  int TEST = 7;
}

public class InterfacesTest implements B {
  public static void main(final String[] args) {
    System.out.println(TEST);
  }
}

yields 7, when perhaps the intent of interface A was that any implementation of A contain a test field valued at 6.
If A were to be declared final we could be assured all implementations of A see the same value of test.
So does anyone understand why this isn't possible?

*

*P.S.: This is NOT a duplicate of
this question, I know they
can't be final, I'm interested in the thinking behind the design
decision that led to this outcome.

*P.P.S.: I understand constants in
interfaces is usually a bad idea,
that isn't the issue here.
EDIT: Please check the revision history, the title of this question was edited in a way which did not reflect the question's intent.  Sorry to everyone who answered the question I wasn't asking.  Yes, interface fields are implicitly public static final, unfortunately that's not what I'm interested in at all.
EDIT 2 To be absolutely clear: this question is about why can't an interface block other interfaces from extending it (by being final or some equivalent).

A: Primary purpose of interface is not being a container of constants, it's to define some APIs which to be implemented by concrete classes.
And, from a lang spec (9.4. Abstract method declarations):

Note that a method declared in an interface must not be declared final or a compile-time error occurs. However, a method declared in an interface may be implemented by a method that is declared final in a class that implements the interface.

A: As I understand it, interfaces aren't supposed to place restrictions on implementations. They are supposed to define contract (API).
From this point, both method doIt and constant TEST are elements of API. We know how to use them, but we don't know what's inside.
And how exactly method doIt is implemented in InterfacesTest or what exact value constant TEST has - implementation details.

A: You have two variables named TEST, not one.  No overriding is taking place.  Overriding is only for methods.

A: It is final.  In fact, it's public static final even if you don't declare those.  What you are doing is not overriding the constant variable; you are hiding the parent interface's version.
Check it out, the A.TEST is not overridden.  It's still 6.
System.out.println(A.TEST);

A: final methods cannot be overriden.
final prevents a field being changed, but doesn't prevent it being hidden.  Note: You cannot override a field.
In your case A.TEST is hidden by B.TEST however
System.out.println(A.TEST);
System.out.println(B.TEST);

would print
6
7

A: If A were to be declared final we could be assured all implementations of A see the same value of test.
May be that You have answered yourself writing that question.
You can't also create a final abstract class, because to have sense it must be implemented, same thing goes for interface it has to be implemented by some class.


text:
Q: Android Architecture Components ViewModel context issue I am trying to use the new Architecture Components in Android, and so far it has worked pretty well. However, I have stumbled into an architectural problem.
I have a MainActivity that hosts a bunch of fragments, A, B, and C. Until now, every time I need my ViewModel (VM) I fetch it in the context of MainActivity (like this: MyViewModel vm = ViewModelProviders.of(getActivity()).get(MyViewModel.class);). Now consider this:

*

*Fragment C lets the user select some value, and writes it to the VM.

*Fragment A uses fragment C to have the user select the value, and then A reads the value directly from VM and shows it in its UI.

*Fragment B uses the same approach as fragment A.

The problem is, that since the VM is always in the context of the MainActivity, if fragment A has been used before B, the value will still be available, and B will show some old data.
The most obvious solution that I see is to create the VM in the contexts of fragments A and B respectively. But then I cannot figure out how to let fragment C access those VMs.
I could also create the VM in the context of fragment C, but that would require fragments A and B to create an instance of C, which I don't think is a nice solution.
A third solution would be keep the current approach and clear the data in the VM when appropriate, but that's also messy, I think.
What is the nicest way to go about this?

A: You can have a mapping in VM and store the values for A and B under different keys.
So, when A starts C it passes its A_key as an argument. When user chooses a value in C, it is being stored in VM's map using A_key as a key. When A checks whether a value is available, it only checks the value stored for A_key.
The same for B and B_key.


text:
Q: Querying a view after creating a clustered index on it still yields the same query plan I have the following view
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
GO

ALTER VIEW web.vGridHotelBooking
WITH SCHEMABINDING
AS
    SELECT
        HBK_ID,
        COF_ID,
        COF_CST_ID,
        HTL_Name,
        COF_Data
    FROM
        web.HotelBooking
    INNER JOIN
        web.CustomerOfferBundle ON COF_ID = HBK_COF_ID
    INNER JOIN
        web.Hotel ON COF_HTL_ID = HTL_ID;
GO

CREATE UNIQUE CLUSTERED INDEX [CLI_vGridHotelBooking__HBK_ID]
ON [web].[vGridHotelBooking] ([HBK_ID]) ON [PRIMARY]
GO

When I execute the statement SELECT * FROM web.vGridHotelBooking I expect to see a single clustered index scan, but instead I get this

This is the same plan I get when executing the SELECT statements directly.
What is that I am doing wrong here? I've used materialized views many times and I did not have that problem before.
EDIT 1
Running the query with a WHERE clause doesn't help either.
SELECT COF_ID
FROM web.vGridHotelBooking
WHERE COF_ID = '06A41DB5-8F14-4E6C-9084-3009E0626DAA';

EDIT 2
SELECT HBK_ID
FROM web.vGridHotelBooking
WHERE HBK_ID = 1801151518187788

EDIT 3
SELECT HBK_ID
FROM web.vGridHotelBooking WITH (INDEX(CLI_vGridHotelBooking__HBK_ID))
WHERE HBK_ID = 1801151518187788;

EDIT 4
Running the query with NOEXPAND yielded the correct plan this time.
SELECT *
FROM web.vGridHotelBooking WITH (NOEXPAND)
WHERE HBK_ID = 1801151518187788;

So the question then is - Why is that? Do I have to worry about this one.
Because CustomerOfferBundle table has aprx 500 000 rows in it and the Hotel table aprx 100 000
EDIT 5

A: As discussed in the comments you can force the use of the indexed view using the WITH (NOEXPAND) hint.
When you do so it shows that the forced plan is estimated at about 10% of the cost of the original plan so you might expect this to be chosen on cost grounds .
However the way that compilation works is that the view definition is first expanded out and then may or may not be matched back to the indexed view later in the optimisation process. For cheap plans optimisation may end without it ever getting to that step.
See Paul White's answer here for more about that. This also mentions

indexed view matching is not available in optimization phase 0
  (transaction processing).

the transaction processing step is concerned with queries referencing at least 3 tables and nested loops joins so it is entirely possible for you that optimisation just ended there.
If you increase the size of the tables (especially HotelBooking) and the original plan becomes more expensive more time will be spent on optimisation and the indexed view will probably end up matched.
You can always use the hint to be sure.


text:
Q: How to show $\sum^{n}_{k=0}{a_kb_k=A_nb_{n+1}+\sum^{n}_{k=1}{A_k(b_k-b_{k+1})}}$ by induction?
Let $n\in\mathbb{N}$ and $a_1,a_2,\cdots,a_n,b_1,b_2,\cdots,b_{n+1}\in\mathbb{R}$ and $A_k=\sum^{n}_{k+1}{a_j}$ with $1\leq k\leq n$.
Show that $\sum^{n}_{k=1}{a_kb_k=A_nb_{n+1}+\sum^{n}_{k=1}{A_k(b_k-b_{k+1})}}$ by induction.

I tried several times, however, I have a hard time to resolve this in the induction step. This is what I tried so far and looks most promising to me:
$$\sum^{n+1}_{k=1}{a_kb_k}=a_{n+1}b_{n+1}+\sum^{n}_{k=1}{a_kb_k}$$
$$=a_{n+1}b_{n+1}+\left(A_nb_{n+1}+\sum^{n}_{k=1}{A_k(b_k-b_{k+1})}\right)$$
$$=a_{n+1}b_{n+1}+\left(\left(\sum^{n}_{k=1}{a_k}\right)b_{n+1}+\sum^{n}_{k=1}{\left(\sum^{k}_{i=1}{a_i}\right)(b_k-b_{k+1})}\right)$$
$$=a_{n+1}b_{n+1}+\left(\left(\sum^{n}_{k=1}{a_k}\right)b_{n+1}+\sum^{n}_{k=1}{\left(\sum^{k}_{i=1}{a_i}\right)(b_k-b_{k+1})}\right)$$
$$=a_{n+1}b_{n+1}+\left(\left(\sum^{n}_{k=1}{a_k}\right)b_{n+1}+\sum^{n}_{k=1}{\left(\sum^{k}_{i=1}{a_i}\right)b_k}-\sum^{n}_{k=1}{\left(\sum^{k}_{i=1}{a_i}\right)b_{k+1}}\right)$$
$$=a_{n+1}b_{n+1}+\left(\left(\sum^{n}_{k=1}{a_k}\right)b_{n+1}+b_1a_1+\sum^{n}_{k=2}{\left(\sum^{k}_{i=1}{a_i}\right)b_k}-b_{n+1}\sum^{n}_{k=1}{\left(\sum^{k}_{i=1}{a_i}\right)}-\sum^{n-1}_{k=1}{\left(\sum^{k}_{i=1}{a_i}\right)b_{k+1}}\right)$$
$$=a_{n+1}b_{n+1}+\left(\left(\sum^{n}_{k=1}{a_k}\right)b_{n+1}+b_1a_1-b_{n+1}\sum^{n}_{k=1}{\left(\sum^{k}_{i=1}{a_i}\right)}\right)$$
$$=a_{n+1}b_{n+1}+\left(b_1a_1+b_{n+1}\left(A_n-\sum^{n}_{k=1}A_k\right)\right)$$
$$=???$$
I'd appreciate any hints or spotted errors!

A: It is not a good idea here to split up the term $A_n$. I would suggest instead:
$$ a_{n+1}b_{n+1} + \left[A_n b_{n+1} + \sum_{k=1}^n A_k(b_k-b_{k+1}) \right]  = A_{n+1} b_{n+1} + \sum_{k=1}^n A_k(b_k-b_{k+1}) = A_{n+1} b_{n+2} + \sum_{k=1}^{n+1} A_k(b_k-b_{k+1})$$

A: Hint:
If it must be shown that $$\sum_{k=0}^nr_k=p_n+\sum_{k=1}^nq_k$$ then this can be done by showing that $r_0+r_1=p_1+q_1$ and secondly $r_{n+1}=p_{n+1}-p_n+q_{n+1}$

A: Posting my answer from chat:
$$
\begin{align}
\sum^{n+1}_{k=1}{a_kb_k} &= a_{n+1}b_{n+1}+\sum^{n}_{k=1}{a_kb_k} \\
&= a_{n+1}b_{n+1}+A_nb_{n+1}+\sum^{n}_{k=1}{A_k(b_k-b_{k+1})} \\
&= a_{n+1}b_{n+1}+A_nb_{n+1} - A_{n+1} (b_{n+1}-b_{n+2})+\sum^{n+1}_{k=1}{A_k(b_k-b_{k+1})} \\
&= A_{n+1}b_{n+2} + a_{n+1}b_{n+1} - (A_{n+1} - A_n)b_{n+1}+\sum^{n+1}_{k=1}{A_k(b_k-b_{k+1})} \\
&= A_{n+1}b_{n+2} + a_{n+1}b_{n+1} - a_{n+1}b_{n+1}+\sum^{n+1}_{k=1}{A_k(b_k-b_{k+1})} \\
&=  A_{n+1}b_{n+2} + \sum^{n+1}_{k=1}{A_k(b_k-b_{k+1})}
\end{align}
$$


text:
Q: How to implement correction suggestions without Spell checker framework? I use Spell checker framework to display suggestions on my custom Android keyboard. I works fine, but not on Samsung devices. How I can fix this, use another way or may be some library?
My code
val spellCheckerSession =
    (context.getSystemService(TEXT_SERVICES_MANAGER_SERVICE) as TextServicesManager)
        .newSpellCheckerSession(
            null,
            Locale.ENGLISH,
            object : SpellCheckerSession.SpellCheckerSessionListener {
                override fun onGetSuggestions(p0: Array<out SuggestionsInfo>?) {}

                override fun onGetSentenceSuggestions(sentenceSuggestionsInfos: Array<out SentenceSuggestionsInfo>?) {
                    // TODO use suggestions
                }
            },
            true
        )
spellCheckerSession?.getSentenceSuggestions(
    arrayOf(TextInfo(inputWord)),
    SUGGESTION_COUNT
)

A: Spell checker is generally used by non-keyboards to offer spelling corrections.  Keyboard generally just automatically correct things, or offer options in their candidates view (and they may use the candidates view API for that or they may just make their own candidates view above the keyboard.  I know at Swype we did the second, because we didn't like how the built in candidate functionality behaved).
Actually I just remembered-  it might be my fault it has problems on Samsung devices.  A decade ago when the spell checker framework came out, it interacted badly with us and some of their other custom software.  I suggested to their engineers they just disable the functionality, since all the keyboards they used had it built in.  They did.  They may never have changed that.  Sorry about that.


text:
Q: Setting and updating form inputs with firebase database and react hooks In my app I have profile section with a form. When the component mounts I want to fetch user data from firebase, and display it in the form, with the current values of the user profile. Either using the "value" prop or the "placeholder" prop.
When the user makes changes in the form inputs and submit the changes, I want the database to update and the form to update with the new data.
Currently I can make the database value appear in the form input field, or I can make the form input field empty, but update the database. But not both.
The following code makes the database data render in the form input, but it cant be changed.
I know it could be something with the second useEffect() and the getUserData() function, that I cant seem to figure out.
const UserEdit = (props) => {
    const [currentUser, setCurrentUser] =  useState('');
    const [forening, setForening] = useState('');

    useEffect(() => {
        firebase_app.auth().onAuthStateChanged(setCurrentUser);
    }, [])

    const getUserData =  async () => {
        await dbRef.ref('/' + currentUser.uid + '/profil/' ).once('value', snapshot => {
        const value =  snapshot.val();
        setForening(value)
        })
    }

    useEffect(() => {
        getUserData()
    },[] )

    const handleInput = (event) => {
        setForening(event.target.value)

    }

    const updateUserData = () => {
        dbRef.ref('/' + currentUser.uid + '/profil/' ).set({foreningsnavn: forening}, function(error)  {
            if(error) {
                console.log("update failed")
            } else {
                alert(forening)
            }
        })
    }

    const handleClick = () => {
        updateUserData()
    }

    return (
        <>

                            {Forening}
                            <input className="form-control" type="text"  value={forening} onChange={handleInput}/>

        </>
    )

}

A: Your second useEffect will run only one time because the second argument array [] of dependencies is empty:
useEffect(() => {
        getUserData()
    },[] )

You can add foreign dependency to make useEffect run with input change
useEffect(() => {
        getUserData()
    },[foreign] )

or you can use polling to sync database state


text:
Q: Why i'm not getting push notification when the app is not running Here is my full code, in this. If the app is running, then i'll get push notification that too for public void handleResponse method. But if i quit the app, i wont get push notification itself, please help.
Mainactivity.java
    public class MainActivity extends AppCompatActivity {

    private static final String YOUR_APP_ID = "2C25D658-240D-4350-FF8A-6CF4DBD88F00";
    private static final String YOUR_SECRET_KEY = "24DB6F44-8C97-1DCF-FF22-060777780600";
    String appVersion = "v1";
    Subscription subscription;

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

        Backendless.initApp(this, YOUR_APP_ID, YOUR_SECRET_KEY, "v1");

        Backendless.Messaging.registerDevice("183254839430", "default", new AsyncCallback<Void>() {
            @Override
            public void handleResponse(Void aVoid) {

                Toast.makeText(MainActivity.this, "Registered", Toast.LENGTH_LONG).show();
            }

            @Override
            public void handleFault(BackendlessFault backendlessFault) {

                Toast.makeText(MainActivity.this, backendlessFault.getMessage(), Toast.LENGTH_LONG).show();
            }
        });

        Backendless.Messaging.subscribe( "default",
                new AsyncCallback<List<Message>>() {

                    @Override
                    public void handleResponse(List<Message> response) {

                        Toast.makeText(MainActivity.this, "Notification arrived successfully", Toast.LENGTH_LONG).show();

                        for (Message message : response) {
                            String publisherId = message.getPublisherId();
                            Object data = message.getData();
                        }
                    }

                    @Override
                    public void handleFault(BackendlessFault fault) {
                        Toast.makeText(MainActivity.this, fault.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                },
                new AsyncCallback<Subscription>()
                {
                    @Override
                    public void handleResponse( Subscription response )
                    {
                        subscription = response;
                    }
                    @Override
                    public void handleFault( BackendlessFault fault )
                    {
                        Toast.makeText( MainActivity.this, fault.getMessage(), Toast.LENGTH_SHORT ).show();
                    }
                }
        );

    }
}

pushreceiver.java.
This code itself is not triggering, i'm confused why :-(
    public class PushReceiver extends GcmListenerService {

        //This method will be called on every new message received
        @Override
        public void onMessageReceived(String from, Bundle data) {

            Toast.makeText(getApplicationContext(), "Notification came PushReceiver", Toast.LENGTH_LONG).show();

            //Getting the message from the bundle
            String message = data.getString("message");
            //Displaying a notiffication with the message
            sendNotification(message);
        }

        //This method is generating a notification and displaying the notification
    private void sendNotification(String message) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        int requestCode = 0;
        PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_ONE_SHOT);
        Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentText(message)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, noBuilder.build()); //0 = ID of notification
    }
}

My Manifest file.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="feelzdroid.backednlessgcm">

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
<uses-permission android:name="feelzdroid.backednlessgcm.permission.C2D_MESSAGE"/>
<permission android:name="feelzdroid.backednlessgcm.permission.C2D_MESSAGE" android:protectionLevel="signature"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name="com.google.android.gms.gcm.GcmReceiver"
        android:exported="true"
        android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE"/>
            <action android:name="com.google.android.c2dm.intent.REGISTRATION"/>
            <category android:name="feelzdroid.backednlessgcm"/>
        </intent-filter>
    </receiver>

    <service android:name=".PushReceiver" android:exported="false">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE"/>
        </intent-filter>
    </service>

</application>

Log.
07-03 16:43:31.893 11026-11143/feelzdroid.backednlessgcm I/GMPM: App measurement is starting up
07-03 16:43:31.915 11026-11143/feelzdroid.backednlessgcm E/GMPM: getGoogleAppId failed with status: 10
07-03 16:43:31.918 11026-11143/feelzdroid.backednlessgcm E/GMPM: Uploading is not possible. App measurement disabled


text:
Q: What is alternative function in sql REGEXP_COUNT in SQL Server Below is the variable in Oracle I need to convert in SQL Server please suggest.
V_BAD_EMAIL_CNT NUMBER :=  REGEXP_COUNT(pv_bad_emails,',') + 1;

A: This will return the number of comma's in the string + 1 in SQL
 declare @pv_bad_emails varchar(1000);
 set @pv_bad_emails = 'a,b,c,d';
 select len(@pv_bad_emails) - len(replace(@pv_bad_emails, ',', '')) + 1

For more reference
How do you count the number of occurrences of a certain substring in a SQL varchar?


text:
Q: Getting the number of occurrences for each combination I have a long dataframe that looks something similar to the following:
       ID      Type   Price
0      1        A       230
1      2        B       150
2      1        B       180
3      3        A       280
4      4        A       222
5      2        B       124
6      1        A       221

I want to count the number of occurrences for each combination of Type, depending on ID, while also getting the mean price for the each combination.
I want the following:
       Combinaton   Counts   Mean Price
0    [2x A, 1x B]       1        210,33
1      [2x B]           1        137
2      [1x A]           2        251

I've tried .value_counts(), groupby, transforming columns, etc.. but nothing seems to get what I want. Can somebody help me on this?

A: Perform two groupby operations, making sure the first aggregation on Type results in a hashable object like a tuple:
df['Counts'] = np.zeros(len(df))

df = df.groupby('ID').aggregate({'Type':tuple, 'Price':'mean', 'Counts': 'count'})

print(df.groupby('Type').aggregate({'Counts':'count', 'Price': 'mean'}).reset_index())

Which results in:
        Type  Counts      Price
0       (A,)      2  251.000000
1  (A, B, A)      1  210.333333
2     (B, B)      1  137.000000


text:
Q: Find unmatched unique pairs of an array from another array I have a list of users and I have also list of pairs of matched users. i-e
const users = ["A", "B", "C", "D", "E", "F", "G"];
const alreadyMatchedUsers = [
    { user1: 'A', user2: 'B' },
    { user1: 'A', user2: 'C' },
  ]

I want to find list of unique unmatched users. By unique, I mean user pair AB and BA will be considered as 1 pair.
Here is the solution I have came up with:
const alreadyMatchedUsers = [
    { user1: 'A', user2: 'B' },
    { user1: 'A', user2: 'C' },
  ]

  const unMatchedArrary = []

  // const users = ['A', 'B', 'C', 'D']

  const users = []

  for (let i = 0; i < 300; i++) users.push(i)

  const n = users.length
  const uniquePossiblePairs = []
  const uniquePossiblePairsCount = (n * (n - 1)) / 2

  for (let i = 0; i < n - 1; i++) {
    console.log('Main loop+++++++++++++++++', users[i])
    for (let j = i; j < n - 1; j++) {
      // uniquePossiblePairs.push({ user1: users[i], user2: users[j + 1] });
      const alreadyMatched = alreadyMatchedUsers.some(
        (mpair) => (users[i] === mpair.user1 || users[i] === mpair.user2)
          && (users[j + 1] === mpair.user1 || users[j + 1] === mpair.user2),
      )

      if (!alreadyMatched) {
        unMatchedArrary.push({ user1: users[i], user2: users[j + 1] })
      }

      console.log('Already Matched, ', users[i], users[j + 1], alreadyMatched)
    }
  }

  console.log('UNIQUE POSSIBLE PAIRS Count', uniquePossiblePairsCount)
  console.log('UNIQUE POSSIBLE PAIRS', uniquePossiblePairs)
  console.log('UNMATCHED ARRARY ', unMatchedArrary)
}

This solutions gives the expected results, But its very expensive operation. Try running this code with 300 users and if alreadyMatched users gets bigger, it will become way more expensive.
How can I get this to be faster?
Thanks

A: const users = ["A", "B", "C", "D", "E", "F"];

const combinations = [];
while (users.length > 0) {
    const lastUser = users[users.length-1]; // start at last user of users list.

     // this loop gets all combinations involving the last user.
    for (let user of users) {
        if (user !== lastUser) {
            combinations.push({"user1": user, "user2": lastUser});
        }
    }

    // this gets rid of last user from the users list, as we have found all its combinations from this iteration of the while loop.
    users.pop()
}

console.log(combinations);

This algorithm ensures number of iterations == number of possible combinations.

A: This is how you can achieve that:

const users = ["A", "B", "C", "D", "E", "F", "G"];
const alreadyMatchedUsers = [
  { user1: 'A', user2: 'B' },
  { user1: 'A', user2: 'C' },
]

const pairs = alreadyMatchedUsers.map(x => `${x.user1}${x.user2},${x.user2}${x.user1}`);

let allPairs = [];

for (user of users) {
  allPairs.push(...users.map(x => `${user}${x},${x}${user}`))
}

// filter allPairs
const uniquePairs = allPairs
   .filter(pair => !pairs.includes(pair) && pair.split(',')[0] != pair.split(',')[1])
   .map(pair => pair.split(',')[0].split(''));

console.log('pairs: ', pairs);
console.log('allPairs: ', allPairs);
console.log('uniquePairs', uniquePairs);

A: Here is my take on this problem. I have replaced the matchedPairs from objects to arrays to simplify this.

 const users = ["A", "B", "C", "D", "E", "F", "G"];
const alreadyMatchedUsers = [
  ["A", "B"],
  ["A", "C"],
];
const unmatchedPairs = [...alreadyMatchedUsers];
const unmatchedPairsFinal = [];
for (let i = 0; i < users.length; i++) {
  users.forEach((user) => {
    if (user !== users[i]) {
      console.log("checking", user, " vs ", users[i]);
      const alreadyDetected = unmatchedPairs.filter((userCheck) => {
        return userCheck.includes(user) && userCheck.includes(users[i]);
      });
      console.log(alreadyDetected);
      if (!alreadyDetected.length > 0) {
        unmatchedPairs.push([user, users[i]]);
        unmatchedPairsFinal.push([user, users[i]]);
      }
    }
  });
}
console.log(unmatchedPairs);
console.log(unmatchedPairsFinal);


text:
Q: In Vim statusline, right-pad number Say I do set statusline+=col:%3v; in Vim 8.
Now if I'm on column 1, my statusline looks like col:  1;.
How do I get the padding on the other side of the number? E.g., how do I get my column 1 statusline to look like col:1   ;?

A: Use %-3v. As documented in :help 'statusline:
field       meaning
-           Left justify the item.  The default is right justified
            when minwid is larger than the length of the item.

This is also the convention used by printf, which vim is clearly imitating.


text:
Q: How to convert an image to a compressed string representation equivalent to one copied to clipboard by `CopyToClipboard[image]`? In my recent question I asked How to embed an image into a string?
The suggested solution was
(* In[1]:= *) image = Import["https://wolfram.com/favicon.ico", "Image"];
(* In[2]:= *) str = ToString[image, StandardForm];

If I execute
(* In[3]:= *) CopyToClipboard[str];

and then paste it into a plain text editor (e.g. notepad on Windows) than I get a very long and verbose string:
\!\(\*GraphicsBox[TagBox[RasterBox[RawArray["Byte", List[List[List[0, 0, 0, 0], (* ... *) List[0, 0, 0, 0]]]], List[List[0, 16], List[16, 0]], List[0, 255], Rule[ColorFunction, RGBColor]], BoxForm`ImageTag["Byte", Rule[ColorSpace, "RGB"], Rule[Interleaving, True]], Rule[Selectable, False]], Rule[BaseStyle, "ImageGraphics"], Rule[ImageSizeRaw, List[16, 16]], Rule[PlotRange, List[List[0, 16], List[0, 16]]]]\)

But if I copy the image to the clipboard directly
(* In[4]:= *) CopyToClipboard[image];

and then paste it into a plain text editor than I get a compressed representation:
\!\(\*
GraphicsBox[
TagBox[RasterBox[CompressedData["
1:eJyNUgss1HEc/+9CKBIyz928OodzCOdxcU95njh5tIQbpvUgDrFKWtIDPaZk
tLTmIiJbWR6pbLVSlNSI0S0j4bS8tiZ9Oi1NFvluv99+n+++n31/3+/nYyxK
CIojEQSRrCy/gqLT2ElJ0elCBTngpItjRWvkD43fZz75v3ibne/1+uIF0ipK
iVviDPd37ADrBdyRdYz8zZYz9yozS3UhdyckeVPl+csq/+LnpR7hvqG4yUaZ
/AP9gf6uMgqtdZwgoY3ilFbtEqJ5gxaa+Zizp7CuVKK03B+K1OwBkgl+MM1m
RnjG6GQZo1tJD7V6HGkTwUMfK0Gw0gyZWvSJJ0r2GBP5Y6goBv054ai3scU5
goEhgosB3zjHpZyykL2pD0nMqadkZ9yj2qOSYOKBiRcaOf4oZ3CRqspAsaEH
oO8IaNFHe7lBZlLPMKMB7g7qPL+ktEStx0kgnTO1xEBwAHrpbIz7haNdKESN
JwtnTeho5nOByG2YJXQBQgdf6VvRHbsv/c+uoyPM4eeK4TA/TIYJgIJTmC6/
irbcFNzmuaEpKhgTp3fik54aBnU2fR7wFdAXz9DnI5S8NzLHc3MqZAejMFlx
Ed8bqyAryseL7d6otnBAX7wQI+SNaN3mJVnglSYeXfuAubuhTnGzfEcaqNI3
RWegN3pOijFYdAJIT4DU2Rk3FSwgUWOgS8UK/dpWaDicwZvnF0Ts55+nel/K
0bU9U2VocP1ZgLu8Hw/tgTxI4/0wEcDEoKMDWmy24Jy6BY4Tlrgm16fOjj9V
IT4kWqpFl4217EOoJx7RLdCqtwEfPe0AcTDAdsBLbTrynH3Tdhmz1TPN+I7F
nCCXv3SMiF9fS1DQTKZBomMwUUNoYZpCwwzVAF8IVYwquqAlu0B5Oe8UBsb4
FPPC48o8vDWvkC1Z9Spus8PrGLjLYf3ya6ey3VhHbnHESv5bHPVOYe0Ngkjf
Bdxs6aFy/2Q+bbX8mpScjCpRovZKNT8BKotUng==
"], {{0, 16}, {16, 0}}, {0, 255},
ColorFunction->RGBColor],
BoxForm`ImageTag["Byte", ColorSpace -> "RGB", Interleaving -> True],
Selectable->False],
BaseStyle->"ImageGraphics",
ImageSizeRaw->{16, 16},
PlotRange->{{0, 16}, {0, 16}}]\)

Both the long and compressed strings, if being pasted back to a Mathematica notebook, are automatically represented as the original image:
(* In[5]:= *)
I am interested in

Question 1: How to get the compressed string programmatically, without using the clipboard?

The content of CompressedData["..."] looks like a result of the Compress function, and indeed it could be checked that
(* In[6]:= *) ToBoxes[image][[1, 1, 1]] ===
 Uncompress["
  1:eJyNUgss1HEc/+9CKBIyz928OodzCOdxcU95njh5tIQbpvUgDrFKWtIDPaZk
  tLTmIiJbWR6pbLVSlNSI0S0j4bS8tiZ9Oi1NFvluv99+n+++n31/3+/nYyxK
  CIojEQSRrCy/gqLT2ElJ0elCBTngpItjRWvkD43fZz75v3ibne/1+uIF0ipK
  iVviDPd37ADrBdyRdYz8zZYz9yozS3UhdyckeVPl+csq/+LnpR7hvqG4yUaZ
  /AP9gf6uMgqtdZwgoY3ilFbtEqJ5gxaa+Zizp7CuVKK03B+K1OwBkgl+MM1m
  RnjG6GQZo1tJD7V6HGkTwUMfK0Gw0gyZWvSJJ0r2GBP5Y6goBv054ai3scU5
  goEhgosB3zjHpZyykL2pD0nMqadkZ9yj2qOSYOKBiRcaOf4oZ3CRqspAsaEH
  oO8IaNFHe7lBZlLPMKMB7g7qPL+ktEStx0kgnTO1xEBwAHrpbIz7haNdKESN
  JwtnTeho5nOByG2YJXQBQgdf6VvRHbsv/c+uoyPM4eeK4TA/TIYJgIJTmC6/
  irbcFNzmuaEpKhgTp3fik54aBnU2fR7wFdAXz9DnI5S8NzLHc3MqZAejMFlx
  Ed8bqyAryseL7d6otnBAX7wQI+SNaN3mJVnglSYeXfuAubuhTnGzfEcaqNI3
  RWegN3pOijFYdAJIT4DU2Rk3FSwgUWOgS8UK/dpWaDicwZvnF0Ts55+nel/K
  0bU9U2VocP1ZgLu8Hw/tgTxI4/0wEcDEoKMDWmy24Jy6BY4Tlrgm16fOjj9V
  IT4kWqpFl4217EOoJx7RLdCqtwEfPe0AcTDAdsBLbTrynH3Tdhmz1TPN+I7F
  nCCXv3SMiF9fS1DQTKZBomMwUUNoYZpCwwzVAF8IVYwquqAlu0B5Oe8UBsb4
  FPPC48o8vDWvkC1Z9Spus8PrGLjLYf3ya6ey3VhHbnHESv5bHPVOYe0Ngkjf
  Bdxs6aFy/2Q+bbX8mpScjCpRovZKNT8BKotUng==
  "]
(* Out[6]= True *)

Unfortunately, RawArray, CompressedData and BoxForm`ImageTag are all undocumented. It looks like RawArray represents (probably, optimized) internal representation of a multi-dimensional array, and CompressedData is equivalent to Uncompress (e.g. unless being held, it automatically evaluates to the object represented by the compressed string) except that CompressedData can be successfully interpreted as part of an input of the form \!\(\* ... \).

Question 2: Did I get their meaning right? Can they be useful in any other context?

Assuming I did it right, the closest result I was able to obtain to what I need is given by
(* In[7]:= *) toCompressedString[image_Image] :=
  "\!\(\*" <> ToString[
    ToBoxes[image] /.
     array_RawArray :>
      With[{compressed = Compress[array]},
       CompressedData[compressed] /; True],
    InputForm] <> "\)";

(/; True is the Trott-Strzebonski trick that I learned trying to write this code).
Is there a more strightforward way to get this string?

A: If you look at the internal expression of the cell containing the image, you'll find that it also uses the compressed form. However, the usual trick of Cell@BoxData@ToBoxes... doesn't seem to work here, as that only gives us the RawArray representation. This gives us a hint at a possible way of retrieving the compressed representation without having to build it up ourselves.
In the following implementation, we create a new document with the image, flip the cell to show its expression (as if you had chosen Cell > Show Expression from the menu bar), copy its contents and then discard the notebook.
ClearAll@getCompressedString
getCompressedString[img_] := Module[{nb = CreateDocument[img, Visible -> False], str},
    SelectionMove[nb, Next, Cell];
    FrontEndTokenExecute[nb, "ToggleShowExpression"];
    str = First[FrontEndExecute[FrontEnd`ExportPacket[NotebookSelection[nb], "InputText"]]];
    NotebookClose@nb;
    First@StringCases[str, x : ("GraphicsBox" ~~ __) :> StringDrop[x, -2]]
]

If you now call getCompressedString on your image, you should get the string you want, which you can then pad with "\!\(\*" and "/)" to get back the image.


text:
Q: Select options through ng-click is not working in chrome browser using AngularJS I need to use ng-click so that I can pass three parameters and set in my local json based on the selection.
<select>
<option id="" value="">--Select--</option>
<option ng-repeat="comparison in comparisons" ng-click="setSkillComparisonOperator(index,comparison.sid,comparison.name)"
 ng-selected="comparison.sid == data.value.comparisonOperator.sid">{{comparison.name}}</option>
</select>

I can use it ng-model and ng-change as follows.
<select ng-model="item" ng-options="o.id as o.id for o in list" ng-change="onFunction(item)">{{item}}</select>

In that case , I can't pass three parameters as follows.
<select ng-model="item" ng-options="o.id as o.id for o in list" ng-change="onFunction(o.id,o.name)">{{item}}</select>

A: At last , I found solution.
JS fiddle link
HTML page is

        <select ng-model="selectedColor" ng-options="color as color.name for color in colors" ng-init="selectedColor = check(color1,colors)" ng-change="setColor(selectedColor)">
            <option value="">Select A Color</option>
        </select>

        Color Id:

        Color name:

        Color shade:

Javascript is
var $scope;
var app = angular.module('miniapp', []);

function Ctrl($scope) {
    $scope.colorId = 4;
    $scope.shade = null;
    $scope.color = null;
    $scope.color1 = {name:'Red', value: 'red',id:2};
    $scope.colors = [
        {name:'Red', shade: 'white',id:1},
            {name:'Orange', shade: 'red',id:2},
            {name:'Yellow', shade: 'blue',id:3},
            {name:'Green', shade: 'yellow',id:4},
            {name:'Blue', shade: 'indigo',id:5},
            {name:'Indigo', shade: 'violet',id:6},
            {name:'Violet', shade: 'orange',id:7}
     ];
    $scope.check =function(selectedColor,colors){
        var i = null;
        for(i in colors){
            if(colors[i].id == selectedColor.id){
                return colors[i];
            }
        }
    };
    $scope.setColor= function(color){
        $scope.colorId = color.id;
        $scope.shade = color.shade;
        $scope.color = color.name;
    };
};

A: Angular actually takes care of this form you with ng:model. You don't need to pass any parameters.
In your callback function you can do this:
$scope.onFunction = function() {
  var id = $scope.item.id;
  var name = $scope.item.name;
  ...
};

A: I have the same problem and I solve this as Krish Lakshmanan did. I also added:
<option value="">Some text</option>

OR (force to select a member from the list)
$scope.options = [1,2,3];
$scope.d  = $scope.options[0];

I don't know why but using Chrome with AngularJs, this bug of selection happens, I think problem is at Chrome, because Firefox it worked (I thought firefox sets the value on focus out the input).

I found this thread here:
  https://github.com/angular/angular.js/issues/4836
The bug: http://jsbin.com/wofejo/1/
The workaround here: http://jsfiddle.net/JqnMr/
The workaround 2 here: http://jsfiddle.net/y61pacre/
And this issue on chromium: https://code.google.com/p/chromium/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Pri%20M%20Week%20ReleaseBlock%20Cr%20Status%20Owner%20Summary%20OS%20Modified&groupby=&sort=&id=415505

I hope I helped someone, if you find the solution without using an empty option or forcing the selection of a member, please tell me! :)


text:
Q: Linking to other jade files I'm trying to understand how Express and Jade works.
First of all, am I doing it right when I'm using layout.jade as a template file (header, body, footer) and using different files to show information in the body (see examples below)?
The code works fine, but i'm unsure if this is the right way to do stuff in Express. If I should keep going with this structure, how can I link to other files (eg.About.jade) internally from for example index.jade, to show that file instead of index.jade?
Thanks in advance!
layout.jade:
!!! 5
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
    script(type='text/javascript', src='https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js')
    script(type='text/javascript', src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js')
    script(type='text/javascript', src='/javascripts/external.js')

  // Header
  header#header

  // Navigation
  nav#nav
    // Navigation code (ul, li etc)...

  // Sidebar
  aside#sidebar
    // Sidebar code...

  // Body
  body!= body

index.jade:
!!! 5
html
  head
    title= title

    section#wrapper
      img.imageStyle(src = '/images/test1.png')
      // And so on...

About.jade:
// You get it...

A: additionally to what Wes Freeman wrote you can also include other jade templates in your jade file.
that way you could have your header.jade, footer.jade and include them in your about.jade file. here's the include documentation from jade:
https://github.com/visionmedia/jade#a13
that way you only have to change the header.jade file if you add for example script or stylesheet tags that should be on every page.

A: I think what you're looking for are view rendering routes in express:
http://expressjs.com/en/guide/using-template-engines.html
So you can set up something like this:
app.get('/', function(req, res){
  res.render('index.jade', { title: 'index' });
});

app.get('/about', function(req, res){
  res.render('about.jade', { title: 'about' });
});

To link from one to the other, once you have the proper routes configured, you can just do something like:
a(href='/') index

a(href='/about') about

Update Also, you don't need this repeated again in index.
!!! 5
html
  head
    title= title


text:
Q: Maintining state on components in a Flux environment We're using React and Flux (via the Alt implementation).
The state is maintained on the stores and is passed to the view components as props, which is nice for data.
I found myself, however, maintaining state such as isOnHover and similar UI states in the store as well, which seems cumbersome (creating action and store handlers for each UI state).
Is maintaining UI state directly on the component itself considered a bad practice, and if so, why?
Thanks.

A: Maintaining anything other than the data which the store provides in the respective store is bad practice in my opinion. One store for each piece of data. A components state should stay in the component.
Setting values like isOnHover should be stored and updated in the component, and initially set using getInitialState.
It's good to think of things like this in terms of using components across projects, you want to be able to essentially plug and play with minimal of fuss and code tangle for each component part.


text:
Q: ASP.NET MVC 4 automatic loading plugins dll without rebuild I have question about this plugin system: .NET 4.0 ASP.NET MVC 3 plug-in architecture with embedded views
It is possible when I start ptoject (web site local in visual studio using ctrl + f5) that when I delete plugin.dll from plugin folder. System automaticly detect it and disable module or when I will put new plugin .dll to plugin folder, system automaticly detect new plugin without rebuild completly solution ? I just need the plugin system which t will not need restart server when user is installing it to the aplication.
Thnaks for your help and sorry for my english !

A: Be careful with the plugins architecture : once you've loaded an assembly in an AppDomain, it cannot be unloaded ( see How to unload an assembly from the primary AppDomain? ).
You may want to have a look at MEF : http://msdn.microsoft.com/en-us/library/system.componentmodel.composition%28VS.100%29.aspx


text:
Q: R multiple lines plotly chart with customized line types I have probably a simple R plotly question but I spent about one hour reading questions in stackoverflow and I really can't find what I need. I have a dataframe (I will share a screenshot) with different columns used to create a multiple lines plotly chart.
This is the code I use to create the plot:
plot_ly(data = df_final, x=~TENOR, y=~RATE) %>% add_trace(type='scatter',mode='lines', color=~LINE_NAME, colors = ~LINE_COL) %>%
    layout(title=paste0("Market data"),
           xaxis=list(title='Term (years)'),
           yaxis=list(title='Yield'))

it works amazing but I would like to have the option to choose if some lines will have to be dashed, dots, or solid lines as well as their width.
I would need / want to specify this information inside the dataframe and choose the dataframe column that has such information (i.e. see the column "LINE_STYLE_FACTOR" in my attached dataframe).
I checked Multiple line chart using plotly r and Plotly r, line style by variable but I can't find how to do what I need.
The solution has to use plotly and not other charting solutions.
Thanks

A: At least for the line types (dash vs line), you can you 'linetype':
library(dplyr)
library(plotly)

df = data.frame(xVals = rep(1:10,2),
                yVals = c(1:10, 2:11),
                myColor = c(rep('Red', 10), rep('Blue', 10)),
                myType = c(rep('solid', 10), rep('dot', 10)),
                myName = c(rep('FirstName', 10), rep('SecondName', 10)))
plot_ly(df,
        x = ~xVals,
        y = ~yVals,
        color = ~I(myColor),
        name = ~myName,
        type = 'scatter',
        mode = 'lines',
        linetype = ~I(myType)
)


text:
Q: How to create user page dynamically after registration of user In mediawiki, how do I create a page for the user dynamically after user registration?
For example, after user xyz get registered, a user page is created with name User:xyz.
How can this be done?

A: Write a MediaWiki extension that hooks into the AddNewAccount hook.  See this question for the PHP code for creating new articles within an extension.

A: You could definitely create a bot to do this, it probably wouldn't even be difficult.


text:
Q: Sessions and PHP classes I'm used to java, objective c and a little c++.
Now i want to use PHP to create a website. I created several classes but to keep it simple: 3 classes.
Account - DataMapper - DataManager
This means that i can get an account from the database. In DataManager i keep track of all things. Like the userId of the user.
The thing is, normally all setted variables stay 'set', but now i'm using php i apperently need to store them by using a session.
DataManager:
<? php
class DataManager
{
    // Hold an instance of the class
    private static $dm;
    private $dataMapper;
    private $dictationView;
    private $userId;

    private function __construct()
    {
        $this->dataMapper = new DataMapper();
        $this->dictationView = new DictationView();
    }

    // The singleton method
    public static function singleton()
    {
        if (!isset(self::$dm)) {
            $c = __CLASS__;
            self::$dm = new $c;
        }

        return self::$dm;
    }

    // Prevent users to clone the instance
    public function __clone()
    {
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }

    function __get($prop) {
        return $this->$prop;
        }

    function __set($prop, $val) {
        $this->$prop = $val;
        }
}

?>

If i set the userId in the singleton DataManager class, the next time i
call an instance of the DataManager class it will not rememeber the userId. Somewhere i have to deal with session i guess. How to use sessions in a good OOP way in the DataManager? Thanks!

A: If you want you can create a wrapper for sessions in PHP. It actually could be beneficial, especially if your application later had to migrate to a cluster of servers and sessions would be moved to a distributed cache. Then, to facilitate this migration you would only have to provide different implementation if same Session class interface.
That said.
This code there itself is not a good OOP. You should stop using singletons. And, if you class require instances of DataMapper and DictationView, then they should be created outside the class and provided in the constructor. Instead of creating a tight coupling because you constructor is making other objects.

A: Now, what you refer to is not PHP but rather how a client-server architecture is being handled.
Here is a change, which assumes you manage the session correctly (with regard to session_start - should be in the bootstrap of your file)
I have also added some of topic corrections to your code, which will help u in the future:

    private function __construct()
    {
        $this->dataMapper = new DataMapper();
        $this->dictationView = new DictationView();
    }

    // The singleton method
    public static function singleton()
    {
        if(isset($_SESSION[self::MY_UNIQUE_IDENTIFIER] &&
           get_class($_SESSION[self::MY_UNIQUE_IDENTIFIER] == 'DataManager'){
                   self::$dm = $_SESSION[self::MY_UNIQUE_IDENTIFIER];
        }
        if (!self::$dm) {//LOOK HERE LOOK HERE!!!!!!!!!!!!!!!!!!!!
           $_SESSION[self::MY_UNIQUE_IDENTIFIER] = self::$dm = new self;
        }

        return self::$dm;
    }

    // Prevent users to clone the instance
    public function __clone()
    {
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }

    function __get($prop) {
        return $this->$prop;
        }

    function __set($prop, $val) {
        $this->$prop = $val;
        }
}
//LOOK HERE LOOK HERE no closing ?>

Some traps I did not address here as they are not the subject of this question:

*

*The right way to manage sessions

*Adjustment to the class to allow inheritance without trashing the session


text:
Q: Python Import Modules I am wondering why someone would like to import only specific classes or functions from a module. In other words:
why should I use the following:
from abc.xyz import fgh
from abc.uvw import jkl
from abc.klo import mno

if I can also just use:
import abc

I thought that if I import the abc module I should have access to everything that is inside, or am I wrong?
cheers

A: Recall that these modules are already written code files for performing specific tasks. Whenever I import a module, the compilers/interpreters take the code from that file and in a way append the code to my code (executable). Now lets say, The abc module is of 15 Kb and I only want to use the function xyz from it, then importing the whole 15kb would just be an overhead for my compiler/interpreter. That is why, a good practice is to import only specific functions/classes so that minimum work needs to be done while compiling or interpreting.

A: Think of a module like a namespace , so if you import abc , you will be able to use abc and refer to anything under abc with abc.something , but if you only import a specific thing from that namespace , for sure you have access to that specific name only in your code.


text:
Q: To have bibliography of Revtex along the text in two-columns I am thinking about having a heading for References, since I think it is needed in publications.
My minimum tex
\documentclass[twocolumn]{revtex4-1}
\usepackage{newunicodechar}
\usepackage{unicode-math}
\usepackage{multirow}

\begin{document}
\section{Methods}
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec gravida tellus sit amet eros varius, in blandit nibh vehicula. Vestibulum vel augue vitae erat posuere consequat. Cras nec suscipit dui. Sed laoreet tristique libero, quis consectetur leo tincidunt ut. Donec sodales rutrum est, at tempor eros laoreet eu. Aliquam vitae purus vel velit adipiscing dictum at nec turpis. Sed egestas feugiat eros, vel lacinia elit. Cras hendrerit erat vel suscipit adipiscing. Maecenas sed enim lacus. Aliquam suscipit dolor faucibus ornare elementum. Nam pretium, orci ac sagittis varius, odio est rutrum leo, sed adipiscing enim turpis vel lorem. Integer porttitor rutrum luctus. Duis vestibulum massa ante, non luctus enim tempor quis. Praesent condimentum fringilla fringilla. Nam eget sodales est, ultricies ullamcorper purus.

Nullam nisl erat, luctus nec libero et, faucibus suscipit massa. Suspendisse rhoncus laoreet ipsum eget posuere. Vivamus bibendum, dui vitae rhoncus sollicitudin, justo elit convallis felis, eget auctor nisi tellus non urna. Fusce semper ullamcorper sem. Nam enim enim, malesuada nec justo eget, pulvinar elementum purus. Suspendisse potenti. Quisque interdum ac diam tristique iaculis. Sed iaculis nisi vitae ipsum varius laoreet. Maecenas volutpat placerat facilisis. Sed eget arcu scelerisque, aliquet mauris nec, euismod ante. Nunc turpis velit, luctus et enim ut, lobortis scelerisque sapien. Cras ut aliquam dolor. Sed ac arcu eros. Nulla luctus egestas tincidunt. In eget quam dolor. Duis ut enim et justo vulputate tempor.

Etiam semper, justo sit amet elementum lacinia, enim lacus tincidunt lacus, eu pretium nulla arcu id nunc. Curabitur consequat tortor quam, vitae aliquam arcu tempor facilisis. Nam vehicula, mi et iaculis pulvinar, urna felis feugiat mi, eu tincidunt ante magna ac risus. Suspendisse id euismod velit. Nam in neque viverra lectus imperdiet mattis. Maecenas sapien erat, volutpat at feugiat ac, rhoncus tristique nunc. Sed sem dolor, blandit eu eleifend nec, rutrum at elit. Sed at metus eu sem blandit sollicitudin. Ut fermentum elit non ligula fermentum consequat. Maecenas pretium non lectus et tristique. Nunc suscipit, mi et placerat rutrum, nunc nisi rutrum massa, in malesuada leo massa non urna. Proin vulputate nunc a eleifend porta. Curabitur sit amet elit non est dictum pulvinar id id nunc. Cras ornare elit eget diam aliquam, in sagittis magna cursus.

Integer quis diam placerat, bibendum dui a, luctus ligula. Sed sit amet dolor vitae nulla pellentesque rhoncus. Nulla molestie purus vitae pharetra gravida. Nunc convallis hendrerit augue vel aliquet. Pellentesque ullamcorper diam enim, in condimentum nulla tincidunt in. Cras ac justo ac felis dictum ornare. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent vitae lorem varius, tincidunt ligula et, blandit nisl. Morbi posuere blandit elit sit amet porta. Sed ligula est, eleifend vel tempus a, dignissim at nunc. Sed fermentum nisi vel massa faucibus, ac pharetra turpis viverra. Nulla sit amet dolor rutrum, porta enim et, egestas justo. Maecenas eget varius turpis, eu placerat dui. Maecenas sit amet mollis nunc, quis volutpat orci.

\cite{berlin}

\section{References}
% if your bibliography is in bibtex format, use those commands:
\bibliographystyle{plain}
\bibliography{article}      % Bibliography file (usually '*.bib' )

\end{document}

My bibtex
%  article.bib
%
%  An example of bibtex entries.
%  Entries taken from BMC instructions for authors page.

% Article within a journal supplement
@ARTICLE{berlin,
    author  = {Radon P, Steinhoff U, von Wagner G, Kraft N},
    title   = {Quality evaluation of a pediatric ECG database for assessment of arrythmia detection algorithms in Automated External Defibrillators},
    journal = {Biomed Tech},
    year    = {2012},
    volume  = {57 (Suppl. 1)},
    issue = {Suppl. 1}

}

My output in print

How can you have the bibliography follow the main text?

A: Answer is in Alex's comment. Use the code instead
documentclass[prl]{revtex4-1}


text:
Q: Replace Text In Serialised PHP Object Bia PHPMYADMIN MariaDB SQL query I have come unstuck with a certain SQL query on a specific data set. Below is an example of the meta_value stored in the database:
a:1:{i:0;a:2:{s:11:"ingredients";a:7:{i:0;a:5:{s:6:"amount";s:1:"3";s:4:"unit";s:3:"cup";s:4:"name";s:23:"spring mix salad greens";s:5:"notes";s:0:"";s:2:"id";i:7263;}i:1;a:5:{s:6:"amount";s:1:"3";s:4:"unit";s:4:"unit";s:4:"name";s:28:"to 4 radishes, thinly sliced";s:5:"notes";s:0:"";s:2:"id";i:7264;}i:2;a:5:{s:6:"amount";s:1:"1";s:4:"unit";s:4:"unit";s:4:"name";s:60:"small orange or tangerine, peeled, seeded, and thinly sliced";s:5:"notes";s:0:"";s:2:"id";i:7265;}i:3;a:5:{s:6:"amount";s:5:"1⁄2";s:4:"unit";s:4:"unit";s:4:"name";s:46:"cucumber, scrubbed or peeled and thinly sliced";s:5:"notes";s:0:"";s:2:"id";i:7266;}i:4;a:5:{s:6:"amount";s:1:"1";s:4:"unit";s:10:"tablespoon";s:4:"name";s:9:"olive oil";s:5:"notes";s:0:"";s:2:"id";i:6785;}i:5;a:5:{s:6:"amount";s:1:"2";s:4:"unit";s:8:"teaspoon";s:4:"name";s:17:"fresh lemon juice";s:5:"notes";s:0:"";s:2:"id";i:6935;}i:6;a:5:{s:6:"amount";s:5:"1⁄2";s:4:"unit";s:8:"teaspoon";s:4:"name";s:4:"salt";s:5:"notes";s:0:"";s:2:"id";i:7215;}}s:4:"name";s:0:"";}}

I wish to replace the following portion:
s:4:"unit";s:4:"unit";

with
s:4:"unit";s:0:"";

However all my attempts completely change the entire value not just and instances of this value.
Any ideas?
I've tried the following but get the error #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''s:4:"unit")' at line 4
UPDATE
    `wp_postmeta`
SET
    `wprm_ingredients` =
REPLACE
    (
        'wprm_ingredients',
        's:4:"unit";s:4:"unit";',
        's:4:"unit";s:0:"";'
    )


text:
Q: Что лучше использовать для конвертации текста в форматы mobi, epub и т.д.? Стоит задача конвертации rss новостной ленты в форматы типа .mobi, .epub, .pdf и другие. Хочется написать всё красиво. Вопрос - есть ли какой-нибудь удобный модуль, который может с этим помочь?

A: Есть конвертер в .epub, но нужно будет установить Calibre
https://github.com/lazzarello/rss-epub-archiver


text:
Q: Edges states dispersion relation of gapped graphene I'm currently looking at this paper: Domain wall in gapped graphene. I do know how to get the dispersion relation of the gapped graphene without the domain wall. But according to this article, it seems possible to derive analytically  the dispersion relation of a infinite gapped graphene with a domain wall at $x=0$.
The schrodinger equation of this system reads:
\begin{equation}
(E-\text{sign}(x) \mu)a_A =t\sum_i b_{A+\vec{s}_i} \quad \text{and} \quad (E+\text{sign}(x) \mu)b_B =t\sum_i a_{B-\vec{s}_i}
\end{equation}
where $a_A$ ($b_B$) are the amplitude on the site of the sublattice A (resp. B).
The vectors $\vec{s_i}$ are just the usual link vectors of the graphene.
My question is the following: how can i get the dispersion relation given in equation (8) and (9-10) of the paper? What the trick?
Edit:
One idea I tried for the bulk dispersion was to square all the equation to get ride of the sign. And then I Fourier Transform the equation. The problem I run into at this point is that I get a sum over all wavevectors that I don't know how to remove...


text:
Q: JSON VOLLEY PARSING error Today i discovered really dumb problem.
Here is my mainactivity:
public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private CoinRecyclerViewAdapter coinRecyclerViewAdapter;
    private List<Coin> coinList;
    private RequestQueue queue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        queue= Volley.newRequestQueue(this);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        recyclerView=findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        coinList=new ArrayList<>();

        Prefs prefs = new Prefs(MainActivity.this);
        String search = prefs.getSearch();
        getCoins(search);

    }

    //get coins
    public List<Coin> getCoins(
            String searchTerm
    ){
        coinList.clear();
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                Constants.URL_LEFT
                //searchTerm+Constants.URL_RIGHT
                , new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {

                    JSONArray coinsArray=response.getJSONArray("data");

                    for (int i = 0; i < coinsArray.length(); i++){

                        JSONObject coinObj = coinsArray.getJSONObject(i);

                        Coin coin = new Coin();
                        coin.setName(coinObj.getString("name"));
                        coin.setSymbol(coinObj.getString("symbol"));
                        coin.setPrice(coinObj.getDouble("price"));
                        coin.setRank(coinObj.getInt("rank"));
                        coin.setPercentChange24h(coinObj.getDouble("percent_change_24h"));
                        coin.setMarketCap(coinObj.getDouble("market_cap"));
                        //coin.setPriceBtc(coinObj.getFloat("price_btc"));
                        coin.setTotalSupply(coinObj.getLong("total_supply"));
                        Log.d("kreten","kreten");
                        Log.d("coins:",String.valueOf(coin.getPrice()));

                    }

                }catch (JSONException e){
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(jsonObjectRequest);
        return coinList;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

I need to parse data from this api to my application
https://api.coinmarketcap.com/v2/ticker/
I found problem when tried to compile and get data from json object but when i tried Log.d("Coins",coin.getName());
i don't get any names i get this
Value: and whole json data
(that is not what i wanted , i need only names so i think i made mistake in MainActivity where i try to grab "data" object i think i am getting it but i don't get full objects because i think i need code to read random numbers above coins id in api or below "data"
So my question is how to get price,rank ,symbol etc from api i think i made mistake here :

  //get coins
    public List<Coin> getCoins(
            String searchTerm
    ){
        coinList.clear();
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                Constants.URL_LEFT
                //searchTerm+Constants.URL_RIGHT
                , new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {

                    JSONArray coinsArray=response.getJSONArray("data");

                    for (int i = 0; i < coinsArray.length(); i++){

                        JSONObject coinObj = coinsArray.getJSONObject(i);

                        Coin coin = new Coin();
                        coin.setName(coinObj.getString("name"));
                        coin.setSymbol(coinObj.getString("symbol"));
                        coin.setPrice(coinObj.getDouble("price"));
                        coin.setRank(coinObj.getInt("rank"));
                        coin.setPercentChange24h(coinObj.getDouble("percent_change_24h"));
                        coin.setMarketCap(coinObj.getDouble("market_cap"));
                        //coin.setPriceBtc(coinObj.getFloat("price_btc"));
                        coin.setTotalSupply(coinObj.getLong("total_supply"));
                        Log.d("kreten","kreten");
                        Log.d("coins:",String.valueOf(coin.getPrice()));

                    }

Thanks guys for time to help me.
p.s. my second question doesn't belongs here but i don't know why i can not compile android when i import PICASSO LIBARY ,, really strange thing...
If someone wanna join me on project message me here or on skype: drvenapila

A: Your line
 JSONArray coinsArray=response.getJSONArray("data");

..wants to parse the data object as an array.
If we look at the first lines of the JSON response from coinmarketcap.com/v2/ticker we see
{
"data": {
    "1": {
        "id": 1,
        "name": "Bitcoin",
        "symbol": "BTC",
        "website_slug": "bitcoin",
        "rank": 1,

..but if it was an array, it would go like "data": [ {
"data" instead contains a Map<String,Object> where the Keys are the current ranking of the coin. E.g. 1 : Bitcoin, 2 : Ethereum, 3 : Ripple
So what you probably want is to get this Map out of "data" and then get the Object for each key(s) you desire.
This may help you: Convert JSON to Map
Trivia:
Funny how each Coin-Object has an "id" which matches the keys of the map.. Indeed one would expect an array here.


text:
Q: There's no getPath() or getPaths() function for polygons in a data layer I'm creating an array of polygons in Google Maps using the loadGeoJson method. I'm making one of the polygons editable. I want to add a listener when a vertice is edited/added.
If I had used the Polygon class, I could have added the listener set_at to its path(s), according to the documentation:

The listener must be set on the polygon's path. If the polygon has multiple paths, a listener must be set on each path.

Which means that in the Polygon class it can be done like this:
let polygon = new google.maps.Polygon({ ...options here ...})
let outerPath = polygon.getPath();
google.maps.event.addListener(outerPath, 'set_at', function() {
  console.log('Vertex moved on outer path.');
});

However, when the polygons are loaded using loadGeoJson, they are considered as features in the Data layer, but the Data.Feature class does not have a getPath method. How can I add the set_at listener to a Polygon in the Data.Feature class?
The geojson that is being loaded looks like this:
{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"name":"Test zone"},"geometry":{"type":"Polygon","coordinates":[[[28.29,70.46],[28.34,70.45],[28.37,70.47]]]},"id":"10"}]}


text:
Q: Bootstrap Dropdown Incorrectly Highlighting In the image below if you look to where arrow is pointing you can see a very small sliver of the navbar that does not get 'highlighted' when the dropdown is opened. I've never seen this before and have no clue what's causing it, and if someone could provide a fix while explaining why it happens that would be fantastic. Here is a JSFiddle.

Navbar Code

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                Toggle navigation

            </button>

                @if(!Auth::check())

                @else

                        {{ Auth::user()->username }}avatar }}">

Dashboard

Settings

Logout

                @endif

CSS
.navbar {
    margin-bottom: 0;
    height: 70px;
}
.navbar-default {
    background-color: #383838;
    border-color: #383838;
}
/* title */
.navbar-default .navbar-brand {
    color: #777;
}
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus {
    color: #5E5E5E;
}
/* link */
.navbar-default .navbar-nav > li > a {
    color: #8D8D8D;
    font-family: Open Sans;
    font-size: 14px;
}
.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
    color: #8D8D8D;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
    color: #6C6C6C;
}
.navbar-default .navbar-nav > .open > a,
.navbar-default .navbar-nav > .open > a:hover,
.navbar-default .navbar-nav > .open > a:focus {
    color: #6C6C6C;
    background-color: #2E2E2E;
}

.navbar-avatar {
    width: 45px;
    height: 45px;
    position: relative;
    float: right;
    top: -4px;
    margin-left: 8px;
    margin-right: 8px;
}

.navbar-user {
    padding: 0;
    margin: 0;
    display: inline-block;
    padding-top:7px;
}

.navbar-steam {
    position: relative;
    float: right;
    top: 8.6px;
    margin-right: 8px;
}

.navbar-nav > li > a {
    padding-top: 15px;
    padding-bottom: 25px;
}

A: Here's an updated Fiddle:
https://jsfiddle.net/tobyl/Laaej9ya/
The only change I made was:
.navbar {
    margin-bottom: 0;
    height: 68px;
}

The height of .navbar and the height of the elements controlling the position of the dropdown were slightly different.


text:
Q: how to define operator overloads without overwriting existing operators How can basic operators like (+, -, *) be overloaded without overwriting their existing definitions? Reading some of the other threads on this topic I couldn't get a sense of what to do. Specifically, I am looking to define matrix operations directly on Array2D types. MathNet.Numerics somehow manages to do it for its Matrix and Vector types but not sure how. Defining regular functions instead of using operators completely fubars logic in linear algebra heavy applications.
type Array() =
    static member (+) (A : float[,], B : float[,]) =
        let r = A.GetLength 0
        let c = A.GetLength 1
        let C = Array2D.create r c 0.
        for i in 0..r-1 do
            for j in 0..c-1 do
                C.[i, j] <- A.[i, j] + B.[i, j]
        C

let a1 = Array2D.create 4 4 1.
let a2 = Array2D.create 4 4 1.
let a3 = a1 + a2   // type float[,] does not support the operator '+'
let y = 2 + 3      // don't want this overridden by something like a 'let inline...'

A: MathNet.Numerics shouldn't have much problem doing that if they provide operators for their own types, as part of their definition.
What you're trying to do is to provide an operator using an extension method - I don't think that's currently possible.
The easiest way out is to provide a slightly different operator, let's say +., so that there's no clashing, but the code still remains fairly easy to follow. This is what OCaml does to differentiate between int and float operators for instance (and F# gives you much room in picking symbols for custom operators).
let inline (+.) (A: float[,]) (B: float[,]) =
    ...

let a3 = a1 +. a2

There are other solutions - you could use a single case union to wrap the 2D arrays and define the operator as a member of that type, or you could make use of SRTPs to patch the operator onto an existing type and have it inlined at compile time, but going that way would also obscure the logic in one way or another.


text:
Q: String word count without using regex? I'm trying to figure out an effective way to do a word count for a given string in JavaScript, without the use of regex.
The following works for some strings:
function wordCount(str) {
  return str.split(" ").length;
}

console.log(wordCount("howdy there partner"));

However - when given a string like, " this is an example " the word count goes to 6 instead of 4. Additionally, this approach will not work for empty strings, like "" or " " (will return a word count of 1 and 2, respectively).
Is there any way to do an accurate word count for these instances, without the use of regex?

A: Just filter out blank values:
function wordCount(str) {
    return str.split(' ').filter(function(val){ return val != '' }).length
}

A: If you are willing to relax your limitation on using regexp, you can do this directly, without using split:
sentence.match(/\w+/g).length

This means match any sequence of characters (\w) with a length of one or more (+), globally (g). It will return an array of matches, the length of which will give the number of words.
In order to protect against the case where there are no words in the string, and match will return null, you should actually write:
(sentence.match(/\w+/g) || []).length

which is still a few characters shorter than the alternative
sentence.split(' ').filter(Boolean).length

in case you worry about such things.

A: function wordCount(str) {
  return str.trim().split(" ").length;
}

console.log(wordCount("howdy there partner"));


text:
Q: Rectification of 601 network error in sim900a GSM I am working with gsm SIM900a module and trying to send data to web server through that. Everything works fine. For every HTTP commands I am getting response as OK. But when it comes to AT+HTTPACTION=1 , it is giving me result as 1,601,0.
I tried to increase delay time between the commands and also the timeout.
 Serial.println("HTTP post method :");

Serial.print("AT\\r\\n");

  SIM900.println("AT");

  delay(5000);

  ShowSerialData();

  delay(5000);

  Serial.print("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"\\r\\n");

  SIM900.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");

  delay(5000);

  ShowSerialData();

  delay(5000);

  Serial.print("AT+SAPBR=3,1,\"APN\",\"internet\"\\r\\n");

  SIM900.println("AT+SAPBR=3,1,\"APN\",\"internet\"");

  delay(5000);

  ShowSerialData();

  delay(5000);

  Serial.print("AT+SAPBR=1,1\\r\\n");

  SIM900.println("AT+SAPBR=1,1");

  delay(5000);

  ShowSerialData();

  delay(5000);

  Serial.print("AT+SAPBR=2,1\\r\\n");

  SIM900.println("AT+SAPBR=2,1");

 delay(5000);

  ShowSerialData();

  delay(5000);

  Serial.print("AT+HTTPINIT\\r\\n");

  SIM900.println("AT+HTTPINIT");
  delay(5000);

  ShowSerialData();

  delay(5000);

  Serial.print("AT+HTTPPARA=\"CID\",1\\r\\n");

  SIM900.println("AT+HTTPPARA=\"CID\",1");

  delay(10000);

  ShowSerialData();

  delay(10000);

After this I am giving the AT+HTTPPARA and passing the URL:
Serial.print("AT+HTTPDATA=100,30000\\r\\n");

  SIM900.println("AT+HTTPDATA=100,30000");

  delay(10000);

  ShowSerialData();

  delay(10000);

  Serial.print("{\"temperature\":\"20.00\" ,\"humidity\":\"10.00\" , \"recordedTime\":[2019-08-12,01:25:00] , \"latitude\":\"15.67\" , \"longitude\":\"50.00\" , \"deviceId\":\"1\" , \"macAddress\":\"A\"}");
  SIM900.println("{\"temperature\":\"20.00\" ,\"humidity\":\"10.00\" , \"recordedTime\":[2019-08-12,01:25:00] , \"latitude\":\"15.67\" , \"longitude\":\"50.00\" , \"deviceId\":\"1\" , \"macAddress\":\"A\"}");

  delay(10000);

  ShowSerialData();

  delay(10000);

  Serial.print("AT+HTTPACTION=1\\r\\n");

  SIM900.println("AT+HTTPACTION=1");

  delay(10000);

  ShowSerialData();

  delay(10000);

  Serial.print("AT+HTTPTERM\\r\\n");

  SIM900.println("AT+HTTPTERM");

  delay(5000);

  ShowSerialData();

  delay(5000);

  Serial.print("AT+SAPBR=0,1\\r\\n");

  SIM900.println("AT+SAPBR=0,1");

  delay(5000);

  ShowSerialData();

  delay(5000);


text:
Q: How to group by columns with sparse data in R's ggplot2 I am working with a data.frame (df) in R like
  A  B G1 G2 G3
1 1  6  0  1  0
2 2  7  0  1  1
3 3  8  1  1  0
4 4  9  0  0  1
5 5 10  1  1  1

Columns A and B are just continuous and numeric. G1, G2, and G3 are categories for each row, where a 0 indicates that row is not in that category and a 1 indicates that row is in that category. Obviously, a row may be in multiple categories.
I want to use ggplot2 (geom_point) to make scatter plots that are color coded by G1:G3 categories or grouped in some other way by G1:G3. I have no clue how to do this. I am currently plotting A vs B using the following code:
ggplot(df, aes(x = A, y = B)) + geom_point()

I currently have no clue how to incorporate my categories in G1:G3.

A: You can also set the categories to factors in a data.table. Then set shape or color to a factor and your ggplot will illustrate the category:
library(data.table)

a <- c(1,2,3,4,5)
b <- c(6,7,8,9,10)
G1 <- c(0,0,1,0,1)
G2 <- c(1,1,1,0,1)
G3 <- c(0,1,0,1,1)

cc <- data.table(a,b,G1,G2,G3)
cc[,G1 := as.factor(G1)][,G2 := as.factor(G2)][,G3 := as.factor(G3)]

ggplot(cc)+
  geom_point(aes(a, b, color = G1, shape = G2), size = 4)

So, the color (red or blue) displays the value for the G1 category while the shape (diamond or triangle) displays the value of the G2 category. You can manipulate this many ways.

A: There are 2 ways I will suggest, the first is the simple case where the only missing value in your code is to set the aesthetic color to one of your categories.  In this case you will create a ggplot for each category.
set.seed(1)
A <- rnorm (20)
B <- rnorm (20)
G <- matrix(sample(c(0,1), replace=TRUE, 60), 20, 3)

df <- cbind.data.frame(A, B, G)
colnames(df) <- c("A", "B", "G1", "G2", "G3")
head(df)
# A           B G1 G2 G3
# 1 -0.6264538  0.91897737  0  1  1
# 2  0.1836433  0.78213630  1  0  0
# 3 -0.8356286  0.07456498  0  0  0
# 4  1.5952808 -1.98935170  0  1  0
# 5  0.3295078  0.61982575  1  1  1
# 6 -0.8204684 -0.05612874  0  0  0

# Note colour = factor(G1) to get categorical, if colour = G1 get continuous
gg_point <- ggplot(df, aes(x = A, y = B, colour=factor(G1))) + geom_point()
gg_point

# Example on how to edit the legend values
G1_legend <- scale_colour_discrete("G1")
G2_legend <- scale_colour_manual("G1", values=c("blue", "red"), labels=c("non-member", "member"))

gg_point + G1_legend
gg_point + G2_legend

# you can use grid.arrange to plot all categories together once you create them
grid.arrange(gg_point_G1, gg_point_G2, gg_point_G3, ncol=3) # or nrow = 3

The second approach reshapes the data by combining categories into a variable, and uses facets to separate plots by category variable
library(reshape2)
df.melt <- melt(df, id.vars=c("A", "B"))
head(df.melt)
# A           B variable value
# 1 -0.6264538  0.91897737       G1     0
# 2  0.1836433  0.78213630       G1     1
# 3 -0.8356286  0.07456498       G1     0
# 4  1.5952808 -1.98935170       G1     0
# 5  0.3295078  0.61982575       G1     1
# 6 -0.8204684 -0.05612874       G1     0

gg_point2 <- ggplot(df.melt, aes(x = A, y = B, colour=factor(value))) + geom_point() + facet_wrap(~ variable)


text:
Q: How change tables's schema of Identity Server 4? By default the  tables's schema of Identity Server 4 is dbo, i want change it to security, so i create ConfigurationContext which inherit from ConfigurationDbContext:
 public class ConfigurationContext : ConfigurationDbContext
 {
    public ConfigurationContext(DbContextOptions<ConfigurationDbContext> options, ConfigurationStoreOptions storeOptions) : base(options, storeOptions)
    { }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.HasDefaultSchema("Security");
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var relationalOptions = RelationalOptionsExtension.Extract(optionsBuilder.Options);
        relationalOptions.MigrationsHistoryTableSchema = "Security";
    }

  }

and in add-migration i use ConfigurationContext :
Add-Migration -c ConfigurationContext

but i got this error:

No parameterless constructor was found on 'ConfigurationContext'. Either add a parameterless constructor to 'ConfigurationContext' or add an implementation of 'IDbContextFactory' in the same assembly as 'ConfigurationContext'.

what is the problem?

A: IdentityServer4 provides this option. In ConfigureServices,
services.AddIdentityServer()
.AddOperationalStore(builder => builder.UseSqlServer(cnStr, options =>
                        options.MigrationsAssembly(migAssembly)),
                        storeOption => storeOption.DefaultSchema = "security")

This way, you can continue to use the IDbContextFactory as suggested in the quickstarts.

A: I know this is quite an old question, but I recently had a similar issue; June Lau's answer does provide some of the info you need to resolve this, but the important part is that migrations don't inspect the database context at runtime, so you need to define the schema before you create your database migration.
Don't worry about extending ConfigurationDbContext either, as that's not needed, just add something like this to your ConfigureServices method in Startup.cs:
var identityServerBuilder = services.AddIdentityServer(options =>
{
    // ...
});

var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
identityServerBuilder.AddConfigurationStore(options =>
{
    options.DefaultSchema = "config";
    options.ConfigureDbContext = b => b.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));
});

Once you've added that code, create a migration for the relevant database context:
Add-Migration CreateInitialSchema -Context ConfigurationDbContext

You should see that the created migration starts like this:
protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.EnsureSchema(
        name: "config");

    migrationBuilder.CreateTable(
        name: "ApiResources",
        schema: "config",
        columns: table => new ...

A: The problem is that Add-Migration -c ConfigurationContext command does not startup your application and thus does not know how to resolve the classes in your constructor:
   public ConfigurationContext( //How do i resolve this, i dont know?
        DbContextOptions<ConfigurationDbContext> options,
        ConfigurationStoreOptions storeOptions)
        : base(options, storeOptions)
   { }

You need to add a parameterless constructor, as the error suggests:
public ConfigurationContext()
    : base(/* todo default static logic here */)
{ /* and here */ }

Why
The database migration tries to create an instance of the ConfigurationContext to determine the 'desired' state (the state you want your database to be after the database migration has been executed).
This migration is a static file inside your project saying which Columns and which indexes etc need to be added or removed to the database to create the 'desired' state.
This Add-Migration command simply reflects your code to find the right context, it does not go through your startup class to see which dependencies you have the find (this would become way to complex since there could also be runtime dependencies or dependencies based on App-settings, etc)


text:
Q: Node addon using libuv and uv_async_send -- node process doesn't exit I have a requirement to invoke a Javascript function from a node addon. The addon will have a background thread that runs continuously, so it's not quite the classic async worker requirement using async_queue_work. I think uv_async_send is more appropriate in this scenario. I want to place a function on the node event loop to be executed as soon as node is free. This function should run in the main node thread.
To get started I have a very simple addon and I'm experimenting with uv_queue_work vs uv_async_send. I can get both to work but in the case of uv_async_send, the node process never exits.
node-uv.cc
#include <node.h>
#include <uv.h>

using namespace v8;

static void Runner(uv_work_t *req)
{
    printf("Async work running!\n");
}

static void RunDone(uv_work_t *req, int status)
{
    delete req;
    printf("Async work done!\n");
}

static void Runner2(uv_async_t* handle) {
    printf("Got async send!\n");
}

void Start(const FunctionCallbackInfo<Value>& args)
{
    printf("In run async\n");

    Isolate* isolate = Isolate::GetCurrent();
    HandleScope scope(isolate);

    uv_work_t *req = (uv_work_t*)malloc(sizeof(uv_work_t));

    /// Example using uv_queue_work (working fine)
    printf("Queue work\n");
    uv_queue_work(uv_default_loop(), req, &Runner, &RunDone);

    uv_async_t *handle = (uv_async_t*)malloc(sizeof(uv_async_t));
    uv_async_init(uv_default_loop(), handle, &Runner2);

    /// Example using uv_async_send (node does not terminate)
    printf("Async send\n");
    uv_async_send(handle);
}

void Init(Handle<Object> exports, Handle<Object> module)
{
    NODE_SET_METHOD(exports, "start", Start);
}

NODE_MODULE(node_uv, Init)

output
$ node test
calling addon
In run async
Queue work
Async send
Async work running!
called addon
Got async send!
Async work done!

(process doesn't quit at this point)
The full example project is here: https://github.com/jugglingcats/node-uv
Any help much appreciated.

A: The problem was I didn't call uv_close!! Had to be something simple.
fixed up callback method
static void Runner2(uv_async_t* handle) {
    printf("Got async send! %d\n", n++);
    uv_close((uv_handle_t *)handle, NULL);
}

Relevant docs: https://nikhilm.github.io/uvbook/threads.html
Fixed github project: https://github.com/jugglingcats/node-uv/tree/working


text:
Q: Highlight a property/variable when its value gets changed during debugging Is it possible when debugging to set a watch on a property or variable, and then have the debugger highlight the line where the value is changed.
I've had a situation where I spent ages going through the code trying to find in which line of code the variable had its value updated.
Thanks

A: In C++, use Data Breakpoints. In C#/VB.NET, this option is not possible. The best you can do is put a breakpoint on the property's setter, and if it a field or an auto property, turn it into a regular property with backing field, and then put a breakpoint on it.
Resharper has a wonderful feature called "Value Tracking" (accessible through Ctrl+Alt+Shift+A) which automates the process of finding where a variable had its value updated, and does so in a second, so if there aren't too many such places, you could just quickly flip through them (with Ctrl+Alt+Pageup/Pagedown) and set a breakpoint in each.