text:
Q: Example of two homeomorphic spaces without a continuous deformation between them? on wikipedia it states:

there need not be a continuous deformation for two spaces to be homeomorphic — only a continuous mapping with a continuous inverse function.

I'm trying to intuitively understand this difference between a continuous mapping and continuous deformation, so I'm trying to find an example of two spaces that are homeomorphic but without a continuous deformation.
Here is a definition of homotopy:

Formally, a homotopy between two continuous functions f and g from a topological space X to a topological space Y is defined to be a continuous function H : X × [0,1] → Y from the product of the space X with the unit interval [0,1] to Y such that, if x ∈ X then H(x,0) = f(x) and H(x,1) = g(x)

Does the following example satisfy?

In a sense there is no continuous deformation between the two (though I honestly cannot immedately see from the definition why not. i.e. I cannot see why simply letting the different parts of the knot "move through" each other is not allowed by the formal definition of homotopy.)

A: $\newcommand{\Reals}{\mathbf{R}}$Since this has gotten bumped:
tl; dr: Comparing homeomorphism (a relation between two topological spaces) and homotopy (a relation between two mappings) is a recipe for confusion. Informal, qualitative descriptions of topology do not help, since they frequently use language such as "continuous deformation", which can be interpreted in either sense.

Let $X$ and $Y$ be topological spaces, and let $f$, $g:X \to Y$ be continuous mappings.
Homeomorphism: A mapping $f:X \to Y$ is a homeomorphism if $f$ is continuous and invertible, and its inverse is continuous. If there exists a homeomorphism $f:X \to Y$, we say the topological spaces $X$ and $Y$ are homeomorphic.
Homotopy: In the loosest sense, two continuous mappings $f$ and $g:X \to Y$ are homotopic if there exists a continuous mapping $H:X \times [0, 1] \to Y$ such that $H(x, 0) = f(x)$ and $H(x, 1) = g(x)$ for all $x$ in $X$.
(For technical reasons, it's usually desirable to fix a "basepoint" in each topological space and to assume all mappings send basepoints to basepoints, or in fancy terms to work in the category of pointed spaces. Since the aim here is merely to formalize qualitative descriptions of topology for posterity, we'll ignore basepoints.)
Isotopy: Along the lines of Paul Frost's comment, we can combine these two concepts. First, we say a mapping $f:X \to Y$ is an embedding if $f$ is a homeomorphism onto its image, i.e., an injective mapping with continuous inverse.
If $f$ and $g:X \to Y$ are embeddings, we say $f$ and $g$ are isotopic, or homotopic through embeddings, if there exists a homotopy $H:X \times [0, 1] \to Y$ such that for each $t$ with $0 \leq t \leq 1$, the mapping $H_{t} = H( \cdot, t):X \to Y$ is an embedding.

Let's see how these concepts differ.

*

*The identity mapping $I_{X}:X \to X$ is a homeomorphism. Every mapping $f:X \to Y$ is homotopic to itself. Every embedding $f:X \to Y$ is isotopic to itself. A non-embedding $f:X \to Y$ is not isotopic to anything, because the definition above makes no sense for non-embeddings.

*Any two mappings $f$, $g:X \to \Reals^{n}$ into a Cartesian space are homotopic (because we are working with "unpointed" spaces). The standard argument is to use the straight line homotopy
$$
H(x, t) = (1 - t)f(x) + tg(x) = f(x) + t(g(x) - f(x)),
$$
which connects the points $f(x)$ and $g(x)$ by a line segment, and then simultaneously "deforms" along these segments as $t$ runs from $0$ to $1$.

*Let $X$ denote the unit circle, which we'll represent as the set of points $(x, y) = (\cos\theta, \sin\theta)$ in the Cartesian plane.

*

*The antipodal mapping $g(x, y) = (-x, -y)$ is a homeomorphism of the circle to itself, hence an embedding. The mapping
$$
H((x, y), t) = (x\cos\pi t - y\sin\pi t, x\sin\pi t + y\cos\pi t),
$$
which rotates the circle counterclockwise through angle $\pi t$, is an isotopy from the identity to the antipodal mapping.

*The reflection mapping $g(x, y) = (x, -y)$ is a self-homeomorphism of the circle, but turns out not to be homotopic (much less isotopic) to the identity. To prove this, we need some "homotopy invariant" of mappings, some number or other mathematical structure associated to a continuous mapping in a way that homotopic mappings have the same invariant, and so that these mappings have different invariants. Doing so is beyond the scope of this answer, but a standard choice is winding number. Intuitively, the identity mapping "winds $+1$ times" (i.e., once counterclockwise) while $g$ winds $-1$ times (once clockwise).

*The inclusion mapping of the circle into the plane $\Reals^{2}$ and the reflection mapping of the circle into the plane are homotopic as mappings into the plane. Indeed, Point 2. above guarantees that any two mappings $f$, $g:X \to \Reals^{2}$ are homotopic. One point is, whether or not two mappings are homotopic depends on the "ambient space" $Y$.

*The trefoil knot, which may be parametrized by
$$
  G(\theta) = \frac{1}{1 + r_{2}\sin 3t}{(r_{1}\cos2\theta, r_{1}\sin 2\theta, r_{2}\cos 3\theta)},\ r_{1}^{2} + r_{2}^{2} = 1,
  $$
is the image of an embedding $g$ of the circle into $\Reals^{3}$. (The mapping $G$ is continuous in $\theta$, and injective as a mapping on the circle, since two values of $\theta$ map to the same location if and only if they differ by an integer multiple of $2\pi$. Since the circle is compact, the inverse mapping $g^{-1}$ is continuous.) By Point 2., any two embeddings of the circle into $\Reals^{3}$ are homotopic. Particularly, the mapping $f(x, y) = (x, y, 0)$ and mapping $g$ from the circle to the trefoil are homotopic. It turns out, however, that these mappings are not isotopic. To prove this, we would need an isotopy invariant of mappings that can distinguish the unknot from the trefoil knot.

The proper notion of topological equivalence depends on context, and quickly becomes subtle even in situations, such as a plane circle and a trefoil knot, that appear qualitative and simple.

*

*As topological spaces the circle and the trefoil are homeomorphic. In this sense, the circle and trefoil knot are "topologically equivalent".

*As mappings of the circle into $\Reals^{3}$, the circle and trefoil are homotopic, i.e., "deformable into each other through continuous mappings".

*As embeddings of the circle into $\Reals^{3}$, the circle and trefoil are not isotopic, i.e., "cannot be deformed into each other" through embeddings.


text:
Q: Gaussian Mixture Models: Difference between Spark MLlib and scikit-learn I'm trying to use Gaussian Mixture models on a sample of a dataset.
I used bothMLlib (with pyspark) and scikit-learn and get very different results, the scikit-learn one looking more realistic.
from pyspark.mllib.clustering import GaussianMixture as SparkGaussianMixture
from sklearn.mixture import GaussianMixture
from pyspark.mllib.linalg import Vectors

Scikit-learn:
local = pd.DataFrame([ x.asDict() for x in df.sample(0.0001).collect() ])
model1 = GaussianMixture(n_components=3)
model1.fit([ [x] for x in local['field'].tolist() ])

model1.means_
array([[7.56123598e+00],
   [1.32517410e+07],
   [3.96762639e+04]])

model1.covariances_
array([[[6.65177423e+00]],
   [[1.00000000e-06]],
   [[8.38380897e+10]]])

MLLib:
model2 = SparkGaussianMixture.train(
    sc.createDataFrame(local).rdd.map(lambda x: Vectors.dense(x.field)),
    k=3,
    convergenceTol=1e-4,
    maxIterations=100
)

model2.gaussians
[MultivariateGaussian(mu=DenseVector([28736.5113]), sigma=DenseMatrix(1, 1, [1094083795.0001], 0)),
 MultivariateGaussian(mu=DenseVector([7839059.9208]), sigma=DenseMatrix(1, 1, [38775218707109.83], 0)),
 MultivariateGaussian(mu=DenseVector([43.8723]), sigma=DenseMatrix(1, 1, [608204.4711], 0))]

However, I'm interested in running the entire dataset through the model which I'm afraid would require parallelizing (and hence use MLlib) to get results in finite time. Am I doing anything wrong / missing something?
Data:
The complete data has an extremely long tail and looks like:

whereas the data has a clearly normal dist ceneterd somewhere closer to one clustered by scikit-learn:

I am using Spark 2.3.0 (AWS EMR).
Edit: Initialization params:
local = pd.DataFrame([ x.asDict() for x in df.sample(0.0001).collect() ])
model1 = GaussianMixture(n_components=3, init_params='random')
model1.fit([ [x] for x in local['field'].tolist() ])

model1.means_
array([[2.17611913e+04],
   [8.03184505e+06],
   [7.56871801e+00]])

model1.covariances_
rray([[[1.01835902e+09]],
   [[3.98552130e+13]],
   [[6.95161493e+00]]])

A: This isn't a python problem, per se. It seems to be more of a machine learning/data validation/data segmentation question, IMO.  That being said, you are correct in thinking that you must parallelize your work, but it matters in what ways you do it.  There are things like 8-bit quantization and model parallelism in your model that you may look into to help you get at what you're after: training a model on large datasets, in a timely manner, without sacrificing data quality or fidelity.
Here is a blog post about quantization: https://petewarden.com/2016/05/03/how-to-quantize-neural-networks-with-tensorflow/
Here is a blog post about model parallelism and 8-bit quantization from Tim Dettmers' Blog: http://timdettmers.com/2017/04/09/which-gpu-for-deep-learning/
and the associated paper: https://arxiv.org/pdf/1511.04561.pdf
Though you will want to keep in mind that, depending on FP operations on your GPU, you may not see substantial benefit from this route: https://blog.inten.to/hardware-for-deep-learning-part-3-gpu-8906c1644664
HTH and YMMV.
Also, you may want to look into data folding, but can't remember the details nor the paper I read at this point in time.  I'll land this here to remember once I do though.

A: I really don't know which type of EM alghoritm is used in scikit-learn or in Spark, but i know for sure that if they use SEM (Stochastic Expectation Maximiztion), it should coverge faster than EM. (see this).
However multiple starting techinque is always suggested to avoid saddle points or local maxima.
I really don't understand your plots, they are on different scale, is the second a zoom in of the first? By the way, i suggest you to choose the number of k by BIC (Bayesian Information Criterion) and to choose the number of components by this measure.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I 'm storring a value in localstorage and trying to use it in an if statement but i get only null, i have stringify the value too This is where I set the value to the localstorage. I get the
data-rel after click and pass it to the localstorage stringified.
var selectedClass = "";
var firstClass = "";
$(".months a").click(function(){
  firstClass = $(this).attr("data-rel");
  localStorage.setItem("firstClass ", JSON.stringify(firstClass) );
});

This is where I get the value back from the localstorage.
var check = "";
var test2 = localStorage.getItem("firstClass");
check = JSON.parse(test2);

And here is when I try to use it but it returns always null so my script
never runs else.
if (check === null) {
selectedClass = "";
    $(".fil-cat").click(function(){
        selectedClass = $(this).attr("data-rel");
     $("#produstswide").fadeTo(100, 0.1);
        $("#produstswide div.fluid-
conteiner").not("."+selectedClass).fadeOut().removeClass('scale-anm');
    setTimeout(function() {
      $("."+selectedClass).fadeIn().addClass('scale-anm');
      $("#produstswide").fadeTo(300, 1);
    }, 300);

    });
} else {
    selectedClass = check;
     $("#produstswide").fadeTo(100, 0.1);
        $("#produstswide div.fluid-
conteiner").not("."+selectedClass).fadeOut().removeClass('scale-anm');
    setTimeout(function() {
      $("."+selectedClass).fadeIn().addClass('scale-anm');
      $("#produstswide").fadeTo(300, 1);
    }, 300);
    localStorage.clear();
}

A: There is a white space in the key string that you use to set the value
localStorage.setItem("firstClass ", JSON.stringify(firstClass) );

Try removing it
localStorage.setItem("firstClass", JSON.stringify(firstClass) );


text:
Q: String to double and using IsNaN I have a variable defined as String,
String totalweight;

This might take values '0.00','0.12'...any deciamls and also will have 'n/a' occasionally.
Now I have to format this field in such a way that if its not a number eg: 'n/a' leave it as such else format them like below.
public String getFmtWeight()
    {
          NumberFormat nf = NumberFormat.getNumberInstance();
          DecimalFormat df = (DecimalFormat)nf;
          df.applyPattern("#0.00");
          if(Double.isNaN(Double.parseDouble(totalweight)))
              return totalweight;
          else
              return df.format(Double.parseDouble(totalweight));

//        if(!totalweight.equals("n/a"))
//            return df.format(Double.parseDouble(totalweight));
//        else
//            return "n/a";

    }

This is breaking when n/a is cast to double throws exception. However commented portion would work. But I do not want to use it since 'n/a' may change in future with different string. Is there anyother way to achieve the same ?

A: One solution would be to use a try-catch to account for when parsing the string as a double fails, e.g.:
public String getFmtWeight()
    {
          NumberFormat nf = NumberFormat.getNumberInstance();
          DecimalFormat df = (DecimalFormat)nf;
          df.applyPattern("#0.00");

          try {
              if(Double.isNaN(Double.parseDouble(totalweight)))
                  return totalweight;
              else
                  return df.format(Double.parseDouble(totalweight));

          } catch ( NumberFormatException ex ) {
              /* thrown when the String can't be parsed as a double */
              return totalweight; // if 'totalweight' is the String you want to parse
          }
    }

This will handle any string that cannot be parsed into a double using parseDouble.

A: You can use regular expression to validate.
NumberFormat nf = NumberFormat.getNumberInstance();
    DecimalFormat df = (DecimalFormat)nf;
    df.applyPattern("#0.00");
    String totalweight = "n/a";

    String pattern = "[0-9]*.[0-9]*";

    boolean isNan = Pattern.matches(pattern, totalweight);
    if(!isNan)  {
        System.out.println(totalweight);
    }
    else {
        System.out.println(df.format(Double.parseDouble(totalweight)));
    }

You can try this code


text:
Q: web parts in asp.net mvc This might be the most trivial question asked, but I raise it again. Am planning to get started with asp.net MVC on a personal project and here am struck if it supports webparts or any other alternative to it is present. I intend to have a start page similar to igoogle or pageflakes, but my initial research pointed out that as there's no ViewState nor Postback concepts in ASP.NET MVC implementing web parts is not possible.
If that is the case, are there any resources which helps in building a start page as the one i wish to using MVC.
PS: Links I found in the initial research

*

*Quick tips on asp.net MVC -
webparts framework

*Building widgets using jquery in
asp.net MVC

A: You should use AJAX to create widgets that can interact with the server without reloading the page.
This way, the widgets will not affect each-other.
jQuery will be useful here.

Alternatively, you could put each widget in its own <iframe>.


text:
Q: Programmatically set ImageButton layout_gravity What I Tried To Do
I tried to set my ImageButton's layout_gravity via Java code, the way I want the ImageButton to be is presented like the way within the Orange frame in the image below:

The Blue frame is a vertical LinearLayout act as a "base" layout and this is the layout I tried to add child layouts to.
The Orange and Red are both horizontal LinearLayout.
The Orange layout is the way I want to put the ImageButton and the TextView, this one is set up via XML
The Red layout is the result I tried to mimic the Orange layout via Java code.
The Related Code
Here's the XML code that set up the Orange layout, this is the effect I want to achieve via Java code:
        <!-- Begin the Orange Layout -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/info_left_padding"
            android:layout_marginRight="@dimen/info_right_padding" >

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:gravity="center_vertical"
                android:minHeight="@dimen/detail_min_line_item_height"
                android:text="TextView" />

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

                <ImageButton
                    android:id="@+id/imageButton1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="right|center_vertical"
                    android:adjustViewBounds="true"
                    android:maxHeight="@dimen/abs__action_bar_default_height"
                    android:scaleType="fitCenter"
                    android:src="@drawable/navigation_cancel" />
            </FrameLayout>
        </LinearLayout>

Here's the Java code that set up the Red layout
        int textHeight = (int)getResources().getDimension(R.dimen.detail_min_line_item_height);
        int imgHeight = (int)getResources().getDimension(R.dimen.abs__action_bar_default_height);

        TextView mTextView = new TextView(this);
        ImageButton mDeleteButton = new ImageButton(this);

        // Set Delete Button Padding
//      mDeleteButton.setPadding(buttonPadding, buttonPadding, buttonPadding, buttonPadding);

        // Set Imagebutton Scale type as fitCentre
        mDeleteButton.setScaleType(ScaleType.FIT_CENTER);

        // Set AdjustViewBounds
        mDeleteButton.setAdjustViewBounds(true);

        // Set max height of the image
        mDeleteButton.setMaxHeight(imgHeight);

        // Set the text appearance to be "large"
        mTextView.setTextAppearance(this, android.R.style.TextAppearance_Large);
        mTextView.setText(text);

        // Set the minimum height of this textview
        mTextView.setMinHeight(textHeight);

        // Set the content of the textview to be centred
        mTextView.setGravity(Gravity.CENTER_VERTICAL);

        // Set the ImageButton's background image
        mDeleteButton.setImageResource(R.drawable.navigation_cancel);

        LinearLayout.LayoutParams hParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

        LinearLayout hLayout = new LinearLayout(this);
        // Set Margins
        hParams.leftMargin = (int) getResources().getDimension(R.dimen.info_left_padding);
        hParams.rightMargin = (int) getResources().getDimension(R.dimen.info_right_padding);
        hParams.bottomMargin = (int) getResources().getDimension(R.dimen.text_layout_margin);

        hLayout.setLayoutParams(hParams);
        // Set orientation to horizontal
        hLayout.setOrientation(LinearLayout.HORIZONTAL);

        // The settings below is actually setting up some of the button's parameters
        LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        buttonParams.gravity = Gravity.RIGHT;
        mDeleteButton.setLayoutParams(buttonParams);

        hLayout.addView(mTextView);
        hLayout.addView(mDeleteButton);

        layout_blue.addView(hLayout);

What I've Tried So Far
According to some SO post like this: Java method for android:layout_gravity I initially tried to first put my ImageButton into a FrameLayout then set the params of this FrameLayout, like this:
FrameLayout buttonFrame = new FrameLayout(this);
FrameLayout.LayoutParams buttonParams = new FrameLayout.LayoutParams(android.widget.FrameLayout.LayoutParams.WRAP_CONTENT,
                                                                            android.widget.FrameLayout.LayoutParams.WRAP_CONTENT,
                                                                            Gravity.RIGHT | Gravity.CENTER_VERTICAL);
buttonFrame.setLayoutParams(buttonParams);
buttonFrame.addView(mDeleteButton);

But I had the same result as the image presented above. Later I also tried to change the LayoutParams width to MATCH_PARENTonly to find theImageButton` was stretched horizontally (Yes it's stretched)
Then I tried the method posted in these two SO posts:
How to set layout_gravity programmatically?
How to set a button's parameters programatically
Their method is to set up a LinearLayout.Params first, then apply this params to the button (The Code I posted in The Related Code section applies this method). In short it is:
    // The settings below is actually setting up some of the button's parameters
    LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    buttonParams.gravity = Gravity.RIGHT;
    mDeleteButton.setLayoutParams(buttonParams);

However, the result was still the same as the image presented above.
Question
Since I need to programmatically add more child views to the Blue layout later, I wonder if there's a way to set up each child layout like the Orange one in the image?
At Last
I found a solution which is quite similar to @Permita 's answer.
Here's my solution:
    LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT);
    textParams.weight = 1.0f;
    mTextView.setLayoutParams(textParams);

A: Add the below code, it will assign all the available space to the texView, shifting the button to right side of the layout to make it appear like the orangeLayout.
mTextView.setLayoutParams(LayoutParams param = new LinearLayout.LayoutParams(
                         LayoutParams.MATCH_PARENT,
                         LayoutParams.MATCH_PARENT, 1.0f));

A: Try layout_width = "0dp" layout_weight="1" for the TextView. This tells TextView to occupy the whole available width, so that FrameLayout with ImageView will align to the right border.
    <TextView
        android:id="@+id/textView1"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:gravity="center_vertical"
        android:minHeight="@dimen/detail_min_line_item_height"
        android:text="TextView" />

A: Instead of using the standard LinearLayout, why not try to use the more complex RelativeLayout? With it, you can adjust the locations of each individual view relative to others. You can set the ImageButton in the orange layout to android:layout_alignParentRight="true", which will set the button attached to the right side of the parent layout, the RelativeLayout in my case, but the LinearLayout in yours. Here is the link to the API Guides for Relative Layouts on the Android developers website.


text:
Q: Why does Daniel Wilks (2011) say that principal component regression "will be biased"? In Statistical Methods in the Atmospheric Sciences, Daniel Wilks notes that multiple linear regression can lead to problems if there are very strong intercorrelations among the predictors (3rd edition, page 559-560):

A pathology that can occur in multiple linear regression is that a set of predictor variables having strong mutual correlations can result in the calculation of an unstable regression relationship.

(...)
He then introduces principal component regression:

An approach to remedying this problem is to first transform the predictors to their principal components, the correlations among which are zero.

So far so good.  But next, he makes some statements that he does not explain (or at least not in sufficient detail for me to understand):

If all the principal components are retained in a principal component regression, then nothing is gained over the conventional least-squares fit to the full predictor set.

(..) and:

It is possible to reexpress the principal-component regression in terms of the original predictors, but the result will in general involve all the original predictor variables even if only one or a few principal component predictors have been used.  This reconstituted regression will be biased, although often the variance is much smaller, resulting in a smaller MSE overall.

I don't understand these two points.
Of course, if all the principal components are retained, we use the same information as when we were using the predictors in their original space.  However, the problem of mutual correlations is removed by working in principal component space.  We may still have overfitting, but is that the only problem?  Why is nothing gained?
Secondly, even if we do truncate the principal components (perhaps for noise reduction and/or to prevent overfitting), why and how does this lead to a biased reconstituted regression?  Biased in what way?

Book source: Daniel S. Wilks, Statistical Methods in the Atmospheric Sciences, Third edition, 2011.  International Geophysics Series Volume 100, Academic Press.

A: What happens when all PCs are used?
If all PCs are used, then the resulting regression coefficients will be identical to the ones obtained with OLS regression, and so this procedure should better not be called "principal component regression". It is standard regression, only performed in a roundabout way.
You are asking how it is possible that nothing is gained, given that after PCA the predictors become orthogonal. The devil hides in the back-transformation of the regression coefficients from the PCA space to the original space. What you need to know is that the variance of the estimated regression coefficients inversely depends on the covariance matrix of the predictors. The PCA-transformed predictors, let's call them $Z$, have diagonal covariance matrix (because they are uncorrelated). So all regression coefficients for $Z$ are also uncorrelated; the ones corresponding to the high-variance PCs have low variance (i.e. are estimated reliably) and the ones corresponding to the low-variance PCs have high variance (i.e. are estimated unreliably). When these coefficients are back-transformed to the original predictors $X$, each of the predictors $X_i$ will get some portion of the unreliable estimates, and so all coefficients can become unreliable.
So nothing is gained.
What happens when only few PCs are used?
When not all the PCs are retained in PCR, then the resulting solution $\hat \beta_\mathrm{PCR}$ will generally not be equal to the standard ordinary least squares solution $\hat \beta_\mathrm{OLS}$. It is a standard result that OLS solution is unbiased: see Gauss-Markov theorem. "Unbiased" means that $\hat \beta$ is correct on average, even though it can be very noisy. Since PCR solution differs from it, it will be biased, meaning that it will be incorrect on average. However, it often happens that it is substantially less noisy, leading to the overall more accurate predictions.
This is an example of the bias-variance trade-off. See Why does shrinkage work? for some further general discussion.
In the comments, @whuber pointed out that the PCR solution does not have to differ from the OLS one and hence does not have to be biased. Indeed, if the dependent variable $y$ is uncorrelated (in population, not in sample) with all the low-variance PCs that are not included in the PCR model, then dropping these PCs will not influence the unbiasedness. This, however, is unlikely to be the case in practice: PCA is conducted without taking $y$ into account so it stands to reason that $y$ will tend to be somewhat correlated with all the PCs.
Why using high-variance PCs is a good idea at all?
This was not part of the question, but you might be interested in the following thread for the further reading: How can top principal components retain the predictive power on a dependent variable (or even lead to better predictions)?


text:
Q: Have all database queries within a request of a controller go to a different database in Rails My company is nearing the end of a large migration/upgrade from our Rails 2.x app to Rails 4. Yes, I'm aware that of the time of this writing, Rails 4 is in RC and not final, but our goal is to be ready as soon as 4.0 final drops. We've gone through the entire upgrade process, replacing and upgrading gems as necessary, but finally hit a very large brick wall.
Some quick background:

*

*We use unicorn to serve up our app

*We have two PostgreSQL databases, each on different servers. One is a master, the other is a hot replicating read-only standby. Two controllers in our app serve up reports from our data. These reports are commonly very SQL intensive so we have the seamless database pool gem have all queries within those controller actions go through the PostgreSQL standby read-only box.
Unfortunately seamless database pool is not yet updated to work with Rails 4. We've looked into octopus and various other gems with no luck. I recently just thought of this idea of how to handle this issue by forgetting about using a gem and just switch the connection on the request for those specific controllers and then making sure that the connection is switched back to the other database after the request did its business so future requests to that unicorn worker will default to the primary database.
I would like to know if this is a really really bad idea and if anyone else has a better suggestion.
database.yml:
production:
  host: primary_db_host_ip
  adapter: postgresql
  encoding: unicode
  database: my_app_production
  pool: 5
  username: ****
  password: ****

standby_by:
  host: standby_db_host_ip
  adapter: postgresql
  encoding: unicode
  database: my_app_production
  pool: 5
  username: ****
  password: ****

app/controllers/application_controller.rb:
class ApplicationController < ActionController::Base
  ...
  ...

  private

  def switch_db
    ActiveRecord::Base.establish_connection("standby_db")
    yield
  ensure
    ActiveRecord::Base.establish_connection("production")
  end
end

app/controllers/special_controller.rb:
class SpecialController < ApplicationController
  around_action :switch_db
  ...
  ...
end

UPDATE: Specifically this is the error that's happening with seamless_database_pool for those that asked how would know if it's not Rails 4 ready...
undefined method `reset_transaction' for nil:NilClass (NoMethodError)
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/seamless_database_pool-1.0.12/lib/active_record/connection_adapters/seamless_database_pool_adapter.rb:336:in `proxy_connection_method'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/seamless_database_pool-1.0.12/lib/active_record/connection_adapters/seamless_database_pool_adapter.rb:122:in `block in reset_transaction'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/seamless_database_pool-1.0.12/lib/active_record/connection_adapters/seamless_database_pool_adapter.rb:243:in `use_master_connection'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/seamless_database_pool-1.0.12/lib/active_record/connection_adapters/seamless_database_pool_adapter.rb:121:in `reset_transaction'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/activerecord-4.0.0.rc1/lib/active_record/connection_adapters/abstract/database_statements.rb:6:in `initialize'
/home/.rvm/rubies/ruby-2.0.0-p195/lib/ruby/2.0.0/monitor.rb:232:in `initialize'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/activerecord-4.0.0.rc1/lib/active_record/connection_adapters/abstract_adapter.rb:90:in `initialize'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/seamless_database_pool-1.0.12/lib/active_record/connection_adapters/seamless_database_pool_adapter.rb:152:in `initialize'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/seamless_database_pool-1.0.12/lib/active_record/connection_adapters/seamless_database_pool_adapter.rb:48:in `new'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/seamless_database_pool-1.0.12/lib/active_record/connection_adapters/seamless_database_pool_adapter.rb:48:in `seamless_database_pool_connection'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/activerecord-4.0.0.rc1/lib/active_record/connection_adapters/abstract/connection_pool.rb:440:in `new_connection'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/activerecord-4.0.0.rc1/lib/active_record/connection_adapters/abstract/connection_pool.rb:450:in `checkout_new_connection'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/activerecord-4.0.0.rc1/lib/active_record/connection_adapters/abstract/connection_pool.rb:421:in `acquire_connection'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/activerecord-4.0.0.rc1/lib/active_record/connection_adapters/abstract/connection_pool.rb:356:in `block in checkout'
/home/.rvm/rubies/ruby-2.0.0-p195/lib/ruby/2.0.0/monitor.rb:211:in `mon_synchronize'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/activerecord-4.0.0.rc1/lib/active_record/connection_adapters/abstract/connection_pool.rb:355:in `checkout'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/activerecord-4.0.0.rc1/lib/active_record/connection_adapters/abstract/connection_pool.rb:265:in `block in connection'
/home/.rvm/rubies/ruby-2.0.0-p195/lib/ruby/2.0.0/monitor.rb:211:in `mon_synchronize'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/activerecord-4.0.0.rc1/lib/active_record/connection_adapters/abstract/connection_pool.rb:264:in `connection'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/activerecord-4.0.0.rc1/lib/active_record/connection_adapters/abstract/connection_pool.rb:546:in `retrieve_connection'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/activerecord-4.0.0.rc1/lib/active_record/connection_handling.rb:79:in `retrieve_connection'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/activerecord-4.0.0.rc1/lib/active_record/connection_handling.rb:53:in `connection'
config/unicorn.rb:16:in `block in reload'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/unicorn-4.6.2/lib/unicorn/http_server.rb:495:in `call'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/unicorn-4.6.2/lib/unicorn/http_server.rb:495:in `spawn_missing_workers'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/unicorn-4.6.2/lib/unicorn/http_server.rb:142:in `start'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/gems/unicorn-4.6.2/bin/unicorn_rails:209:in `<top (required)>'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/bin/unicorn_rails:23:in `load'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/bin/unicorn_rails:23:in `<main>'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/bin/ruby_noexec_wrapper:14:in `eval'
/home/.rvm/gems/ruby-2.0.0-p195@theapp/bin/ruby_noexec_wrapper:14:in `<main>'

A: For what it's worth, one of the other developers is going to try to dig into the gem and see if he can get it working in Rails 4. Hopefully it won't take too long...


text:
Q: How to properly implement POSTPONE in a Forth system? John Heyes' ANS Forth test suite contains the following definition:
: IFFLOORED [ -3 2 / -2 = INVERT ] LITERAL IF POSTPONE \ THEN ;

This is then used to conditionally define various words depending on whether we're using floored or symmetric division:
IFFLOORED : T/MOD  >R S>D R> FM/MOD ;

So IFFLOORED acts like either a noop or a \ depending on the result of the expression. Fine. That's easily implementable on my threaded interpreter by doing this:
: POSTPONE ' , ; IMMEDIATE

...and now IFFLOORED works; the definition is equivalent to : IFFLOORED -1 IF ['] \ EXECUTE THEN ;.
Unfortunately, further down the test suite is the following code:
: GT1 123 ;
: GT4 POSTPONE GT1 ; IMMEDIATE
: GT5 GT4 ;
\ assertion here that the stack is empty

The same implementation doesn't work here. If POSTPONE compiles a reference to its word, then GT4 becomes the equivalent of : GT4 123 ;... but GT4 is immediate. So when GT5 is defined, 123 is pushed onto the compiler's stack and GT5 becomes a noop. But that's not right; the test suite expects calling GT5 to leave 123 on the stack. So for this to work, POSTPONE must generate code which generates code:
: POSTPONE  ' LITERAL  ['] , LITERAL ;

And, indeed, if I play with gForth, I see that POSTPONE actually works like this:
: GT1 123 ;
: GT4 POSTPONE GT1 ; IMMEDIATE
SEE GT4

<long number> compile, ;

But these two definitions are not compatible. If I use the second definition, the first test fails (because now IFFLOORED tries to compile \ rather than executing it). If I use the first definition, the second test fails (because GT4 pushes onto the compiler stack rather than compiling a literal push).
...but both tests pass in gForth.
So what's going on?

A: Let me answer here, as the question changed considerably. I am still not sure I understand the question, though :)
In your example, you define
: GT4 POSTPONE GT1 ; IMMEDIATE

What happens here, is the following:

*

*: is executed, reading GT4 and creating the new word

*POSTPONE's compilation semantics is executed, which is to compile the compilation semantics of GT1 - as you have seen in GForth.

*; is executed, ending the definition

*IMMEDIATE is executed, marking the last defined word as immediate.

POSTPONE is called only when compiling GT4, and it does not appear in the compiled code. So when later using this immediate word in the definition of GT5, the interpretation semantics of POSTPONE is not needed.
By the way, according to the standard, POSTPONE has only compilation semantics, and the interpretation semantics is undefined.
See also the POSTPONE tutorial in the GForth manual.
EDIT Examples of interpretation and compilation semantics:
: TEST1 ." interpretation" ;  => ok
: TEST2 ." compilation" ; IMMEDIATE  => ok
: TEST3 TEST1 TEST2 ;  => compilation ok
TEST3  => interpretation ok
: TEST4 POSTPONE TEST1 ; IMMEDIATE  => ok
: TEST5 TEST4 ;  => ok
TEST5  => interpretation ok
: TEST6 POSTPONE TEST2 ; IMMEDIATE  => ok
TEST6  => compilation ok

If you have any more questions, you can reference these tests.

A: The snippet you've quoted does the following things:

*

*Evaluate -3/2 (at compile time), and check if it is -2.

*If it is, store a 0 (false), otherwise store a -1 (true) in IFFLOORED, so when it is evaluated, it will put this value on the stack. (This is the effect of LITERAL.)

*When evaluating IFFLOORED, after pushing the value on the stack, comes an IF - THEN expression. When the value is true, it means that we are not in a floored environment, so we want to comment out the rest of the line, and that is what \ does.

So here comes the tricky part - \ is IMMEDIATE, i.e., you cannot use it inside a colon definition, because it will comment out the rest of the line. You have to explicitly tell the compiler that you want to compile this function, and not execute it, which is what POSTPONE does.

A: The behavior of postpone word in compilation state is to determine compilation semantics for its parsed argument and append these semantics to the current definition.
Compilation semantics for a word can be either special or ordinary (see the section 3.4.3.3 Compilation semantics of Forth-2012). To work correctly, postpone should distinguish these cases and generate code according to the different patterns.
A problem of your implementations is that they are correct either for ordinary compilation semantics or for special compilation semantics.
A standard compliant implementation is as follows:
: state-on  ( -- )  1 state ! ;
: state-off ( -- )  0 state ! ;

: execute-compiling ( i*x xt --j*x )
  state @ if  execute  exit  then
  state-on  execute  state-off
;
: postpone ( "name" -- )
  bl word find dup 0= -13 and throw 1 = ( xt flag-special )
  swap lit, if ['] execute-compiling else ['] compile, then compile,
; immediate

See more details in my post How POSTPONE should work.


text:
Q: how to identify the male-female and female-male jumper wires? I know it is a basic question but still I am confused , I wanted to use the female-male jumper wires on my basic electronic project ,So my question is how Can I identify which is female-male or male-female jumper wires?

A:
left: male connectors; right: female connectors


text:
Q: WinZip, 7zip, Winrar Command Line to Compress structure of folders I have a Windows Server 2008R2 which has a massive file share of Video files, I need to run a zip command line in a batch script which will :
a) Compress / zip each video file inside each folder with the respective filename
b) then compress / zip each folder with its respective name
c) Retain the original folder structure
d) then zip the whole structure into one single zip file containing the whole folder structure and video zip files inside it.
is this even possible ? Can I use any of the above programs via command line to batch / powershell it ?
The server has 8GB RAM with a  Core i3 Processor.
Will be grateful for your suggestions and help

A: 7zip comes with 7z.exe which can be used on the command line or in scripts.  However, you'll have to use a script to do the folder structure zipping that you want.  I've done something similar, zipping log files by month then year.  It's not pretty, but I can post the script if you'd like to see it.

A: Assume the directory name is \video .
Create a batch file with the following lines:
for /r \video %%a in (.) do @zip.exe -m "%%~pa\video" "%%~pa\*"
zip.exe -m -r Allvideo "\video\*"

This will create a final archive called allvideo.zip with a directory structure mirroring \video.  Where video files once resided, video.zip will be found.
For this example I used the Zip utility found at:
http://www.info-zip.org/Zip.html
Your server has enough horsepower for this activity, but, you may need to watch disk space. I'm only able to get ~5% size reduction by compressing a video file.


text:
Q: Error with external_labels config in alertmanager.yml section of helm Prometheus values.yaml I've installed prometheus using helm into my kubernetes cluster as follows;
helm list
NAME        NAMESPACE   REVISION    UPDATED                                 STATUS      CHART               APP VERSION
prometheus  prometheus  9           2021-09-07 08:54:54.262013 +0100 +01    deployed    prometheus-14.6.0   2.26.0

I am trying to apply external_labels in the values.yaml to identify the time series sent to Alertmanager.  I've used the prometheus docs to get what I believe to be the correct config, as below;
alertmanagerFiles:
  alertmanager.yml:
    global:
      external_labels:
        environment: 'perf'

My installation goes ok;
helm upgrade --install prometheus .

However my prometheus-server pod is crashing due to the following error;
level=error ts=2021-09-06T18:49:25.059Z caller=coordinator.go:124 component=configuration msg="Loading configuration file failed" file=/etc/config/alertmanager.yml err="yaml: unmarshal errors:\n  line 2: fie │
│ ld external_labels not found in type config.plain"

Many of the answers here point to indentation issues, however I can't see what I am doing wrong..  from the Prometheus docs;
global:
  # The labels to add to any time series or alerts when communicating with
  # external systems (federation, remote storage, Alertmanager).
  external_labels:
    [ <labelname>: <labelvalue> ... ]

I have been scratching my head on this for a week or two - would appreciate a second pair of more experienced eyes, thank you!

A: I have managed to get this working.. firstly I was putting the configuration in totally the wrong place.  I figured this out when looking at the github page for prometheus alertmanager, and I could not see the field defined in the 'good config test', so it must be configured elsewhere..
Indeed the prometheus config page says so - so I added a section under ## Prometheus server ConfigMap entries;
serverFiles:
  prometheus.yml:
    global:
      external_labels:
        environment: perf

This did not work either, the pod was crashing.  Turns out this should be configured in the part in the values.yaml which configures the prometheus-server container itself - where the top level field = server, and we can see the default global values are also configured here.  So I added external_labels into this section;
server:
  global:
    scrape_interval: 1m
    scrape_timeout: 10s
    evaluation_interval: 1m
    external_labels:
      environment: perf

When I upgraded using helm upgrade --install prometheus . I can now see the correct config in kubectl get cm prometheus-server -o yaml, plus my Pager Duty alerts are now showing the environment name in the Summary.
A little side tip on how to test alerts without having to kill pods/create OOMs etc is to create an alert expr: which constantly fires (e.g kube_pod_container_status_restarts_total > 3) which I did by accident but proved to be quite useful.


text:
Q: How to prove that $f: \mathbb{R} \to \mathbb{R}$ is continuous, given that $xy-y^2 \leq f(x)-f(y) \leq x^2-xy$? Let $f: \mathbb{R} \to \mathbb{R}$ and let $$xy-y^2 \leq f(x)-f(y) \leq x^2-xy$$
I am trying to prove that f is continuous i.e:
$$\lim_{x \to x_0}f(x) = f(x_0)$$

To be honest, I barely understand the problem. What I can extract from it is:
$$ xy-y^2 \leq x^2-xy \iff \boxed{x^2+y^2 \geq 1} $$
Hence, the inequality holds only $\forall$ outter points of the unit circle, centered at $(0,0)$.
More than that, I can't understand how to show continuity for $f$, since I don't even know what $f$ is. In order for a function to be continuous the following condition must be satisfied:
$$\lim_{x \to x_0} f(x) = f(x_0)$$

Any tips that will help me understand the problem would be greatly appreciated

A: This follows from Squeeze Theorem. As $y \to x$, $x^{2}-xy$ and $xy-y^{2}$ both tend to $0$ and hence $f(x)-f(y) \to 0$. This means: $f$ is continuous at $x$.
[ For $x \neq 0$ check that $|x^{2}-xy| <\epsilon$ if $|x-y| <\frac {\epsilon} {|x|}$ and
$|xy-y^{2}| <\epsilon$ if $|x-y| <\frac {\epsilon} {\epsilon+|x|}$. The case $x=0$ is trivial and  leave it to you].

A: Hint: You need, for all $x\in\mathbb R$ and $\epsilon>0$, that there exists a $\delta>0$ so that
$$|f(y)-f(x)|<\delta\text{ if }|y-x|<\epsilon.$$
This is a good definition of continuity to use, because it involves bounding the quantity $f(y)-f(x)$, which is exactly what you're given. In particular, you know that
$$|f(y)-f(x)|\leq \max(|xy-y^2|,|x^2-xy|).$$
Can you show that, for all $x\in\mathbb R$ and $\epsilon>0$, that there exists a $\delta>0$ so that
$$|xy-y^2|,|x^2-xy|<\delta?$$

A: Just to mention $$xy-y^2\le x^2-xy \iff x^2+y^2-2xy \ge 0 \iff (x-y)^2\ge 0$$ which is true for any $x,y\in \Bbb{R}$ so the inequality holds for all points in the plane, not only the outer points of the unit circle as you have mentioned.
Besides that since the given inequality holds for all pair of real numbers $x,y$, take $y=x_0$ and $\lim_{x\to x_0}$ on both sides of the given inequality  $$\lim_{x\to x_0} (f(x)-f(x_0)) \ge \lim_{x\to x_0} (xx_0-x_0^2)=0 \\ \lim_{x\to x_0} (f(x)-f(x_0)) \le \lim_{x\to x_0} (x^2-xx_0)=0 \\ \implies \lim_{x\to x_0} (f(x)-f(x_0)) =0 $$
which is same as the squeeze theorem mentioned in other answers.

A: Becuse
$$0=\lim_{x\rightarrow x_0}(xx_0-x_0^2)\leq\lim_{x\rightarrow x_0}(f(x)-f(x_0))\leq\lim_{x\rightarrow x_0}(x^2-xx_0)=0.$$


text:
Q: Cool riddle involving integer vectors Let $V$ be a $k$-dimensional vector ($k$ is given) of the form $$V=[n_1, n_2, ..., n_k],$$
where $n_1, n_2, ..., n_k$ are positive integers.
Your objective is to determine $V$ by choosing $T$ vectors of your choice, and receiving their dot products with $V$ respectively.
for example, if my vector is $[1, 2]$, and your vectors are $[1, 1], [5, 3/2]$, you will get their dot poducts: $([1,1]*[1,2] =3, [5,3/2]*[1,2] = 8)$

What is the minimum number of vectors $T$ that you need to choose to determine $V$? (bonus: add the requirement that your vectors must consist of positive integers as well)

(p.s. there exists a solution $T<k$, it's not that obvious)
The solution to this riddle(s) is amazing, and i'll post it in a couple of days.

A: If $V$ were limited to entries at most $b$, then the solution would be easy: query
$$ V \cdot [b^0, b^1, \dots, b^{k-1}]$$
The result, when read in base-$b$, would be the vector $V$. However, this would be foiled for any constant choice of $b$ because the entries of $V$ could be arbitrarily large. (Any scheme to "guess" such a $b$, for example, by repeatedly doubling, could be similarly fooled).
However, it's easy to get a $b$ large enough: $V \cdot [1, 1, \dots, 1]$ is the sum of the entries in $V$. Since all of the entries in $V$ are strictly positive, this dot product is strictly bigger than any entry in $V$ (as it's the sum of the largest element and the rest of the elements, which are at least 1).
Thus, the first query is $b = V \cdot [1, 1, 1, \dots, 1]$.
The second query is $v = V \cdot [b^0, b^1, b^2, \cdots, b^{k-1}]$.
Then $V$ is the result from reading the digits of $v$ in base-$b$, so $t \leq 2$.
(Since any number of vectors have the same dot product, $t \geq 2$ so this does give $t = 2$ exactly)

This relies heavily on the positiveness of the entries of $V$. Can the problem be solved in fewer than $k$ queries when the entries of $V$ are allowed to be negative?

I remember a very similar problem, that tasks you with determining the coefficients of a polynomial $q$ with only non-negative integer as coefficients with as few integer queries as possible. (The method looks about the same as this problem).
A link to a blog post concerning this problem is here.

A: Here is my answer:
Let $I = [ln(2),ln(3),...,ln(p_k)]$ where $p_k$ is the $k^{th}$ prime.
$V*I=n_1ln(2)+n_2ln(3)+...+n_kln(p_k) = ln(2^{n_1}*3^{n_2}*...*p_k^{n_k})$
Therefore, by taking the prime factorizations of $e^{V*I}$, and looking at the exponents, we can deduce what $V$ is.
So by choosing $I$ and only $I$ to be our vector, we can fully deduce $V$ (and $minT=1$).

A: If any real numbers are allowed then $ T=1 $: choose the vector $(e, e^2,\ldots , e^n) $ and use the fact that $ e $ is transcendental. It is not constructive but you know that different vectors will output different dot products.
Edit: if $(a_1,\ldots, a_n) $ and $(b_1,\ldots, b_n) $ are two vectors that output the same number,  then $ e $ is a root of the polynomial with integer coefficients $$\sum (a_i -b_i) X^i$$ therefore all its coefficients are zero.

A: I would choose $T = k$ vectors $a_1, a_2, \ldots, a_k$, which are linearly independent.
Then, I would create a matrix $A$ which rows corresponds to each vector $a_i$. For construction, $A$ is invertible.
Moreover, given $q_i$ as the dot product of $V$ with $a_i$, I create the column vector $q = [q_1 ~ q_2 ~ \ldots ~ q_k]^\top.$
Finally, I can calculate $V$ as follows:
$$V = A^{-1}q.$$
Additionally, I can avoid the inversion of matrix $A$ if I choose $a_i$ as versors, i.e. $a_i$ has only $0$ components, and the $i$-th entry is $1$. In this case, $A$ is the identity matrix, and I obtain that:
$$q_i = n_i.$$


text:
Q: How can I compute the probability of a union of intersections? How can I compute the probability of a union of intersections? For example, if A, B, and C are independent events,
$$\Pr((A\cap B)\cup(A\cap C)\cup(B\cap C)) = ? $$
Is it $\Pr((A∩B)∪(A∩C)∪(B∩C)) = \Pr(A) \cdot \Pr(B) + \Pr(A)\cdot \Pr(C) + \Pr(B)\cdot \Pr(C)$ ? Feels like this is too simple and I have to subtract something...

A: $\Pr(X\cup Y\cup Z) = \Pr(X)+\Pr(Y)+\Pr(Z)-\Pr(X\cap Y)-\Pr(X\cap Z)-\Pr(Y\cap Z)+\Pr(X\cap Y\cap Z)$
This is true even when $X,Y,Z$ can be written as intersections or unions of other events or something even more complicated.

A: I assume you are interested in
$$P((A\cap B)\cup(A\cap C)\cup(B\cap C));$$
without the brackets this is ambiguous. That is precisely the event that at least two of $A,B,C$ occur.
Now $P(A\cap B)+P(A\cap C)+P(B\cap C)$ is not the same as this probability, since the events overlap - this would count $A\cap B\cap C$ three times (indeed, it's easy to see that this sum can be greater than $1$). Thus the actual answer is
$$P(A\cap B)+P(A\cap C)+P(B\cap C)-2P(A\cap B\cap C);$$
if the events are independent you can replace these with products as usual.


text:
Q: How to perform clicking on the first item in an ArrayList by Espresso I have tried to click on the first item of my arraylist for few hours, I have read a lot of questions on Stack Overflow, tutorials and I have tried to implement them in many ways, but it doesn't work.
   clickView(getSearchActivity().hintListView);

onData(anything())
    .onChildView(withId(R.id.hintLayout))
    .atPosition(0)
    .perform(click());

onData(allOf(is(instanceOf(String.class))))
    .atPosition(0)
    .perform(click());

onData(instanceOf(ArrayList.class))
    .atPosition(0)
    .perform(click());

onData(instanceOf(String.class))
    .atPosition(0)
    .perform(click());

onData(anything())
    .inAdapterView(withId(R.id.hintLayout))
    .atPosition(0)
    .perform(click());

onData(anything())
    .inAdapterView(allOf(withId(R.id.hintLayout), isCompletelyDisplayed()))
    .atPosition(0).perform(click());

I have to click on the first item of the ListView, that take ArrayList
id of this ListView is hintLayout.
Does anybody know what is the problem ? and where can it be ?

A: A ListView must be filled with an adapter.  After your adapter is finished just add it to your ListView like this:
private void setListAdapter(ListDataAdapter adapter){
    lvYourListView.setAdapter(adapter);
}

In order to get the data back out on the OnClick event you need to something like this in you onCreate() method:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

 lvYourListView = (ListView) findViewById(R.id.lvListview);
        lvYourListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ListData data = new ListData();

                data = (ListData)parent.getItemAtPosition(position);

                doSomethingWithData(data);

            }
        });

If you need help with the adapter - just let me know. I will need to see more of your code in order to do that.


text:
Q: A confusing question in Royden's Real Analysis
Let $I $ be a closed and bounded interval, and $E $ a measurable subset of $I$. Let $\epsilon>0$. Show that there is a step function $h $ on $I $ and a measurable subset $F $ of $I $ for which $h=\chi_E $ on F and $m (I\sim F) <\epsilon $.

Here we assume all sets are subsets of $\Bbb {R} $.
Why can't we have $F=I$?  Clearly I is measurable!


text:
Q: How could I do frequency analysis on a string without using a switch I am working a school project to implement a Huffman code on text.  The first part of course requires a frequency analysis on the text.  Is there a better way aside from a giant switch and an array of counters to do it?
ie:
int[] counters

for(int i = 0; i <inString.length(); i++)
{
switch(inString[i])
    case 'A':
    counters[0]++;
.
.
.

I would like to do all alpha-numeric characters and punctuation.  I am using c++.

A: Why not:
int counters[256] = {0};
for(int i = 0; i <inString.length(); i++)
    counters[inString[i]]++;
}

std::cout << "Count occurences of \'a\'" << counters['a'] << std::endl;

A: You can use an array indexed by character:
int counters[256];
for (int i = 0; i < inString.length(); i++) {
    counters[(unsigned char)inString[i]]++;
}

You will also want to initialise your counters array to zero, of course.

A: using a map seems completely applicable:
map<char,int> chcount;
for(int i=0; i<inString.length(); i++){
  t=inString[i];
  chcount[i]? chcount[i]++ : chcount[i]=1;
}


text:
Q: In Qt, how to setCodecForCStrings globally (in header)? I'm developing a bunch of Qt applications in C++ and they all use some modules (translation units) for common functionality that use Qt as well.
Whenever I convert a C string (implicit conversion) or C++ string object (fromStdString()) to a QString object, I expect the original data to be UTF-8 encoded and vice versa (toStdString()).
Since the default is Latin-1, I have to set the codec "manually" (in the init procedure of every one of my programs) to UTF-8:

QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf8"));

Not all of my modules have an init procedure. The ones containing a class do (I can put this line in the class constructor), but some modules just contain a namespace with lots of functions. So there's no place for setCodecForCStrings(). Whenever I convert from/to a QString implicitly (from within one of my modules), I rely on the codec being already set by the init procedure of the main program, which seems to be a rather bad solution.
Is there a reliable way to set the codec to UTF-8 in my modules, or will I just have to be very careful not to use implicit conversions at all (in my modules at least) and write something like std::string(q.toUtf8().constData()) instead of q.toStdString()?

A: This can be done using a class definition for an automatically instantiated singleton-similar class having some init code in its constructor:
class ModuleInit {
    static ModuleInit *instance;
public:
    ModuleInit() {
        QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf8"));
    }
};
ModuleInit * ModuleInit::instance = new ModuleInit(); // put this line in .cpp!

Putting this code anywhere into any project will set the text codec to UTF-8. You can, however, overwrite the text codec in the main() method, since the code above is executed even before the main() method.
With "anywhere" I of course mean places where it is syntactically allowed to. Put the class definition in some header file, and the instantiation in the appropriate .cpp file.
You can even put the whole code in one .cpp file, say moduleinit.cpp which you compile and link, but never explicitly use (there is no header file you could include...). This will also avoid accidental instantiations except the very first one and you will not have any problems with duplicate class names.
Note that you can't set the codec for C-strings in one particular file. Setting the codec using QTextCodec::setCodecForCString will set it application-wide!


text:
Q: New Google spreadsheet Concatenate limit 50000 characters Migrating to new Google spreadsheets. I have a custom formula that combines a few arrays into one array
=TRANSPOSE(SPLIT(ARRAYFORMULA(CONCATENATE('Monthly link'!A10:A&CHAR(13) , 'Monthly link'!R10:R&CHAR(13) , 'Monthly link'!AG10:AG&CHAR(13) , 'Monthly link'!AU10:AU&CHAR(13) )), CHAR(13)))
this formula works perfectly fine in the old Google spreadsheet, but in the new one, it gave me a "Error: Text result of CONCATENATE is longer than the limit of 50000 characters."
Is there a way around this? I've tried the Array_Literal formula but can't seem to get it to work, that seems like the a possible solution. But it seems the function combines arrays across and not down.
I've tried:
=array_literal('Monthly link'!A10:A,'Monthly link'!R10:R,'Monthly link'!AG10:AG,'Monthly link'!AU10:AU)

A: Looking back to here, you can probably nest concatenate:
=TRANSPOSE(SPLIT(ARRAYFORMULA(CONCAT(CONCATENATE('Monthly link'!A10:A&CHAR(13) ,
'Monthly link'!R10:R&CHAR(13)), CONCATENATE('Monthly link'!AG10:AG&CHAR(13) ,
'Monthly link'!AU10:AU&CHAR(13)) )), CHAR(13)))

I simply added in one more CONCATENATE to combine the strings with only one value, then use CONCAT to combine those.
EDIT
This isn't exactly a fix, but reading google documentation states that you can create an old spreadsheet by going here.
EDIT 2
Try this code:
=TRANSPOSE(SPLIT(CONCAT(ARRAYFORMULA(CONCATENATE('Monthly link'!A10:A&CHAR(13),
'Monthly link'!R10:R&CHAR(13))), ARRAYFORMULA(CONCATENATE(
'Monthly link'!AG10:AG&CHAR(13), 'Monthly link'!AU10:AU&CHAR(13)))), CHAR(13)))

It seems the error is coming from ARRAYFORMULA, has it has a limit of 50000. Not CONCATENATE or CONCAT. So, I use CONCAT to combine two different ARRAYFORMULAs that both house half of the original data. You can continue to divide these until there are even 4 ARRAYFORMULAs that all only have one dataset if need be.
EDIT 3
Currently, I am working on implementing a function in javascript found here.
You can test it currently by Tools->Script editor->Paste, then to run it go Tools->Script Manager->organizeData->Run.
I'll continue to work on it... it is currently not working, but I am close;)
EDIT 4
I finished it! You can see it here. You need to create a new script using the above instructions (Tools->Script editor->Paste), save it, then you can run it from the Script Editor window or from the spreadsheet by doing Tools->Script Manager->organizeData->Run.
What the script does is gets the data from the forms, puts it in the data to be copied, then it has a strange restriction where it requires a letter in the column to be able to copy it,  so it adds a letter in so the script will fill the rows with "undefined". From there, all of the rows have "undefined" in them, so data can be copied to all of them.
If you want to know how to implement the script directly into a cell, you can just put:
=organizeData()

it will call the custom function! See here for more details.

A: Don't know if this is working, but might be worth a shot. Someone posted this on Google Docs help forum.
/.../ If you want more than 50,000 characters in a single cell, you can use QUERY's header clause.

Example:

=ArrayFormula(query(row(A1:A70000),,100000))

This creates a cell with 408,893 characters. You can verify by using the LEN function.

Ok I fixed the above line like this, I think it works:
=ArrayFormula(query(A1:A100000,,100000))

This is provided that you have data in column A, from row 1 to row 100000. It will concatenate all of it. I guess max length is 100000 characters?

A: My answer is related to another similar Q, marked as duplicete:
Text result of JOIN is longer than the limit of 50000 characters
My solution is to use the formula:
=query(joinSplit(A2:A, ";"), "select Col1, count(Col1) group by Col1", 0)
where joinSplit(A2:A, ";") is a custom formula.
The code to paste into script editor is:
function joinSplit(column, delim)
{
  var result = [];
  var row = [];
  for (var i = 0, l = column.length; i < l; i++)
  {
    row = column[i].join(delim).split(delim);
    row.forEach( function(elt) { result.push([elt]); } );
  }
  return result;
}

It will return the column of unique items.
If data is:
A;B;C;D
D;D
E;F;A;A
G;A;B;C

The result is column:
A
B
C
D
D
D
E
F
A
A
G
A
B
C

A: The joinSplit script SAVED MY LIFE.
I tweaked it to trim out whitespace in case your data has a ", " in it.
function joinSplit(column, delim)
{
  var result = [];
  var row = [];
  for (var i = 0, l = column.length; i < l; i++)
  {
    row = column[i].join(delim).split(delim);
    row.forEach( function(elt) { result.push([elt.trim()]); } );
  }
  return result;
}


text:
Q: Using sessions created other than by login with systemd-homed? I've been experimenting with systemd-homed, and have mostly successfully migrated an account over to it using the procedure here. When logging in conventionally, via login(1), everything works exactly as it should.
The specific problem I am having is with sessions created by means other than login(1).
One of these is the systemd-logind linger facility. When a user session is created by this (for example, after enabling it with loginctl enable-linger avatar and restarting), the services running in that session can't access the home directory (which is not mounted). Another is a user session created by machinectl, i.e., machinectl shell avatar@.host, which likewise can't access the home directory.
(In either case, it is possible for them to access the home directory if a working user session already exists, but of course it's impossible to guarantee that.)
The ultimate cause of this appears to be the lack of an entered password in either case, viz.:
Sep 05 18:02:24 pallas-wsl systemd-homed[702]: avatar: changing state inactive → activating-for-acquire
Sep 05 18:02:24 pallas-wsl systemd-homework[4380]: None of the supplied plaintext passwords unlock the user record's hashed passwords.
Sep 05 18:02:25 pallas-wsl systemd-homed[702]: Activation failed: Required key not available
Sep 05 18:02:25 pallas-wsl systemd-homed[702]: avatar: changing state activating-for-acquire → inactive

How can I make systemd-homed activate the home directory in these scenarios?

A: It seems like you are not hashing your passwords inside your request. Maybe look at these JSON keys: pkcs11EncryptedKey and hashedPassword, maybe that will solve your problem


text:
Q: React-Redux Dispatch design Overview
We have a page with a header (Blue color) and content section (Green color) that can be seen in image below. The requirement is when a user selects a year in header, then the content page will show data as per the selected year.

What is happening right now Technically
When user selects a year in header, we dispatch the selected value and the active container's mapStateToProps function is triggered and the selected year is passed to the component.
class Page1Content extends Component {
}

function mapStateToProps(state) {
    return { selectedYear : state.userSelectedValue };
}

export default connect(mapStateToProps, null)(Page1Content);

Question 1
How will data on Page1Content will refresh? Few approaches:

*

*In ComponentDidUpdate react life cycle method of the Page1Content API to fetch data can be called. However have seen opinions where we should avoid React hooks and life cycle methods with Redux.

*In mapStateToProps function API can be called.

Can any one suggest what is the better place to call the API?
Question 2
Data on Page1Content will be used only by this page. This data will not be used by any other component and hence need not be shared by any other Component. Now question 2 is

*

*In case we decide to use ComponentDidUpdate should we again dispatch the API call using Thunk or any other library and then catch the response in mapStatesToProps again?

*Or we should make the API call and resolve it in the component itself as a promise. Then the response will be set in State and respective Template will be refreshed.

A: ComponentDidUpdate is a lifecycle method not a hook. Hooks is functionality that allows functional components to have class based functionality such as state.
You are using a class based component in your example so you are not using hooks.
https://reactjs.org/docs/hooks-intro.html
Yes Redux shouldnt be used with hooks since context is a better option.
You can lift state up so to speak and update the local state in the parent component getting rid of redux completely.
Just pass down the setState function and the state itself to the appropriate children.
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
               some_prop: false
             }
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState({some_prop: true})
    console.log('Click happened');
  }
  render() {
    return (

     <Page1Component props={this.state.some_prop} />
  }
}

Edit:
Question 1
How will data on Page1Content will refresh?
best option is with a ternary expression in your render method, there is no need to check if the state updated. In react if the state is changed your component will automatically re render.
  render() {
    return (

        {this.props.selectedYear
           ?
 {this.props.selectedYear}

           : null
         }

  }
}

Question 2
Data on Page1Content will be used only by this page. This data will not be used by any other component and hence need not be shared by any other Component. Now question 2 is
If I understand this correctly you will need to use an action creators, redux thunk is overkill here.
class Header extends Component {
  constructor(props) {
    super(props);
  }

  handleClick() {
    this.props.dispatchActionCreator({some_value})
    console.log('Click happened');
  }
  render() {
    return (
      <button onClick={(some_value) => this.handleClick(some_value)}>Click </button>
  }
}

function mapDispatchToProps(state) {
    return {
       dispatchActioNCreator: (some_value) => dispatch(ACTIONS.action_creator(some_value) };
}

This will save your value from your header to the global redux state and then you can just access with mapStateToProps in your Page1Component.


text:
Q: show that all the the roots of the equation $2x^3-ax^2+bx-c=0$ are real let $k_{1}>k_{2}>k_{3}>k_{4}>k_{5}>k_{6}$ and $a=k_{1}+k_{2}+k_{3}+k_{4}+k_{5}+k_{6}$ and
$b = k_{1}k_{3}+k_{3}k_{5}+k_{5}k_{1}+k_{2}k_{4}+k_{2}k_{6}+k_{4}k_{6}$ and $c=k_{1}k_{3}k_{5}+k_{2}k_{4}k_{6}$
show that all the the roots of the equation $2x^3-ax^2+bx-c=0$ are real
want be able to go head, could some help me with this,thanks

A: We can write
$$2x^3-ax^2+bx-c=(x-k_1)(x-k_3)(x-k_5)+(x-k_2)(x-k_4)(x-k_6)$$
Let this be $f(x)$.
Then, we have
$$f(k_1)\gt 0,\quad f(k_2)\lt 0$$
$$f(k_3)\lt 0,\quad f(k_4)\gt 0$$
$$f(k_5)\gt 0,\quad f(k_6)\lt 0$$
Since $f(x)$ is continuous, by the intermediate value theorem, there are three real numbers $\alpha,\beta,\gamma$ such that $$f(\alpha)=f(\beta)=f(\gamma)=0,\quad k_2\lt\alpha\lt k_1,\quad k_4\lt\beta\lt k_3,\quad k_6\lt\gamma\lt k_5$$


text:
Q: Ios Swift3 : URLSession shared datatask showing an error I am getting the below error while trying to get data from PHP sever.
URLSession being initialised seems to have an error at shared. Kindly help me to get swift3 equivalent.
This is error message and sample code below :

Ambiguous reference to member 'dataTask(with:completionHandler:)'

let task = URLSession.shared.dataTask(with: PhpReqVar)
{
    data, response, error in
    // Code Todo
}

Thanks in advance.

A: Your completion handler does not take any parameters and you are not closing the (.
Try this (assuming that PhpReqVar is of type URL or URLRequest):
let task = URLSession.shared.dataTask(with: PhpReqVar)
{
    data, response, error in
    //CodeTodo
}

A: The code should be the following:
let task = URLSession.shared.dataTask(with: PhpReqVar as URLRequest) { (data, response, error) in
 //code here
}

You have missed to add the completionHandler's parameters. Also specifying PhpReqVar as URLRequest, not as MutableURLRequest.


text:
Q: Sieve of Eratosthenes near complexity approximation I have tried to give a more precise approximation to Sieve of Eratosthenes.
Elementary operations and weights that I used:
 prime[p]         -> 1 operation
 m = p * p        -> 2 operations
 prime[m] = false -> 1 operation
 m = m + p        -> 2 operations

My proof:
Is my proof correct? I found in the literature that the complexity is O(nlog(log(n))) or O(nlog(log(n))/log(n)).

A: Yes, that's correct, O(nloglogn)==O(nloglog(sqrt(n))):


text:
Q: Setting multidimentional arrays as vector in C++ I have "int array[10][10]" (Two dimentional (Size can be changed!) )
and I want to set all of items into "vector> Vector"
I tried:
vector<vector<int>> Vector;
for(int i = 0; i < 10; i++)
for(int j = 0; j < 10; j++)
{
    Vector[i][j] = array[i][j];
}

But it doesnt work. I get this exception:
The program has unexpectedly finished.

A: vector<vector<int>> Vector(10, vector<int>(10));

will do the trick


text:
Q: InheritanceBasedAopConfigurer using runtime constructor arguments I've got a (prototype) class owned by the Spring.NET context, created with an AutoProxy with runtime constructor arguments. It get's instantiated like this.
var context = ContextRegistry.GetContext();
var myClass = context.GetObject("myclass", new object[]{ myRuntimeConstructorArgument }) as MyClass;

This class has some inner logic going, where it catches an event that gets handled by a class method, like this:
// MyClass owned by Spring.NET context
public class MyClass {

  // InnerObject not owned by Spring context
  private InnerObject innerobject;

  // argument object not owned by Spring context
  public MyClass(ObjectNotOwnedBySpring myRuntimeConstructorArgument) {
     ...
     this.innerobject = new InnerObject();
     this.innerobject.SomeEvent += this.handleSomeEvent;
  }

  // I would like to intercept this event handler
  public virtual void handleMyEvent (object sender, EventArgs args)
  {
    // do stuff
  }
}

I'm trying to use AOP to remove an abstraction leak (caused by a bug in an external component), by intercepting the handleMyEvent method.  Because Spring.Aop uses a proxy based approach to intercept method calls, inner method calls don't get intercepted. I get that part.
If I understand the documentation correctly, that's where the InheritanceBasedAopConfigurer comes into play, by using a 'true' inheritance based AOP mechanism. From the documentation:

Interception advice is added directly in the method body before invoking the base class method.

Exactly what I need!
Unfortunatly, I can't get the InheritanceBasedAopConfigurer get to play nicely with the runtime constructor arguments:

Spring.Objects.Factory.ObjectCreationException: Error creating object with name 'myclass' > defined in 'file [spring-aop-config.xml] line 36' : Could not resolve matching constructor.

Is runtime constructor arguments not supported by the InheritanceBasedAopConfigurer ? Or is this a wrong use case for the InheritanceBasedAopConfigurer ?


text:
Q: Why am I receiving successful API post, but the data not actually posting? Forgive me for I am new here. I am working on an API in PHP in order to create a new customer in my customer management system, AMS360, using an API post. I am receiving successful post responses but when I go to the AMS360 UI, I cannot find the customer I just created. I am error checking by creating txt files with the responses, Add_Cust_Result_Dec.txt is empty, while Add_Cust_Result.txt is populated with the response for a successful Post, however the user was not created in my system. Can anyone point me in the right direction to fix this or start debugging this?
My post request looks like this:
$url = "https://api-sandbox.vertafore.com/authgrant/v1/api/Customers";

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $info);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Authorization: Bearer $key",
        'Content-Type: application/json'
    ));

$result = curl_exec($ch);
$result_dec = json_decode($result);
file_put_contents("Add_Cust_Result.txt", $result);
file_put_contents("Add_Cust_Result_Dec.txt", $result_dec);

Below this code, I check if the customer was added successfuly like so:
if (isset($result_dec->CustomerId)) {...}

Considering the $result_dec did not output anything to the txt file, im assuming its empty? Thank you for any advice.


text:
Q: lightingBitMask of SpriteKit would prevent SKAction? I'm trying to use add a lightingBitMask to the background so that I can see the effect of SKLightNode. But when I enable lightingBitMask, as shown in line 32, the action in line 55-56 would not take into effect. In other words, the "rock" stops rotating.
Here is my code.
Thanks for the kindly help.

A: The problem is found:
If you use a simulator, the problem would occur. But if you use an iOS device, everything is fine....
I believe Xcode still has bugs with SpritKit.


text:
Q: .net Maui ViewList Binding with an ObservableCollection I have a ObservableCollection: tags
and for that the Property: Tags
They should be the ItemsSource for my List View: tagList
Until now I got a List from another method and iterated them into tags the whole time but now
that takes too long.
But now I found a simpler way to fill the list without iterating it from one to another but the problem is that. But it doesn't display the tags in the Listview so I tried it to bind it per the xml code but it doesn't seem to work.
Here is the XML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TagEditor.TagPage"
             Title="TagPage">
    <VerticalStackLayout
        Spacing="5"
        HorizontalOptions="Center">

        <RefreshView
            x:Name="RefreshScroll">
            <ScrollView
                    HeightRequest="500"
                    WidthRequest="500"
                    VerticalOptions="StartAndExpand"
                    VerticalScrollBarVisibility="Always"
                >
                <VerticalStackLayout>
                    <ListView
                        x:Name="tagList"
                        ItemsSource="{Binding Tags}"
                        BackgroundColor="LightGray"
                    >
                    </ListView>
                </VerticalStackLayout>
            </ScrollView>
        </RefreshView>

    </VerticalStackLayout>
</ContentPage>

and here is the c# code
    private ObservableCollection<Tag> tags = new();

    public ObservableCollection<Tag> Tags { get { return tags; }  set { tags = value; } }

    public TagPage(TagFinder tagFinder)
    {
        MessagingCenter.Subscribe<MainPage>(this, "DISCONNECT", (sender) =>
        {
            MainThread.BeginInvokeOnMainThread(() =>
            {
                Application.Current?.CloseWindow(this.Window);
            });
        });
        InitializeComponent();
        tagList.ItemsSource = Tags;
        try
        {
            UpdateSearchresults();
        }
        catch (FileNotFoundException e)
        {
            DisplayAlert("Error", e.Message, "Ok");
        }
    }

What would I have to do so the Tags are beeing used as the ItemsSource?

A: Based on your code, I did a test ,and it works on my side.
You can add Cell label to display each item of ListView.
Please refer to the following code:
  <ListView x:Name="tagList"
            ItemsSource="{Binding Tags}"
            BackgroundColor="LightGray">
        <ListView.ItemTemplate>
                  <DataTemplate>
                       <TextCell Text="{Binding Name}"
                                 Detail="{Binding MyProperty}"/>
                   </DataTemplate>
         </ListView.ItemTemplate>
  </ListView>

note:
Name and MyProperty bound to TextCell are all my own definitions.

A: Here is solution using Xml Linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication40
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {

            XDocument doc = XDocument.Load(FILENAME);
            XNamespace ns = doc.Root.GetDefaultNamespace();
            XNamespace nsX = doc.Root.GetNamespaceOfPrefix("x");

            XElement listView = doc.Descendants(ns + "ListView").FirstOrDefault();
            string name = (string)listView.Attribute(nsX + "Name");
        }
    }

}


text:
Q: Html to WordPress scripts not working after enqueue it's like a small headache now, I am trying to enqueue the javascript files in functions.php but they are not working after 100's of tries. Let me know what is the issue, why my javascript file isn't working.
<?php

function ct_styles(){
    wp_enqueue_style('style', get_stylesheet_uri());
    wp_enqueue_style('style_bootstrap', get_theme_file_uri('assets/css/vendor/2-bootstrap.min.css'));
    wp_enqueue_style('style_pack', get_theme_file_uri('//unpkg.com/aos@next/dist/aos.css'));

}
add_action('wp_enqueue_scripts', 'ct_styles');

function ct_scripts(){
    wp_enqueue_script('jquery');

    wp_enqueue_script( 'ct_bootstrap', get_theme_file_uri( '/assets/js/vendor/2-bootstrap.min.js' ), array(), '1.0.0', true );
    wp_enqueue_script( 'simplebar', get_theme_file_uri( '/assets/js/vendor/4-simplebar.min.js' ), array(), '1.0.0', true );
    wp_enqueue_script( 'ct_pack', get_theme_file_uri( '//unpkg.com/aos@next/dist/aos.js' ), array(), '1.0.0', true );
    wp_enqueue_script( 'ct_lazy', get_theme_file_uri( '/assets/js/vendor/lazysizes.min.js' ), array(), '1.0.0', true );
    wp_enqueue_script( 'ct_main', get_theme_file_uri( '/assets/js/scripts.min.js' ), array(), '1.0.0', true );

}
add_action('wp_enqueue_scripts', 'ct_scripts');
?>

A: Try like this
get_template_directory_uri() = parent theme
get_stylesheet_directory_uri() = child theme
function add_theme_scripts() {

 wp_enqueue_style( 'style_bootstrap', get_template_directory_uri(). '/assets/css/vendor/2-bootstrap.min.css', array(), null, 'all');
 //Add other required css

wp_enqueue_script( 'ct_bootstrap', get_template_directory_uri() .'/assets/js/vendor/2-bootstrap.min.js',array ( 'jquery' ), null, true);
 //Add other required js

}
add_action( 'wp_enqueue_scripts', 'add_theme_scripts' );


text:
Q: Can not Connect Drupal to DB only on AWS uploaded an existing drupal codebase to a virtual host set up on AWS. it is showing "can not connect to database"
I created database "dbname" and can connect fine through ssh. But can not get settings.php to connect. As far as I can tell the mysql user has all needed permissions to access the db remotely.
what I have
$db_url = 'mysql://username:password@us-west-rds.amazonaws.com/dbname';

Here is example of settings.php with a drupal 7 site of ours that connects fine
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'dbname',
      'username' => 'dbuser',
      'password' => 'password',
      'host' => 'us-west-rds.amazonaws.com',
      'port' => '3306',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

A: There are several things to check:

*

*do you have the security group open to allow access from your server (as said by Bob Kinney in the other answer)?

*do you have a firewall set up on your server that prevents connecting to your RDS instance?

*does your user have sufficient rights to connect to your database?

The easiest way to debug this is to use the console mysql command and try to connect to your instance from there:
mysql dbname -u username -p password -h db01b2.ck1dmcn6kfws.us-west-1.rds.amazonaws.com

If this does not work, check the points given above. If this works and does not work in Drupal only, check your PHP code and/or Drupal config.

A: Sounds like you may not have set up your security groups to allow access from your EC2 instances.  You'll want to make sure your DB security group has an ingress rule to allow traffic from your EC2 instance/security group.
How do I control network access to my DB Instance(s)?

A: You're pointing at the wrong hostname.
'host' => 'us-west-rds.amazonaws.com'

Each individual database instance will have it's own hostname. You can look it up in the AWS Console. The one you're currently pointing to looks like you intended to point to the RDS web service API endpoint.

A: You might also want to check...
setsebool httpd_can_network_connect_db on


text:
Q: How to execute a Group Collection Query using Firestore? (IOS) Hey everybody this is my first time asking a question on here so if the posting is incorrect etc... i apologize in advance.
I'm working on a project where students at the university I go to will be able to request a Resident Advisor to unlock their rooms for them. I'm stuck on how to query the entire(root) collection to find a  subcollection with a field that contains a value that matches my collection ID. I've seen a lot of resources on Stack, Firebase, and i've tried to implement them but I've had no succes.
Here's a picture:
Accessing the Subcollection
My code snippet is:
db.collectionGroup("Dorms").whereField("UID", isEqualTo: UID).getDocuments { (snapshot, error) in

// here is where i'd like to gather the fields subcollection/document and then store them as variables

Thank you in advance for any help and advice. It's greatly appreciated!

A: This is my first time posting an answer so I hope this is somewhat helpful, but in my experience when querying files in a collection I create a forloop then use if let statements to get variables from the document
var someVariable : Int

db.collectionGroup("Dorms").whereField("UID", isEqualTo: "UID").getDocuments { (snapshot,  error) in
        if let e = error {
            //this is printing the error if there is one getting the documents
            print("There was an error getting the documents \(e)")
        } else {
            if let dorms = snapshot?.documents { //accesses all the documents in the collection
                for doc in dorms {
                    let data = doc.data() //Gets all the information in the document
                    //Here you would use an if let to create variables from the information in the data
                    //For example
                    if let dormRoomNumber = data["dormRoomNumber"]/*You'll put the name of your field in here, so whatever you have named it in firestore*/] as? Int //make sure the the data type here mathces the data type in your firestore database
                    {
                        someVariable = dormRoomNumber
                    }
                }
            }

        }
    }


text:
Q: WooCommerce Images are uploading to the server but not attaching I've Created a Script that Grabs an image from an external site and it is imported to the WordPress image gallery. -> wp-admin/upload.php [Media Library]

My Code Snipplet
foreach($url as $linkurl) {
    $tmp = download_url( $linkurl);

    preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $linkurl, $matches);

$clean = str_replace(array("%2B", "%52", "%20", "%5"), "B", basename($matches[0]));

$file_array = array(
    'name' => basename( $clean ),
    'tmp_name' => $tmp
);

if ( is_wp_error( $tmp ) ) {
    @unlink( $file_array[ 'tmp_name' ] );
    return $tmp;
}

$id = media_handle_sideload( $file_array, $post_id, 'gallery desc' );

$value = wp_get_attachment_url( $id );

update_post_meta($post_id,  array_push($post_id, '_product_image_gallery', $id));

//update_post_meta($post_id,  array_push($post_id, '_product_image_gallery', $value ));

}

What am I doing Wrong

A: I think that you have made a mistake in the last line. array_push is not doing what you are trying to achieve (check the Manual) same as update_post_meta accepts different arguments.

Besides that WooCommerce is storing galleries in simple comma separated list like 1,45,78,34 so you should change the last line
update_post_meta($post_id,  array_push($post_id, '_product_image_gallery', $id));
to
update_post_meta($post_id, '_product_image_gallery', $id);
or if you add multiple images then instead of $id enter comma separated list.


text:
Q: Queston on Karatsuba Recursion I'm trying to implement a recursive Karatsuba algorithm. I successfully coded a recursive algorithm for multiplication but it calculates ad and bc.
However, for this program, I've tried noting down each intermediate value namely ac, bd, total, sum. Many values don't turn up as the expected value. I can't figure out where my code is getting messed up. I'm still an amateur programmer and I've spent already several hours trying to debug but now I have no choice but to post my large code here:
#include <iostream>
using namespace std;

int approxLog(int n, int b) {
    return !(n/b < 1) ? 1+approxLog(n/b, b) : 1;
}

int power(int b, int e) {
    return (e < 1) ? 1 : b*power(b, e-1);
}

int odd1(int n) {
    if(n%2 != 0)
        return n-1;
    else
        return n;
}

int odd2(int n) {
    if(n%2 == 0)
        return n/2;
    else
        return n/2 + 1;
}

void num_split (int num, int d, int *a, int *b) {
    int  i = 1, tmp = 0, j = 1, k = 0;
    while (i <= d/2) {
        tmp += (num%10)*power(10, i-1);
        num /= 10;
        i++;
    }
    *b = tmp;
    tmp = 0;
    while (i <= d) {
        tmp += (num%10)*power(10, j-1);
        num /= 10;
        i++;
        j++;
    }
    *a = tmp;
    tmp = 0;
}

long long int multiply(int x, int y, int n) {
    int a = 0, b = 0, c = 0, d = 0;
    int ac = 0, bd = 0, total = 0, sum = 0;
    int *ptr_a = &a;
    int *ptr_b = &b;
    int *ptr_c = &c;
    int *ptr_d = &d;
    num_split(x, n, ptr_a, ptr_b);
    num_split(y, n, ptr_c, ptr_d);

    if((x < 10) || (y < 10)) {
        return x*y;
    }
    else {
        ac = multiply(a, c, odd2(n));
        bd = multiply(b, d, n/2);
        total = multiply((a+b), (c+d), odd2(n));
        // cout << total <<  endl;
        sum = total - ac - bd;
        return power(10, odd1(n))*ac + power(10, n/2))*sum + bd;
    }
}

int main() {
    int x = 1234, y = 1234;
    int n = approxLog(x, 10);
    long long int product = multiply(x, y, n);
    cout << product << endl;

    return 0;
}

A: The problem is that in each recursion, you should take the approx. log of the the bigger of x and y. So the following alteration in your code would fix the problem (notice the commented out portions too!):
long long int multiply(int x, int y)//, int n)
{
    int a = 0, b = 0, c = 0, d = 0;
    int ac = 0, bd = 0, total = 0, sum = 0;
    int *ptr_a = &a;
    int *ptr_b = &b;
    int *ptr_c = &c;
    int *ptr_d = &d;
    int n = (x>y)?approxLog(x, 10):approxLog(y, 10);
    num_split(x, n, ptr_a, ptr_b);
    num_split(y, n, ptr_c, ptr_d);

    if((x < 10) || (y < 10)) {
        return x*y;
    }
    else {
        ac = multiply(a, c);//, odd2(n));
        bd = multiply(b, d);//, n/2);
        total = multiply((a+b), (c+d));//, odd2(n));
        cout << total <<  endl;
        sum = total - ac - bd;
        return power(10, odd1(n))*ac + power(10, (n/2))*sum + bd;
    }
}

int main() {
    int x = 134546, y = 1234;
    //int n = approxLog(x, 10);
    long long int product = multiply(x, y);//, n);
    cout<<"Karatsuba: "<<product<<endl;
    cout<<"Normal:    "<<x*y<<endl;

    return 0;
}


text:
Q: cuda sprintf to global/shared memory buffer We can do printf in kernels now,
but is it possible to do the sprintf(buffer, format, arg, ... ) function?
I'm doing cuda accelerated OBJ file writing, and I need to convert floats into ASCII strings for writing.
edit: Cuda is not doing the actual writing of course =) Just generating the obj char buffers from a list of floats.

A: Besides the va_list, the code from Georges Menie should help you get started. Also, for simple argument list, simplePrintf exposed a few as @RobertCrovella mentioned. C++11 features of recent CUDA distributions might also help.
However, parallelisation of this task on the GPU and maintaining consistency in object list indices and consistent string formatting (floatting point especially) might be your biggest issue.


text:
Q: Google drive, onedrive or box which is the fastest API method for displaying complete folder contents? We are working on a web application for photo selections/proofing. To manage the photo albums, we want to use a file sharing service like dropbox, google drive, onedrive etc.
One of our use cases includes displaying albums with large quantity of photos inside our web application. We are currently using dropbox to fetch complete folders (albums) but since the dropbox api doesn't offer batch requests, it takes A LOT of time to generate individual share links and display inside our application (in terms of hours)
I am personally checking other APIs too but will really appreciate little guidance from people having experience with other APIs like google drive, onedrive, box.com etc
What will be the best method/api to achieve the use case efficiently?
Like I personally think if we have a batch operations available, we would be able to fetch an album of 3000 photos (120 kb avg size) in less than 5 minutes on a normal internet connection.

A: All services you mention (dropbox, onedrive, google drive) offer a thumbnail service. My advice is to use that functionality first.
So (supported by all services):

*

*request meta data about all files in folder (one call), including thumbnail URL and id. Normally this request is paged. For 3000 images you need only three requests (if page-size is 1000, the maximum for Google Drive API)

*display thumbnails (using the cached URL)

*retrieve actual image if user selects thumbnail based on the cached id. Which is one call

We integrated with all three services (and s3) and in my experience, the performance is more than enough for this kind of scenario.


text:
Q: Migración Wordpress problema de redirección Mi problema es el siguiente:
Tenia un sitio web montado en godaddy.com,
hice una migración desde ahí hacia un nuevo hosting con nuevo dominio.
los pasos a seguir fueron :

*

*Mediante FTP descargar todo el contenido de la carpeta public html.

*Exportar la BDD.

*Subir el contenido a la nueva public html.

*Crear una nueva base de datos y usuario, asociarlos e importar la BDD.

*Usar la herramienta "https://interconnectit.com" (También probe con los comandos SQL y los plugins de search and replace)

*Actualice en enlaces permanentes desde la administración de wordpress.

Aun así desde la barra de navegación me sigue redigiriendo al dominio anterior, funcionando bien solo el home.
(la redirección del menu es del tipo oldsite.com/page en vez de newsite.com/page)
He probado miles de soluciones sin resultado.
Hay una sola solución que no he probado porque el hosting nuevo no me permite el acceso al archivo httpd.conf.
Encontrada en :
" https://wordpress.stackexchange.com/questions/14685/after-server-migration-only-the-homepage-works "
Necesito de su sabiduría querida comunidad.
Solución :
Se debio cambiar manualmente las redirecciones en los archivos footer.php y header.php
PD :Gracias a todos.

A: Generalmente es el proceso que suelo utilizar yo tambien. Posibles cosas que debes de revisar:

*

*Lo primero es comprobar que en la base de datos ya no queda nada con la URL anterior, entiendo que con Search & Replace has cambiado todo http://oldomain.com por http://newdomain.com. Si no queda nada de la URL antigua vamos bien.

*Tienes que verificar que no tienes ningún plugin de caché que pueda estar haciendo de las suyas, en caso de que sea así borra el caché o directamente desactiva el plugin

*Si tenias algun plugin de seguridad tipo iThemes o Wordfence revisa que en su configuración no tengas algo forzado, aunque Search & Replace toque toda la BBDD, esos plugin generan .htaccess en varios directorios.

*Verifica que tu .htaccess no tenga nada del antiguo dominio. Si tienes acceso SSH a tu directorio lo puedes hacer usando esto: egrep -r 'oldomain.com' *

*Por ultimo, intenta entrar a la página en modo "incógnito" del navegador, si por alguna cosa estabas haciendo redirecciones 301, el navegador puede haberlas cacheado y llevándote a confusión.

*Como te comentan por aquí, puedes comprobar las DNS (por si fuera el problema) de que estén apuntando al antiguo servidor y que estes cargando otra página web, aquí tienes un par de herramientas: https://www.dnswatch.info/ y https://www.whatsmydns.net/
Si todo esto que te he comentado no soluciona el problema, tendrás que mirar el error log del sistema y comentarnos algo.


text:
Q: cakephp: cant pre-select a related model when adding I think i've missed something. (cakephp)
I have a hasMany relationship from applicants to employers.And when i view an applicant, i see the related employers table all working perfectly (thanks to bake!)
But if i click 'New Employer', i want the applicants dropdown to pre-select so that i can hide it. i just cant figure out how i'd pass the applicant_id to the add view for employers.
(if i edit an employer from the related employers table for an applicant, the applicant_id does get passed)
Can anyone help? please?
Vauneen

A: Simple. Pass the applicant_id to your employers/add action.
One way to do this is through URL parameters. Example: /employers/add/3 will pass "3" to the add action, and this could be taken as the applicant ID. Here's the controller code:
function add($applicantId = null) {
    // Optional: Check if $applicantId is provided
    if (!$applicantId) {
        $this->Session->setFlash('Applicant ID is missing.');
        $this->redirect(array('action' => 'index'));
    }
    // Process action
    if (!empty($this->data)) {
        $this->Employer->create();
        if ($this->Employer->save($this->data)) {
            // etc ...
        }
    } else {
        // Insert default values such as applicant_id into the form
        $this->data = array(
            'Employer' => array(
                'applicant_id' => $applicantId
            )
       );
    }
}

Now, you need to ensure that all links provide the applicant ID parameter:
echo $this->Html->link('Add Employer', array('controller' => 'employers', 'action' => 'add', 3);

(Note: The last element "3" is the applicant ID)
Finally, you can hide the applicant ID from the form in the add.ctp file:
echo $this->Form->input('applicant_id', array('type' => 'hidden'));

Hope that helps!