text:
Q: Login PHP: User Level Login in single page using MYSQL sorry if what I'm about to ask is something really basic, but I've been stuck on this for two weeks.
I have a login page where User can login to my website. Different user's role will be prompt to different pages. Now, the login is fine, but when my user key in wrong password or username, there's no warning triggered and user stays on the blank login.php page when user supposed to be redirected back at index.php and warning is triggered.
Below is my code
login form (index.php)

  <form method="post" action="login.php">

      <input type="username" name="username" class="form-control" placeholder="Username">

      <input type="password" name="password" class="form-control" placeholder="Password">

        <button class="btn btn-primary btn-block btn-flat" type="submit" name="login" value="true">Sign In</button>

  </form>

and here my back end script (login.php)

<?php
session_start();
$conn=mysqli_connect('localhost','root','','snapshot');
//Getting Input value
if(isset($_POST['login'])){
  $username=mysqli_real_escape_string($conn,$_POST['username']);
  $password=mysqli_real_escape_string($conn,$_POST['password']);
  if(empty($username)&&empty($password)){
  $error= 'Fields are Mandatory';
  }else{
 //Checking Login Detail
 $result=mysqli_query($conn,"SELECT*FROM user WHERE username='$username' AND password='$password'");
 $row=mysqli_fetch_assoc($result);
 $count=mysqli_num_rows($result);
 if($count==1){
      $_SESSION['user']=array(
 'id' =>$row['id'],
 'username'=>$row['username'],
 'uname'=>$row['uname'],
 'password'=>$row['password'],
 'role'=>$row['role']
   );
   $role=$_SESSION['user']['role'];
   //Redirecting User Based on Role
    switch($role){
  case 'user':
  header('location:user/dashboard.php');
  break;
  case 'management':
  header('location:management/index.php');
  break;
  case 'admin':
  header('location:admin/index.php');
  break;
 }
 }else{
 $error='Your PassWord or UserName is not Found';
 }
}
}
?>

and before asking I already read few similar questions and find no solutions. Thank you in advance for the help.

A: At the end of login.php you're setting the value of $error to Your PassWord or UserName is not Found - however nothing further is happening.
Your switch that redirects the user only comes into play if the user is found in the database, on a side note here you should be encrypting the users password and comparing the hashes.
To solve your issue, try doing something like the following:
} else {
 $error='Your PassWord or UserName is not Found';
 header('location:login.php?error=' . $error);
}

Then in your login form you can simply check for the error message and display it:
<?php if(isset($_GET['error'])): ?>

<?= $_GET['error'] ?>

<?php endif ?>


text:
Q: What is the time complexity of Trsm and other BLAS operations? I am accelerating a model by replacing all its linear algebra operations with cuBlas's functions. And I want to get the time complexity or FLOPs of the model to evaluate its performance in roofline model.
There are two kinds of operation in the model: Gemm and Trsm.
I know the FLOPs of Gemm is about 2 * k * m * n from the question : How to compute the achieved FLOPS of a MPI program which calls cuBlas function:

The standard BLAS GEMM operation is C <- alpha * (A dot B) + beta * C and for A (m by k), B (k by n) and C (m by n), each inner product of a row of A and a column of B multiplied by alpha is 2 * k + 1 flop and there are m * n inner products in A dot B and another 2 * m * n flop for adding beta * C to that dot product. So the total model FLOP count is (2 * k + 3) * (m * n) when alpha and beta are both non-zero.

But for Trsm, I have no idea about its computation complexity. All the documents I found say it's about O(n^3) which isn't clear enough to get the computation complexity.
Sincerely thank you for your answers!

A:
But for Trsm, I have no idea about its computation complexity. All the documents I found say it's about O(n^3) which isn't clear enough to get the computation complexity.

It's about O(n^2) not O(n^3).
TRSM performs a number of different implementation depending on the form of the matrix, but for the canonical B <- alpha * inv(A) dot B where B is (m by n) and A is a non-unit upper triangular matrix, the operation count should be something like n * (3/2*m + 1) [n diagonal scaling operations plus 1/2 * 3 * m * n operations over all the non-zero row entries]
If you want to know the exact FLOP count for the reference implementation of any of the BLAS or LAPACK routines, the obvious way to do it is inspect the reference serial code and count the floating point operations, either by hand or by instrumentation of the code itself.

redpajama_set_name: RedPajamaStackExchange


text:
Q: K-means Clustering in C++ Implementation Help and Improvement I was given an array of colors and my task is to estimate the real 2 different colors out of the array. So I figured I'll try to do a k means algorithm to best estimate the two colors and index which input is which, but my algorithm doesn't find the centroids well. And by well I mean the centroids are completely off.
What I do wrong?
Here is my full code:
#include <iostream>
#include <sstream>
#include <array>
#include <algorithm>
#include <cmath>
#include <cassert>
#include <vector>

using namespace std;

struct color {
    float red;
    float green;
    float blue;
};

void kMeansClustering(vector <color>* stick, vector <color>* centroids, int k , vector <int>* clustID);
float DistColors(color centroid, color c);
void UpdateCentroids(vector <color>* stick, int k , vector <color>* centroids , vector <int>* clustID);
color ColorEstimator(vector <color>* stick, int k, int epochs, vector <int>* clustID);

int main()
{

    array<color, 50> input = { { {231.40743881294037, 237.44965622220946, 254.77121736965333}, {228.5534410910449, 235.464386448478, 242.19988902045463}, {230.30772169389454, 238.72320816537146, 250.49564182065964}, {227.15016686772202, 236.24691719267867, 252.90235409762704}, {230.41895618727227, 238.657597362693, 248.29153087604715}, {229.93684620291512, 234.01819943500396, 249.60623949753426}, {228.42175736330205, 238.34361201766305, 247.2204140886806}, {227.84022562034895, 236.5214355504492, 247.8538373236252}, {227.71544053823285, 240.16861817247062, 254.60425325391995}, {226.58842798166197, 237.68042876356262, 254.71957768401475}, {230.88840479065888, 236.7678042900178, 248.61150119469562}, {226.86912093334206, 235.8884424252573, 247.88671586964455}, {227.45517488635113, 240.3819316766157, 250.51481023872068}, {229.59861886575894, 235.83584959054974, 251.46889400577427}, {229.23367809030552, 237.24044401350025, 249.4279962431541}, {228.32192716816607, 237.05340803933723, 250.64537320750122}, {230.08628579311065, 235.0134454354286, 246.5735753630862}, {229.252340468657, 234.00910635835228, 249.34217504033197}, {225.22447511374702, 239.4709613428637, 246.4458975263566}, {225.61187564359977, 235.66097995340849, 249.02345892965656}, {229.79637417586468, 239.10337544176383, 246.92327185739796}, {227.58812892987137, 240.21670944169784, 250.60935853418786}, {228.41945997585944, 238.11672487783682, 253.91798978403156}, {228.96868361083293, 235.2705636041433, 251.18917992896004}, {229.28284008153832, 239.37264981015255, 250.3604105076603}, {231.5687396936171, 232.90968630866203, 243.5450028582501}, {229.40662599794854, 236.45161336682256, 248.05397175207972}, {228.70207834717965, 243.15024540608889, 250.5010381192849}, {229.95651741532535, 239.64157110660392, 248.80395810592591}, {228.9988967797162, 236.21108589663837, 246.07611157333568}, {122.69433611768231, 169.37473153784, 66.18694573878635}, {125.25289749728812, 169.7640666346183, 68.91076979782899}, {123.38953288543718, 168.98423240064878, 68.2114085083602}, {125.35729146507643, 169.51176403300119, 69.78421062439558}, {124.3884981048362, 168.94995025162697, 68.63663408419842}, {126.73444024584143, 171.7928274202038, 69.00474217104087}, {124.01034543440451, 167.87622211655415, 67.71426849138949}, {123.3329143640377, 170.10828953207476, 68.18084821738653}, {124.05385478199051, 169.44109340129506, 70.42607758635805}, {126.15353870421363, 170.69852488354542, 66.82441574127802}, {229.0877270736824, 236.21275756861388, 249.53741724579652}, {231.4238125605047, 238.34822768240278, 249.30582303433133}, {228.28016325966595, 232.5048867215949, 246.89611636914483}, {227.27386122243635, 241.11957952107088, 251.0571248642451}, {225.13067522766005, 235.50757722085427, 249.22992628681828}, {227.9106192249585, 233.08165289848347, 248.3099867450273}, {227.52684451385937, 238.51789816429803, 251.5834717176488}, {224.408858290033, 233.5616065285502, 247.7543836219995}, {226.51482613575666, 239.76326979626094, 247.35607749364993}, {228.60095253722585, 238.309990231983, 244.90373176067322} } };
    vector<color> inputVector(input.begin(), input.end());
    vector <int> clustId;
    int epochs = 5, k=2;
    ColorEstimator(&inputVector, k, epochs, &clustId);
    return 0;
}

void kMeansClustering(vector <color>* stick, vector <color>* centroids,int k, vector <int>* clustID)
{
    vector <float> minDistance;
    color c;
    float dist;
    int colorIndex, clusterId ;

    for (vector<color>::iterator i = centroids -> begin();
        i != centroids -> end(); ++i) {
        // quick hack to get cluster index
        clusterId = i - centroids->begin();
        c = *i;
        //cout << c.red << " " << c.green << " " << c.blue << endl;
        for (vector<color>::iterator it = stick->begin();
            it != stick->end(); ++it) {

            c = *it;
            //cout << c.red << " " << c.green << " " << c.blue << endl;
            dist = DistColors(*i , c);
            // quick hack to get color index
            colorIndex = it - stick->begin();
            if (minDistance.size() < stick->size())
            {
                minDistance.push_back(dist);
                clustID->push_back(clusterId);
                continue;
            }
            //cout << minDistance.at(colorIndex);
            if (dist < minDistance.at(colorIndex))
            {
                clustID->at(colorIndex) = clusterId;
                minDistance.at(colorIndex) = dist;
            }
        }
    }
}

float DistColors(color centroid, color c)
{
    return sqrt(pow(centroid.red - c.red, 2) + pow(centroid.green - c.green, 2) + pow(centroid.blue - c.blue, 2));
}

void UpdateCentroids(vector <color>* stick, int k, vector <color>* centroids, vector <int>* clustID)
{
    vector<int> nPoints;
    vector<double> sumRed, sumGreen, sumBlue;
    int colorIndex, clusterId;

    // Initialise with zeroes
    for (int j = 0; j < k; ++j) {
        nPoints.push_back(0);
        sumRed.push_back(0.0);
        sumGreen.push_back(0.0);
        sumBlue.push_back(0.0);
    }

    // Iterate over colors to append data to centroids
    for (vector<color>::iterator it = stick->begin();
        it != stick->end(); ++it) {
        colorIndex = it - stick->begin();
        clusterId = clustID -> at(colorIndex);
        nPoints[clusterId] += 1;
        sumRed[clusterId] += it->red;
        sumGreen[clusterId] += it->green;
        sumBlue[clusterId] += it->blue;
    }
    cout << nPoints.size() << endl;
    // Compute the new centroids
    for (vector<color>::iterator c = centroids ->begin();
        c != centroids->end(); ++c) {
        clusterId = c - centroids->begin();
        c->red = sumRed[clusterId] / nPoints[clusterId];
        c->green = sumGreen[clusterId] / nPoints[clusterId];
        c->blue = sumBlue[clusterId] / nPoints[clusterId];
        //centroids->at(clusterId) = c;
        //cout << c->red << " " << c->green << " " << c->blue << " " << nPoints[clusterId] << endl;
    }
}

color ColorEstimator(vector <color>* stick, int k, int epochs, vector <int>* clustID)
{
    vector <color> centroids;
    color c;
    int n;
    // Initialising the clusters
    n = stick->size();
    for (int i = 0; i < k; ++i) {
        //c = {(float) (rand() % 256) , (float)(rand() % 256), (float)(rand() % 256) };
        c = stick->at(rand() % n);
        centroids.push_back(c);
    }
    for (int e = 0; e < epochs; e++)
    {
        //c = centroids.at(1);
        //cout << c.red << " " << c.green << " " << c.blue << endl;
        kMeansClustering(stick, &centroids, k, clustID);
        UpdateCentroids(stick, k, &centroids, clustID);
        //c = centroids.at(0);
        //cout << c.red << " " << c.green << " " << c.blue << endl;
    }
    return c;
}

A: I found the bug to the code.
The way I update my cluster indices vector for every color is wrong, instead of reassigning a value I added a value to the vector which made it really big and so it didn't work.
That was the main reason why the code I posted didn't work, I changed it to:
void kMeansClustering(vector <color>* stick, vector <color>* centroids,int k, vector <int>* clustID)
{
    vector <float> minDistance;
    color c;
    float dist;
    int colorIndex, clusterId ;

    for (vector<color>::iterator i = centroids -> begin();
        i != centroids -> end(); ++i) {
        // quick hack to get cluster index
        clusterId = i - centroids->begin();
        c = *i;
        for (vector<color>::iterator it = stick->begin();
            it != stick->end(); ++it) {

            c = *it;
            dist = DistColors(*i , c);
            // quick hack to get color index
            colorIndex = it - stick->begin();
            if (minDistance.size() < stick->size())
            {
                minDistance.push_back(dist);
                if(clustID->size() < stick->size())
                {
                    clustID->push_back(clusterId);
                }
                else {
                    clustID->at(colorIndex) = clusterId;
                }
                continue;
            }
            //cout << minDistance.at(colorIndex);
            if (dist < minDistance.at(colorIndex))
            {
                clustID->at(colorIndex) = clusterId;
                minDistance.at(colorIndex) = dist;
            }
        }
    }
}


text:
Q: Android pick activity text color I have a problem with pick activity, i have this popup :

Text color is white and background too.
This is code i use :
    Bundle bundle = new Bundle();
    ArrayList<String> shortcutNames = new ArrayList<String>();
    shortcutNames.add(getString(R.string.group_applications));
    bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);

    ArrayList<ShortcutIconResource> shortcutIcons = new ArrayList<ShortcutIconResource>();
    shortcutIcons.add(ShortcutIconResource.fromContext(this,
            R.drawable.ic_launcher));
    bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);

    Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
    pickIntent.putExtra(Intent.EXTRA_INTENT, new Intent(Intent.ACTION_CREATE_SHORTCUT));
    pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.app_name));
    pickIntent.putExtras(bundle);

    startActivityForResult(pickIntent, 1);

A: I finally got the solution:
You need to use
Intent pickIntent = new Intent(Intent.ACTION_CHOOSER);

The rest is still the same.
This code will give you the Holo dialog.


text:
Q: Unique[] in RHS of rule I have a function, explicit that takes dot product of two symbols, and replaces it with repeated dummy indices generated by Unique[].
explicit[expr_] :=
  expr //. {Dot[a_, b_] :> (Subscript[a, #] Subscript[b, #]) &[
  Unique[]]};

So that if my input is v.w, then the output is $v_{$3}w_{$3}$ which is good.
The problem is that if there is a single term multiplying two pairs of dot products, I don't know how to get Unique[] to generate a new symbol for each pair.  That is, if I input c.d e.f the output is $c_{$3}d_{$3}e_{$3}f_{$3}$, which is bad.  I want $c_{$3}d_{$3}e_{$4}f_{$4}$, with new repeated subscripts. How do I modify my code?

A: You merely need to watch your operator precedence.  Here with brackets to group the RHS properly:
explicit[expr_] :=
  expr //. {Dot[a_, b_] :> ((Subscript[a, #] Subscript[b, #]) &[Unique[]])};

explicit[c.d e.f]


text:
Q: Connectedness and path connectedness of a union
Exercise: Let $A = \{(x, \sin (1/x)): 0<x\le 1\}$ and $B = \{(x,y)\in\mathbb R_{\le 0}\times\mathbb R | 0.5\le |y|\}$ be sets and $X = A\cup B$ the union.
  Show that $X$ is connected and path connected.

For connectedness: $A$ and $B$ are a cross-product of intervals so they are connected, but I don't how to prove the connectedness of the union.
Path connectedness: For $A$ it is clear. It is the path $\alpha (s)=(s,\sin (s^{-1})), s\in [a,b]$ for $a,b\in A$. But for the rest I don't know how to get the path. For explicit examples, it is clear that $X$ is path connected but I find no general solution.
Generally It is enough to prove the connectedness with path connectedness.

A: I am assuming that $B= (-\infty,0]\times \{y\in R: |y|\geq 1/2\}.$ Then $A\cup B$ is NOT path-connected.
Proof : Assume that $f:[0,1]\to A\cup B$ is continuous with $f(0)=(1,\sin 1)$ and $f(1)\in B.$
Let $r=\min \{t\in (0,1] :f(r)\in B\},$ which exists because $f^{-1}B$ is closed in $[0,1]$, and $f(0)\not \in B.$
Let $D =\{f(t): t\in [0,r)\}.$
$\bullet$ We have $ D=A$ because

*

*$f(r)\in B$ and the continuity of $f$ require that $f(r)\in Cl_{A\cup B} D$, with $D\subset  A,$ so $\inf \{x\in  [0,r) :(x,\sin 1/x ) \in D \}=0,$ and

*$ D$ is a connected space as it is a continuous image of $[0,r),$ so if  $(z,\sin 1/z)\in A\backslash D$ then  $\{(x,y)\in D :x<z\}$ and $\{(x,y)\in D :x>z\}$ are disjoint non-empty subsets of the space $ D,$ and their union is $D,$ contradicting connectedness of $D$.
$\bullet$ Now let $f(r)=(0,s).$ We have $1/2\leq |s|\leq 1$ because the continuity of $f$ implies $(0,s)\in (Cl_{A\cup B} D)\cap B=(Cl_{A\cup B} A)\cap B=\{(0,y): 1/2\leq |y|\leq 1\}.$
$\bullet$ Consider the function $g:[0.1]\to A\cup B$ where $g(t)=f(t r)$ for $t \in [0,1]$. Now $g$ is a path from $(1,\sin 1)$ to $(0,s)$ with $\{g(t): t\in [0,1)\}=D=A.$
$\bullet$ And consider the nbhd $V=(A\cup B)\cap \{(x,y): |x|<1/4 \land |y-s|<1/4\}.$ There exists $d>0$ such that $t\in (1-d,1]\implies g(t)\in V.$
$\bullet$ Now the space $A\cap V$ has infinitely many connected components, and each  connected component $C$ of $A\cap V$ satisfies $B\cap (Cl_{A\cup B} C )=\phi.$ But  since $E=\{g(t):t\in (1-d,1)\}$ is connected,  there must be a component $ C$ of $V\cap A$  such that $E\subset C.$ This implies that $g(1)=f(r)=(0,s)\not \in Cl_{A\cup B}E,$ that is, $g(1)\not\in Cl_{A\cup B}\{g(t):1-d<t<1\},$ contradicting the continuity of $g.$ QED.


text:
Q: recyclerview notifyDataSetChanged stop detecting end of recyclerview for pagination i have a recyclerview and definitely an adapter related to it.
but the problem that am facing when i am calling notifyDataSetChanged the recyclerview will not be able to detect the end of recyclerview is there any possible fix for it ?


text:
Q: What do You Use C++ Exceptions For? Probably exceptions is the most controversial C++ feature. Many teams including google do not use them. Of course the decision to use them or not depends on the context -- for example, in some games it might be ok to crash on out-of-memory, but not in a medical equipment control software. Apart from out-of-memory, some teams may use exceptions for network disruption, file-not-found etc. but others may say this is too common to be called an exception (others may say, but if it is common, so what?)
Often the decision not to use exceptions is based on the potentially misguided argument that it is difficult to write exception-safe code. Some people say the argument is misguided because using the alternative of using error codes will lead to at least as much difficult code. David Abrahams clarifies this point.
In this question, I am curious to know:

*

*For what cases do you use exceptions?

*What is the context of your application? Why can't you live without exceptions?

*How do you manage to write exception-safe code? What is the level of investment you have to make?

*Is/Was it worth it?

A: I'm generally pro-exception for truly exceptional situations, but I probably have a higher bar than most in deciding what's "exceptional".
What makes this hard is that the low-level code must decide what's exceptional, but only the high-level code knows whether a given error is exceptional.  For example, consider a function that loads an icon.  What should it do when it fails?  Only the calling code knows whether the failure is critical (the program NEEDS that icon to proceed) or not (the icon is just decorative).
Practical issues tend to trump elegance.  Constructors that fail have to throw exceptions in order for RAII to work.  On the other hand, destructors shouldn't throw exceptions.  Then there are all the barriers across which you cannot let an exception fly.  For example, in Windows, it's not safe to let an exception propagate out of an OS callback (like a window procedure).  If you're multi-threaded, an unhandled exception in one of your worker threads will bring down the process, without unwinding and calling the d'tors on your other threads.  Device drivers and kernel code generally cannot use C++-style exceptions because of paging constraints.  COM doesn't play nice with exceptions.

A: Although a lot of people treat exceptions in C++ really as 'something exceptional happened', I find them incredibly handy to do basic error-checking / validation as well, mostly at application-level (as in not in the core of the library)
Example, I'd rather write
try
{
  MethodA();
  MethodB();
  //.. a whole lot of other methods crucial to succeed for app initialization
}
catch( const SomeException& e )
{
  //show user the critical error contained in e
  return 1;
}

then writing
if( !MethodA() )
{
  //retrieve and show error
  return 1;
}
if( !MethodB() || !MethodC() )
{
  //retrieve and show error
  return 1;
}
//etc

This tends to lead to less code, also within the methods themselves.

A: I use exceptions for exceptional behaviour, and not too frequently. When debugging crashes, I frequently use break-on-exception, so if your code is using exceptions to handle things that normally occur, I shall be quietly fuming at you. Use them when things have gone wrong in an unexpected way.
Acceptable example: server your code relies on is unavailable, so your service cannot do anything meaningful.
Example that means I'm annoyed at your code: user entered a number greater than 100, as input to your function which expects a number <=100.
In fact, if you're working on a user-facing application, the user probably shouldn't be able to do anything that generates an exception.
This is a very grey area though, so feel free to upvote/downvote me if you agree/disagree. If you disagree please post a comment saying why - I'm curious to hear other guidelines/rules/metrics.

A: Almost everybody writes code can throw exceptions.  They're all over the standard libraries. Given that, I don't think a "no exception" policy is a good one.
I don't write my own exception-throwing code much, because I don't directly deal with that many things that are likely to go wrong such that throwing would be useful.  If something goes seriously wrong where there's no obvious way to fix it, throwing is a good idea.
I do try to make sure that what I write will work sanely in case of exceptions being thrown.

A: In my experience if I use exceptions to "smartly" recover the exception handling tends to over time become more and more complex when it finally adds way too much overhead compared to value. Instead I have adopted the approach of using exceptions purely for detection, having an exception thrown in a function and logging it at that point allows me to faster find ev. problems. Using hierarchies where you rethrow the exception to capture it in a higher level well I tried that but find it makes the code unnecessarily difficult to follow without a major benefit.

A: Last time I used them:
throw "Constant (appropriate) error message"
when encountering a serious condition.
A couple of times I stuck extra data in global variables, but that was before I wrote multi-threaded code. I'd have to rethink that one (obviously).
Not that I'd recommend this technique anymore.


text:
Q: Differentiate Word manual save from auto save and auto recovery save I want to run some operations only when user does a Word manual save within the Application_DocumentBeforeSave event in my VSTO project (supports Word 2013 and up).
In order to do that, I need to differentiate Word manual save from auto save and auto recovery save.

My current code can only identify the Word auto recovery save.
public void Application_DocumentBeforeSave(Word.Document doc, ref bool SaveAsUI, ref bool Cancel)
{
    object oBasic = Application.WordBasic;
    object fIsAutoSave = oBasic.GetType().InvokeMember("IsAutosaveEvent", BindingFlags.GetProperty, null, oBasic, null);
    if (int.Parse(fIsAutoSave.ToString()) == 1)
    {
        //Auto save triggered by word auto recovery
    }
    else
    {
        //Some operations goes in here
    }
}

fIsAutoSave.ToString() returns 1 only when the save is an auto recovery save. For manual save and auto save, it returns 0. Every time SaveAsUI is false too.
I tried several solution from web, but all of them only identifying the auto recovery save of Word. Could somebody please help me with this?
Thank you in advance.

A: The Word object model doesn't provide anything for that.


text:
Q: Combining index and value sorting with top-K selection Say I have a dataframe with columns A, B, C, and data.
I would like to:

*

*Convert it to a multi-index dataframe with indices A, B and C

*Sort the rows by the the indices A and B of this dataframe.

*Within each A B pair of the index, sort the rows (i.e. the C index) by the value on the column data.

*Get the top 20 rows within each such A B pair, according to the previous sorting on data.

This shouldn't be hard, but I have tried all sorts of approaches, and none of them give me what I want. The following, for example, is close, but it gives me only values for the first group of A B indices.
temp = mdf.set_index(['A', 'B','C']).sort_index()

# Sorting by value and retrieving the top 20 entries:
func = lambda x: x.sort('data', ascending=False).head(20)
temp = temp.groupby(level=['A','B'],as_index=False).apply(func)

# Drop the dummy index (?) introduced in the line above
temp = temp.reset_index(level=0)['data']

Update:
def create_random_multi_index():
  df = pd.DataFrame({'A' : [np.random.random_integers(10) for x in xrange(500)],
                     'B' : [np.random.random_integers(10) for x in xrange(500)],
                     'C' : [np.random.random_integers(10) for x in xrange(500)],
                     'data' : randn(500) })

  return df

E.g. of what I am looking for (showing top 3 elements, note how the data is sorted within each A-B pair) :
             data
A B  C
1 1  10  2.057864
     5   1.234252
     7   0.235246
  2  7   1.309126
     6   0.450208
     8   0.397360
2 2  2   1.609126
     1   0.250208
     4   0.597360
...

A: Not sure I 100% understand what you want, but I think this will do it. When you reset it stays in the same order. The key is the sortlevel(), it sorts lexiographically the levels (and the remaining levels on ties). In 0.14 (coming soon) their is an option sort_remaining which you can play with I think.
In [48]: np.random.seed(1234)

In [49]:  df = pd.DataFrame({'A' : [np.random.random_integers(10) for x in xrange(500)],
   ....:                      'B' : [np.random.random_integers(10) for x in xrange(500)],
   ....:                      'C' : [np.random.random_integers(10) for x in xrange(500)],
   ....:                      'data' : randn(500) })

First set the index, then sort it and reset.
Then groupby A,B and pull out the first 20 biggest elements.
df.set_index(['A','B','C']).sortlevel().reset_index().groupby(
             ['A','B']).apply(lambda x: x.sort(columns='data',ascending=False).head(20)).set_index(['A','B','C'])
Out[8]:
             data
A B  C
1 1  1   0.959688
     2   0.918230
     2   0.731919
     10  0.212463
     1   0.103644
     1  -0.035266
  2  8   1.459579
     8   1.277935
     5  -0.075886
     2  -0.684101
     3  -0.928110
  3  5   0.675987
     4   0.065301
     5  -0.800067
     7  -1.349503
  4  4   1.167308
     8   1.148327
     9   0.417590
     6  -1.274146
     10 -2.656304
  5  2  -0.962994
     1  -0.982679
  6  2   1.410920
     6   1.352527
     10  0.510330
     4   0.033275
     1  -0.679686
     10 -0.896797
     1  -2.858669
  7  8  -0.219342
     8  -0.591054
     2  -0.773227
     1  -0.781850
     3  -1.259089
     10 -1.387992
     10 -1.891734
  8  7   1.578855
     2  -0.498898
  9  3   0.644277
     8   0.572177
     2   0.058431
     9  -0.146912
     4  -0.334690
  10 9   0.795346
     8  -0.137661
     10 -1.335385
2 1  9   1.309405
     3   0.328546
     5   0.198422
     1  -0.561974
     3  -0.578069
  2  5   0.645426
     1  -0.138808
     5  -0.400199
     5  -0.513738
     10 -0.667343
     9  -1.983470
  3  3   1.210882
     6   0.894201
     3   0.743652
              ...

[500 rows x 1 columns]

A: Try this
df.sort('data', ascending=False).set_index('C').groupby(['A', 'B']).data.head(3)

Its not the most readable syntax, but will get the job done
A  B  C
1  1  9     1.380526
      1     0.903524
      7    -0.112363
   2  2     0.284057
      5     0.131392
      1     0.111512


text:
Q: How do I return an error message when the user inputs wrong info? I have a program that displays a numbered list and asks the user to input either a number or name from the list, and loops a block until the user enters "exit", after which it ends.
I want to add a line or two that puts an error message like, "Sorry, I don't seem to understand your request" if the user inputs something that is not on the list (name/number) and is not the word "exit".
I can't seem to figure it out. Any advice? My current code is below.
def start
  display_books
  input = nil
  while input != "exit"
    puts ""
    puts "What book would you more information on, by name or number?"
    puts ""
    puts "Enter list to see the books again."
    puts "Enter exit to end the program."
    puts ""
    input = gets.strip
    if input == "list"
      display_books
    elsif input.to_i == 0
      if book = Book.find_by_name(input)
        book_info(book)
      end
    elsif input.to_i > 0
      if book = Book.find(input.to_i)
        book_info(book)
      end
    end
  end
  puts "Goodbye!!!"
end

A: Seems that you should add an elsif statement in this if:
if book = Book.find_by_name(input)
  book_info(book)
elsif input != 'exit'
  puts "Sorry, I don't seem to understand your request"
end

A: A good template for an interpreter is to build around Ruby's very capable case statement:
loop do
  case (gets.chomp.downcase)
  when 'list'
    display_books
  when /\Afind\s+(\d+)/
    if book = Book.find($1.to_i)
      book_info(book)
    end
  when /\Afind\s+(.*)/
    if book = Book.find_by_name($1)
      book_info(book)
    end
  when 'exit'
    break
  else
    puts "Not sure what you're saying."
  end
end

Although this involves regular expressions, which can be a bit scary, it does give you a lot of flexibility. \A represents "beginning of string" as an anchor, and \s+ means "one or more spaces". This means you can type in find   99 and it will still work.
You can create a whole command-line interface with it if you take the time to specify the commands clearly. Things like show book 17 and delete book 17 are all possible with a bit of tinkering.


text:
Q: Get-PNP**** cmdlets not working even after installing PnP.Powerhsell latest verision I have installed PowerShell 7 and installed module PnP.PowerShell, when i tab the commands, it is working [Get-Help of the cmdlet (Get-PnPGroupMember) provides the required output], but when i run the script getting following error not sure.
Failed;https://abc.sharepoint.com/sites/somesite;The 'Get-PnPGroupMember' command was found in the module 'PnP.PowerShell'

Not sure, where and what i am missing ?

A: After uninstalling Microsoft.Online.SharePoint.PowerShell module and re-installation PnP.PowerShell solved the issue, may the issue is because of having old verision of SharePoint online cmdlets caused the issue.


text:
Q: Properties of $S_d$ sheaf A sheaf $F$ on a scheme $X$ is $S_d$ if for every $x\in X$, $F_x$ has a regular sequence of length at least $\min(d, \text{dim } \mathcal{O}_x)$.
I know when $d=\dim X$, this means $F$ is Cohen-Macaulay. But what properties of $F$ can we get if $d$ is small. Say 1 and 2?
One more specific question, on page 183 of Kollár and Mori's book, they justified a exact sequence remained exact after tensoring with $\omega_X$ by saying $\omega_X$ is S_2, can someone tell me why?
Thanks a lot in advance!


text:
Q: Use UDF to define a dropdown list (data validation) in a cell good afternoon.
I am trying to write my function to output a list to a cell (drop-down list using data validation).
It was assumed that a list is specified where the elements are encoded according to the following structure: parent pointer | pointer to children | Item text.
At the moment, the function is only half ready and is able to read only the specified list. But already at this stage, I wanted to test it and try to add a drop-down list through the check of the cell.
It was not possible to do this directly, and I tried to add through the Named Range.
I am not asking to end the function, however, I am asking you to suggest how to make the dropdown list. Maybe my function does not return something (although it does return an array). How do I get my plan into action?
    'Definition of structure
Type Node
    Name As String
    ID As Long
    Level As Long
    ChildrenMas() As Long 'an array of links to child Nodes
    Parent As Long 'indicates a link to the parent
    ParentMarker As String  'indicates the parent symbol
    ChildrenMarker As String 'indicates the symbol that children expect for this parent
    ThisIsRoot As Boolean 'For the root - true, for the rest - false
    DeepCount As Long ' Number of offspring in all subsequent generations
    UsedInFinalTree As Boolean 'the attribute is set at the time of determining the place in the tree for the node
End Type
Type Tree
    Name As String
    ElementsCount As Long
    Levels As Long

End Type

Function MultilevelList(Range As Range, _
                                Optional Delimiter As String = "|", _
                                Optional Levell As Long = 0, _
                                Optional OutputInformation As String = "text")

    ReDim RangeAsString(1 To Range.Count) As String
    Dim RangeAsStringCount As Long
    Dim c As Range
    Dim NodesArray() As Node 'an array of tree nodes
    Dim ReturnedNodesArray() As Node 'an array of tree nodes for output
    Dim ReturnedNodesArrayNames() As String
    Dim m As Node
    Dim NewTree As Tree 'creating a tree
    Dim i, j, k, SLong As Integer
    Dim S As String
    Dim a() As String 'array to divide the string
    Dim tm, td As Boolean

    i = 1
    For Each c In Range
        RangeAsString(i) = c.Text
        i = i + 1
    Next c
    RangeAsStringCount = Range.Count
    NewTree.Name = "Tree"

    'define the length of the array as the length of the resulting Range of strings
    ReDim NodesArray(1 To UBound(RangeAsString))
    For i = 1 To UBound(NodesArray)
        NodesArray(i).ParentMarker = "_none_ParentMarker" & i
        NodesArray(i).ChildrenMarker = "_none_ChildrenMarker" & i
    Next i

    k = 1
    For i = 1 To UBound(RangeAsString)
        SLong = 0
        S = RangeAsString(i)
        For j = 1 To Len(S)
            If Delimiter = Mid(S, j, 1) Then SLong = SLong + 1
        Next
        If SLong >= 2 Then
            a = Split(S, Delimiter, 3)
            NodesArray(k).ID = k
            NodesArray(k).ParentMarker = a(0)
            NodesArray(k).ChildrenMarker = a(1)
            NodesArray(k).Name = a(2)
            If NodesArray(k).ParentMarker = "" Then
                NewTree.Levels = 1
                NewTree.ElementsCount = NewTree.ElementsCount + 1
                NodesArray(k).Level = 1
                NodesArray(k).ThisIsRoot = True
                NodesArray(k).UsedInFinalTree = True
                RangeAsString(i) = Empty
                RangeAsStringCount = RangeAsStringCount - 1
            End If
            If i + 1 <> UBound(RangeAsString) Then k = k + 1
        Else
            RangeAsString(i) = Empty
            RangeAsStringCount = RangeAsStringCount - 1
        End If
    Next i

    tm = False
    Do Until RangeAsStringCount < 1
        If tm = True Then Exit Do
        td = False
        For i = 1 To UBound(NodesArray)
            If NodesArray(i).Level = 0 Then
                For j = 1 To UBound(NodesArray)
                    If NodesArray(i).ParentMarker = NodesArray(j).ChildrenMarker And _
                      NodesArray(j).Level <> 0 Then
                        If IsNotEmptyArray(NodesArray(j).ChildrenMas) Then
                            k = UBound(NodesArray(j).ChildrenMas)
                            ReDim Preserve NodesArray(j).ChildrenMas(1 To UBound(NodesArray(j).ChildrenMas) + 1)
                            k = k + 1
                            NodesArray(j).ChildrenMas(k) = i
                            NodesArray(i).Level = NodesArray(j).Level + 1
                            NodesArray(i).UsedInFinalTree = True
                            NodesArray(i).Parent = j
                            RangeAsStringCount = RangeAsStringCount - 1
                            td = True
                        Else
                            k = 0
                            ReDim Preserve NodesArray(j).ChildrenMas(1 To 1)
                            NodesArray(j).ChildrenMas(1) = i
                            NodesArray(i).Level = NodesArray(j).Level + 1
                            NodesArray(i).UsedInFinalTree = True
                            NodesArray(i).Parent = j
                            RangeAsStringCount = RangeAsStringCount - 1
                            td = True
                        End If
                        B = B
                    End If
                Next j
            End If
            Debug.Print i
            If td = False Then RangeAsStringCount = RangeAsStringCount - 1
        Next i
    Loop

    ReDim ReturnedNodesArray(1 To UBound(NodesArray))
    ReDim ReturnedNodesArrayNames(1 To UBound(NodesArray))
    k = 0
    For i = 1 To UBound(NodesArray)
        If Levell = 0 Then
            If NodesArray(i).UsedInFinalTree = True Then
                k = k + 1
                ReturnedNodesArray(k) = NodesArray(i)
                ReturnedNodesArrayNames(k) = ReturnedNodesArray(k).Name
            End If
        Else
            If NodesArray(i).Level = Levell And NodesArray(i).UsedInFinalTree = True Then
                k = k + 1
                ReturnedNodesArray(k) = NodesArray(i)
                ReturnedNodesArrayNames(k) = ReturnedNodesArray(k).Name
            End If
        End If
    Next i
    ReDim Preserve ReturnedNodesArray(1 To k)
    ReDim Preserve ReturnedNodesArrayNames(1 To k)

    B = UBound(RangeAsString)

    If OutputInformation = "text" Then
        MultilevelList = WorksheetFunction.Transpose(ReturnedNodesArrayNames)
        'MultilevelList = ReturnedNodesArrayNames
    End If

End Function

'function to check the initialized youth of the array
Function IsNotEmptyArray(parArray As Variant) As Boolean
  On Error Resume Next
  IsNotEmptyArray = LBound(parArray) <= UBound(parArray)
End Function

Example file

A: In my example I am creating a simple list containing months by UDF
Option Explicit

Public Function arrValues() As Variant
Dim i As Long

Dim arr(1 To 12, 1 To 1) As Variant   'two-dimensional array to get vertical list
For i = 1 To 12
    arr(i, 1) = MonthName(i)
Next

arrValues = arr
End Function

From what I have tested: you have to put the result on a worksheet.

Add a name to B2 - the name references B2 only and has to have a #-sign at the end - because this is an array formula:

Now you can use lstArrValues as a validation list.

A: It sounds, from your comments, that you're also after sub lists. If that's the case, then you might be better off with a pure VBA solution (rather than writing your array to a named range).
I'm pretty sure that ike is correct, ie you can't reference a UDF or array formula in the list parameter.
If the VBA solution interests you, then it would look something like this:
Option Explicit

Public Sub SetTopValidationList()
    Dim items As Variant
    Dim formulaText As String

    'This is your array of validation items.
    items = Array(1, 2, 3)

    'The formula parameter needs a comma separated string.
    formulaText = Join(items, ",")

    'Add the validation.
    With Sheet1.Range("B2").Validation
        .Delete
        .Add xlValidateList, xlValidAlertStop, xlBetween, formulaText
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
End Sub

Public Sub SetSubValidationList(topItem As Variant)
    Dim items As Variant
    Dim formulaText As String

    If IsEmpty(topItem) Then
        With Sheet1.Range("B4")
            .Validation.Delete
            .ClearContents
        End With
        Exit Sub
    End If

    Select Case topItem
        Case 1: items = Array(10, 11, 12)
        Case 2: items = Array(20, 21, 22)
        Case 3: items = Array(30, 31, 32)
        Case Else: items = Empty
    End Select

    If IsEmpty(items) Then
        With Sheet1.Range("B4")
            .Validation.Delete
            .ClearContents
        End With
        Exit Sub
    End If

    formulaText = Join(items, ",")
    With Sheet1.Range("B4").Validation
        .Delete
        .Add xlValidateList, xlValidAlertStop, xlBetween, formulaText
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With

End Sub

And you'd simply trap the top level change in the code behind your worksheet, eg:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Me.Range("B2"), Target) Is Nothing Then
        SetSubValidationList Me.Range("B2").Value2
    End If
End Sub


text:
Q: Errno::ENOENT: No such file or directory in finding duration of video from S3 Using gem paperclip-ffmpeg in rails for videos.It works fine but when I find the duration of video in seconds it gives me an error
Errno::ENOENT: No such file or directory - the file 'http://getpayad-dev.s3.amazonaws.com/ads/videos/000/000/014/original/Ufone_Tarzan_commercial_%28Ufone_Network_Quality%29_most_Funny_Ad.mp4?1451555000' does not exist
from /home/des0071/.rvm/gems/ruby-2.2.1/gems/streamio-ffmpeg-1.0.0/lib/ffmpeg/movie.rb:11:in `initialize

My code is
movie  = FFMPEG::Movie.new("#{self.video.url}")

A: Well, the FFMPEG::Movie.new definition is found here: streamio-ffmpeg/movie.rb

raise Errno::ENOENT, "the file '#{path}' does not exist" unless File.exists?(path)

#ruby 2.2.0p0 (2014-12-25 revision 49005)
File.exists?("http://getpayad-dev.s3.amazonaws.com/ads/videos/000/000/014/original/Ufone_Tarzan_commercial_%28Ufone_Network_Quality%29_most_Funny_Ad.mp4?1451555000")
=> false

The problem is with ruby's File Class.  So I tried this:
   File.exists?("http://www.google.com")
   => false

OK, so either google isn't online or File can't take URI as a parameter.

A File is an abstraction of any file object accessible by the program and is closely associated with class IO File includes the methods of module FileTest as class methods, allowing you to write (for example) File.exist?("foo").
  Class: File Ruby 2.2.0

So, File Class is really a child of IO, what does IO say?

Many of the examples in this section use the File class, the only standard subclass of IO. The two classes are closely associated. Like the File class, the Socket library subclasses from IO (such as TCPSocket or UDPSocket).
  Class:IO Ruby 2.2.0

It looks like the reason for the error is due to inheritance, or because the gem is not designed to stream the file over http.

A: As the previous answer suggestions, ffmpeg doesn't appear to be able to fetch the file over HTTP -- it's expecting a local file.
Depending upon how your files are encoded, they may have metadata at the beginning or end of the file which contains this information.
Subsequently a potential approach is to grab the first or last ~100KB of the file and check for the MOOV atom/metadata there.


text:
Q: Looking for some CSS that will make my links look like buttons
Possible Duplicate:
How do I make an html link look like a button?

I've looked around on the web. Found some links to very colorful buttons that don't look like buttons at all :-)
Is there anyone out there that has some CSS they found or came up with that could help me to make my links look like "real" buttons that I see when I use a "submit" type button in a form.
I don't mind if the CSS uses graphic backgrounds. Just looking for something that simulates a button as close as possible. I could also use jQuery as I have that on my page.
Thank you very much

A: For instance:
a {
    background:#eee;
    text-decoration:none;
    color:#333;
    font-family:Arial, sans-serif;
    font-size:11px;
    font-weight:bold;
    padding:3px 5px;
    border:1px solid #aaa;
    border-radius:3px;
    cursor:default;
}

a:hover {
    background-color:#f2f2f2;
    border-color:#888;
    box-shadow:0 0 2px #ccc;
}

a:active {
    vertical-align:-1px;
}

Live demo: http://jsfiddle.net/QTRpb/1/show/

A: In webkit and gecko there is the -webkit-appearance and -moz-appearance properties that does what you want. I'm not sure on support in other browsers – you'd need to check. Here's a demo:
http://jsfiddle.net/kZ2WE/2/
In CSS3 there is a standard property appearance, but, as of june 2013, it isn't supported in any browser.
The proprietary extensions work for Chrome, Safari (webkit) and Firefox (mozilla). It isn't supported at all nor in IE niether in Opera.

A: You could just use buttons instead of anchor elements. Don't put the button in a form and the page won't change when clicked. Give the buttons unique IDs, and have jquery attach event handlers to the buttons' click events that open a new web page.
$(document).ready(function(){
    $("#mybutton").click(function(){
        window.open("mypage.html");
    });
});

A: Maybe this could be useful for you: 22 CSS Button Styling Tutorials and Techniques.

A: Try the brief tutorial at the below link, it shows how to use a button as a hyperlink. Not sure what would happen with all those forms if you had loads of these on the same page though!
http://www.htmlgoodies.com/tutorials/buttons/article.php/3478871/So-You-Want-A-Link-Button-Huh.htm

A: Super Awesome Buttons from Zurb. Requires some CSS3

A: How hard did you look? I googled
"how to make a button using css"
And got excellent links.
The ones I used in the past are:
http://www.thesitewizard.com/css/3d-buttons.shtml
http://www.brainjar.com/dhtml/menubar/
If you google "css button generator" you will also get interesting sites:
http://www.iwebtoolsonline.com/html-and-css-rounded-corner-button-generator
http://css-tricks.com/examples/ButtonMaker/


text: Q: How to send key combinations(control+shift+T) using Selenium with Ruby on Mac? I need to send the following key combination (control+shift+T) using selenium on a Mac machine with Ruby. Someone suggest me a solution for this.


text:
Q: Statistic that combines proportion and 'success' size I have proportion data where I am interested in the proportion of successes, but also in the number of successes.  Is there some statistic I can calculate to summarize this info into one number?
Sample data:
X   N    P
2   4   .5
40 200  .2
3   10  .3
50 100  .5

Here the first and last data have the same proportion, but I would like the statistic to acknowledge the fact there is a lot more confidence in the last line (maybe incorporate the margin of error some how, but I would like it to take into account X not N).

A: I'd compute the proportion (X/N=P) along with a 95% confidence interval for that proportion. The width of that confidence interval shows you the margin of error you want. Use this free online calculator to do the math.

A: You might consider shrinkage estimation of $P$ given $X$. One straightforward way to do this is, for each row $i$,
$P_{i}^* = m\frac{c}{c+x_i} + \frac{x_i}{n_i}\frac{x_i}{x_i+c}$, where

*

*$x/n = P$, the proportion of successes

*$x =$ the number of successes

*$m =$ the mean proportion across the whole data set (which, based on the data above, is 0.303)

*$c =$ a scaling constant (the higher this is, the more shrinkage there is)

The intuition is that you are creating a weighted average $P^*$ which shrinks each proportion to the mean on the basis of how many successes it has. The left term establishes the base value, which will be more or less of a factor based on the degree to which $x_i$ differs from $c$. The right term pushes the value from $P_i^*$ away from that average, once again based on how $x_i$ differs from $c$.
The downside if that you have to choose an arbitrary scaling constant $c$. But you can justify this based on how many successes values $x_i$ it would take you to "trust" the proportion estimate $p_i$.
A canonical example of this in action is the imdb top 250, for which movie ratings are scaled to be higher (or lower, for the bottom 100) on the basis of how many votes they have.
(By the way, it's not clear to me why you trust entries with high $X$ more than high $N$, but you clearly have more domain-specific knowledge.)

A: You can't summarize this in one statistic,  But p and N the two binomial parameters tell the story.


text:
Q: Iterate through SQL select query to get more related data I would like to generate an excel report based on a SQL stored procedure.
Therefore i have to 'fill' few columns on this report. Some are related to (let's say) the Order table, others are related to the Product table and so on.
On the excel report i need to see the columns: Order no, Order value, Product 1 name, Product 2 name, Product 1 value, Product 2 value (there are max 2 products on each order).
The Product table is linked to the Order table.

I know this kind of listing it's a bit confusing, but that is what i wanna get.
Atm i have written the sequence:
SELECT
order.OrderNo,
order.OrderValue,
product.Name,
product.Value

From ORDER AS order
lEFT outer join PRODUCT as product on order.OrderId = product.OrderId

The query works but i only get data for the first product in each order. Is there a way to select data from all products specific to each order?

A: You can use row_number() and conditional aggregation:
SELECT op.OrderNo, op.OrderValue,
       MAX(CASE WHEN seqnum = 1 THEN Name END) as Name_1,
       MAX(CASE WHEN seqnum = 1 THEN Value END) as Value_1,
       MAX(CASE WHEN seqnum = 2 THEN Name END) as Name_2,
       MAX(CASE WHEN seqnum = 2 THEN Value END) as Value_2
FROM (SELECT o.OrderNo, o.OrderValue, p.Name, p.Value,
             ROW_NUMBER() OVER (PARTITION BY o.OrderNo ORDER BY p.Value DESC) as seqnum
      FROM ORDER o LEFT JOIN
           PRODUCT p
           ON o.OrderId = p.OrderId
     ) op
GROUP BY op.OrderNo, op.OrderValue;

A: If your DBMS supports it, you can use a PIVOT for this, for example:
declare @order table(
    OrderId int,
    OrderNo varchar(10),
    OrderValue decimal(10,2)
)

declare @product table(
    OrderId int,
    [Name] varchar(20),
    [Value] decimal(10,2)
)

insert into @order values
(1,'ORD001',436.45),
(2,'ORD002',964.33),
(3,'ORD003',1265.98)

insert into @product values
(1,'Widget',195.45),
(1,'Doohickey',241.00),
(2,'Widget',195.45),
(2,'Thingy',397.99),
(2,'Doofer',370.89),
(3,'Widget',195.45),
(3,'Thingy',397.99),
(3,'Foobar',415.78),
(3,'Whatchamacallit',256.76)

select
    OrderNo,
    OrderValue,
    [Widget],
    [Doohickey],
    [Thingy],
    [Doofer],
    [Foobar],
    [Whatchamacallit]
from
(
    select
        o.OrderNo,
        o.OrderValue,
        p.[Name],
        p.[Value]
    from @order o
    left join @product p on o.OrderId = p.OrderId
) SourceTable
pivot
(
    sum([Value])
    for [Name] in ([Widget], [Doohickey], [Thingy], [Doofer], [Foobar], [Whatchamacallit])
) as PivotTable

gives you this result:

However, this does require you to know all the distinct values of Product.Name which could appear and to include them in your query. The upside is you can perform further aggregation on the resultant values, per Product.


text:
Q: Slideshow Fix and Timer So I found out how to create a slideshow from a w3Schools. The slideshow is currently manual, meaning the user must click to change to another slide.
I would like to make it so the user can manually click or wait for the timer. Every, let's say 5 seconds, the slideshow will change slide.
I also need to fix an issue which isn't shown on the JsFiddle. When the page is loaded, all 3 images in the slideshow are loaded, when the user clicks the arrow to change slide they return to just showing one which it should upon loading. I'm not sure why this happens but I can't fix it.
So the following will be loaded upon page load

Rather than just one, after clicking the arrow only one displays, it essentially fixes its self.
I am also open to other slideshow methods, this is just one I found which worked somewhat.
https://jsfiddle.net/a4zxrLem/
Important: In JsFiddle example the arrows do not change the image, however they do work.

A: Add this to your code:
setInterval(function(){
   plusSlides(1);
}, 5000);//for 5 seconds

Here is the fiddle: https://jsfiddle.net/gerardofurtado/a4zxrLem/2/
Your second problem is simpler: for the fiddle to work, select "Load Type: No wrap in body", on the menu that shows up when you click "javascript".


text:
Q: Is there anyway for adding graphql api with postgres data source using aws amplify CLI? You can change the data source of appsync service in aws console, but I am not sure if it can work after I run command
 amplify push api
 And haven't found a way of changing data source with aws-amplify.

A: There isn't a direct way, no, as AppSync doesn't have native Postgres data sources. You could theoretically do anything with a Lambda data source, though, very much including Postgres.
An AppSync dev created a sample app that shows a way to do this, via what Amplify calls custom resolvers. You can find that repo here: https://github.com/mikeparisstuff/amplify-cli-nested-api-sample


text:
Q: Detect variable change on runtime I'm working with the web audio API. In note.js i try to fill an array with some couple of notes for index.js to play. But it does not work as intended. However, when i set the array directly in index.js it works.
I have no clue why it is like that. Basically i want index.js to play whatever notes gets pushed into the array in note.js. Below i have pasted the two versions of index.js to demonstrate what i want to do.
Hope someone can help me with this one.
index.js (does work)
import NoteModule from './note.js';
const notelist = new NoteModule();

notelist.notes = ['C4','D4','E4','F4','G4','A4','B4','C5'];

let seq = new Tone.Sequence(function(time, note){
    event.humanize = true;
    synth.triggerAttackRelease(note,'8n');

}, notelist.notes, '8n');

index.js (does not work)
import NoteModule from './note.js';
const notelist = new NoteModule();

let seq = new Tone.Sequence(function(time, note){
    event.humanize = true;
    synth.triggerAttackRelease(note,'8n');

}, notelist.notes, '8n');

note.js
import $ from 'jquery';

export default class NoteModule {
constructor(possibleNotes,notes,note) {
    this.possibleNotes = ['','C4','D4','E4','F4','G4','A4','B4'];
    this.notes = notes;
    this.note = 0;
}

init() {
    console.log('NoteModule');
    this.addListeners();
}

addListeners() {
    $('div.step').on('click', this.step.bind(this));
}

step(e) {

    let notes = [];

    $(e.currentTarget).parent().find('.note').text(this.possibleNotes[this.note]);
    this.note = (this.note+1)%(this.possibleNotes.length);

    $('.pads div.note').each(function() {
        let note = $(this).text();

        if (note && note.length > 0) {
            notes.push(note);
        }
    });

this.notes = notes;
}
}

HTML:

A: You need to rework a bit how your files are structured and how your module is working. It does not work, because you are creating the Tone.Sequence before anything has the chance to be set in your NoteModule class, and you are not really updating your notes array anyway, you also didn't bind your step method in your constructor, meaning it won't have access to the this context, leaving all your modifications not saved.
Refactor your module to do something like the following, passing a function callback that will be executed once you click on a play button (that you will have to create). If you want to play as soon as a new note is played, just call the callback like I did in the step method.
import $ from 'jquery'

export default class NoteModule {

  constructor (callback, notes) {
    this.possibleNotes = ['','C4','D4','E4','F4','G4','A4','B4']
    this.notes = notes
    this.callback = callback
    this.note = 0
    // you need this otherwise the step method won't have access to the context
    this.step = this.step.bind(this)
  }

  init () {
    console.log('NoteModule')
    // make sure this is called, otherwise your events won't work
    $('div.step').on('click', this.step.bind(this))
    $('.play').on('click', () => this.callback(this.notes))
  }

  step (e) {

    const notes = []

    $(e.currentTarget).parent()
      .find('.note')
      .text(this.possibleNotes[this.note])

    this.note = (this.note + 1) % (this.possibleNotes.length)

    $('.pads div.note').each(el => {
      const note = $(el).text()

      if (note && note.length > 0) {
        notes.push(note)
      }
    })

    this.notes = notes
    // or callback here, as you want

  }
}

And in your index.js simply import, initialize your class and pass the function callback that will receive the notes:
import NoteModule from './note.js'

const callback = notes => {
  const seq = new Tone.Sequence((time, note) => {
    event.humanize = true
    synth.triggerAttackRelease(note, '8n')
  }, notes, '8n')
}

new NoteModule(callback)


text:
Q: c:set tag to set a non-primitive type value What's a possible way to use Spring Security tag <sec:authentication property="principal.id" /> as the value for the <c:set…> tag?
These statements:
<c:set var="userId" value="<sec:authentication property='principal.id' />"/>
<c:set var="userId" value="<sec:authentication property=\"principal.id\" />"/>

won't work.

A: There is no reason to use «value» attribute in your case. Use <c:set> tag in this way:
<c:set var="userId">
    <sec:authentication property="principal.id"/>
</c:set>


text:
Q: Concerning the proof Euclid lemma on prime numbers Euclid's Lemma: Let $p$ be a prime number, and let $a,b\in \mathbb{Z}$. Then
$$p\mid ab\implies p\mid a\vee p\mid b$$
I know that there are proofs available in the websites. I'd like to get some feedbacks what you think about the proof i made here.
Proof: If $a,b=0$, the implication is clear. Now suppose $a,b\neq 0$. Suppose $p\mid ab$. We know that $(a,p)\mid a$ and $(a,p)\mid p$, which implies that $(a,p)\mid p$ (by Specialization). But
$$(a,p)\mid p\iff (a,p)=1 \vee (a,p)=p.$$
Checking the cases $(a,p)=1$ and $(a,p)=p$, we see that
$$(a,p)=1\implies p\mid b\implies p\mid b\vee p\mid a$$
where the first implication is used by the Bezout's lemma, and
$$(a,p)=p\iff p\mid a\wedge p\mid p\implies p\mid a\implies p\mid a\vee p\mid b.$$
Altogether,
$$(a,p)=1 \vee (a,p)=p\implies p\mid a\vee p\mid b.$$
QED. Is this a valid proof? If there are mistakes in some directions, please let me know.

A: In terms of logic, your proof is technically correct. It's essentially equivalent to the "standard" proof using Bezout's lemma.
However, from a mathematical writing standpoint, the way you presented this proof is less than ideal. Whenever writing proofs, you should be asking yourself: What ideas are important?
The important idea behind Euclid's lemma is the following step:

$p\not\mid a \implies p|b$

As you pointed out in the comments, this can be proven using Bezout's Lemma. It's a nice little gem of number theory.
What is not important for the proof of Euclid's lemma is the mundane "logic" steps. The first few sentences in your proof are needlessly wordy. It would suffice to say:

By definition of the gcd, $(a,p) | p$. Since $p$ is prime and the gcd is positive, there are two cases: $(a,p) = 1$ and $(a,p) = p$.

Here, we're emphasizing the important part of this step: The fact that because $p$ is prime, $(a,p)$ can only be equal to $1$ or $p$.
Next, in your proof you look at the two cases $(a,p) = 1$ and $(a,p) = p$. Once again, you skipped the justifications involving number theory and kept fiddling around with logical symbols instead. The important part of these cases is that $(a,p) = 1$ implies $p | b$ and $(a,p) = p$ implies $p | a$. So, let's write that:

If $(a,p) = p$, then by definition of the gcd, $p | a$.
If $(a,p) = 1$, then by Bezout's Lemma there exist integers $x,y$ such that $ax + py = 1$. Multiplying by $b$, we have $abx + pyb = b$. Since $p | ab$, there exists an integer $k$ such that $ab = pk$. So $p(k + yb) = b$. Thus $p | b$.

Note the parts that I skipped: Using the commutative and associative properties to write $(ax)b = a(xb) = a(bx) = (ab)x$, using the distributive property to immediately conclude $pkx + pyb = p(kx+yb)$, using closure of the integers to assert that $k + yb$ is an integer. These steps are technically parts of the proof, but I skipped them because they're not important to the number theory. We know how to manipulate the integers using the commutative, associative, and distributive properties. So we can skip these steps, just like we skip the excessive "logic" steps.
Finally, you can conclude that your initial assumption $p | ab$ (with $p$ prime) implies $p|a$ or $p|b$:

Therefore, $p | a$ or $p | b$.

Note that my "rewritten" bits of your proof are essentially the same as what you wrote in your post and in the comments. Like I said, your proof was technically correct. It just emphasized the unimportant facts (e.g. logical manipulations) instead of the important facts (e.g. precisely citing relevant results in number theory).
The point of writing mathematical proofs is not verifying the result. A well-written proof should also convey why it should make sense for the result to be true.
That's why it's ok to leave off details such as

$p|a \implies (p|a \vee p|b)$

but why it's not ok to leave off justifications for

$(a,p) = 1 \implies p | b$.

The first statement is "obviously" true by logic. When doing math that isn't logic, it's ok to assume basic logic facts. But the second statement is not at all obvious (in the context of elementary number theory). In fact, it's 90% of what you're trying to prove! So you should explicitly prove this step, and emphasize that it is important.


text:
Q: Actively Refused Connections I know this question has been asked several times before, but my case is a little odd.
I have a machine listening to X.X.X.X:8080, which acts as a load-balancer and redirects requests to two other machines, listening to port 8081. When I run the program, there are no bugs or errors; it's a simple app.
The problem comes when I'm trying to test it out for load-testing. I'm using a Web Performance and Load Test via Visual Studio 2012, and I've recorded the WebTest routes correctly (as far as I know). But when I run a load-test with anything over 200 users, the error report generated shows this error:
"No connection could be made because the target machine actively refused it X.X.X.X:8080."
And the queer thing is, exactly 1,000 of these errors show up every time, no more no less. Anything below 200 users and I get other errors, which I can figure out, but this really has me on my hair's end.
I am using Tomcat, and Apache HTTPD Server in front of it.
Help!


text:
Q: ¿Cómo puedo optimizar mis subconsultas? Hola tengo una duda como poder optimizar mis subconsultas.
Tengo 3 consultas, en uno como condición separados por el ID_Etapa_vital.
select  Etapa_Vital.ID_Etapa_vital
       , (select count(*)
            from paciente
            where paciente.Genero ='Masculino'
            and paciente.ID_Etapa_Vital = Etapa_Vital.ID_Etapa_Vital
         ) NumeroDePacientesMasculinos
       , (select count(*)
            from ong_padma.sesiones
            inner join paciente on paciente.ID_numero_historia = sesiones.ID_numero_historia
           where paciente.Genero = 'Masculino'
            and paciente.ID_Etapa_Vital = Etapa_Vital.ID_Etapa_Vital
         ) NumeroDeSesionesConPacientesMasculinos
      ,(select count(*)  from
            (
            select nombre
            from ong_padma.sesiones
            inner join paciente on paciente.ID_numero_historia = sesiones.ID_numero_historia
            where paciente.Genero = 'Masculino'
            and paciente.ID_Etapa_Vital = 1  <-------------------------
            group by nombre
            having count(cantidad_sesiones)>2
            ) paciente)Continuadores
  from Etapa_Vital
 where Etapa_Vital.ID_Etapa_Vital = 1; <---------------------------

En esta consulta solo obtengo por el ID_Etapa_vital  1.
_____________________________________________________________________________________________________
|ID_Etapa_vital |NumeroDePacientesMasculinos| NumeroDeSesionesConPacientesMasculinos|continuadores
| --------------| --------------------------|---------------------------------------|-------------------
|  1            |    20                     |          40                           |       10

Pero... en realidad quisiera que quede así separado por los ID_etapa_vital.
________________________________________________________________________________________________________
|ID_Etapa_vital |NumeroDePacientesMasculinos| NumeroDeSesionesConPacientesMasculinos|continuadores
| --------------| --------------------------|---------------------------------------|-------------------
|  1            |    50                     |          80                           |       60
|  2            |    40                     |          10                           |       60
|  3            |    70                     |          300                          |       60
|  4            |    250                    |          800                          |       60
|  5            |    50                     |          30                           |       60
|  6            |    500                    |          800                          |       60

leí sobre tablas dinámicas pero no se como poder poder trasladar mis sub consultas.

A: *

*Relaciona la tercera sub-consulta con la tabla principal, en lugar de esto:
 and paciente.ID_Etapa_Vital = 1

que siempre te trae los registros de ID_Etapa_Vital igual a 1, utiliza:
 and paciente.ID_Etapa_Vital = Etapa_Vital.ID_Etapa_Vital

lo que hará que, para cada registro de la tabla Etapa_Vital, la sub-consulta haga el cálculo correcto.

*Quita el where de la consulta principal. Este está provocando que traiga solo el registro con ID igual a 1, si lo quitas, traerá todos los de la tabla:
Edición:
Según comenta el AP, mySQL es incapaz de procesar la referencia a la tabla principal de la consulta en una sub-sub consulta, cosa que no debiera, pero no me sorprende de este motor. Lo que sugiero es que re-escribas esa consulta para tener la referencia un nivel afuera, por ejemplo:
select count(*)
  from (select   paciente.ID_Etapa_Vital
               , paciente.ID_numero_historia
               , count(1) Sesiones
          from paciente
               inner join ong_padma.sesiones on sesiones.ID_numero_historia = paciente.ID_numero_historia
         where paciente.Genero = 'Masculino'
         group by paciente.ID_Etapa_Vital
               , paciente.ID_numero_historia
        having count(1) > 2
       ) a
 where a.ID_Etapa_Vital = Etapa_Vital.ID_Etapa_Vital

Al tener la condición, el motor debiera ser capaz de ejecutar la sub-consulta con una eficiencia similar a la anterior. En todo caso, habría que analizar los planes de ejecución de ambas para ver qué hace el motor y buscar una solución en caso que no esté optimizándola adecuadamente.


text:
Q: Handle ActionForward in Struts 2 I am migrating my Struts1 application to Struts2.
Is there any alternative for the below code in Struts2, I am using this in my Action classes.
String path = mapping.findForward("failurePath").getPath();
new ActionForward(path);

A: You can directly use in struts.xml
<result name="resultName" type="redirect" >failurePath.action?param1=${value1}&param2={value2}</result>

You need to have setter and getter methods for value1 and value2 oin action class


text:
Q: android SQLiteException: no such column on custom roms On devices with modified android versions i get this error. For example on Xiaomi devices.
String query = "select * from dialogues where userId = ? and topChat = 0 order by updatedAtByClient desc";
Cursor dialogRes = db.rawQuery(query, new String[]{userId});

Here i get exception:
android.database.sqlite.SQLiteException: no such column: topChat (code 1):,
while compiling: select * from dialogues where userId = ? and topChat = 0
order by updatedAtByClient desc

I have written the exception message by hand, because the user has sent me it in a screenshot, so there might be typos.
How can this be fixed, and why does this happen?
UPD1:
the create table statement looks similar to this:
"CREATE TABLE IF NOT EXISTS dialogues(fieldName VARCHAR, camelCaseFieldName VARCHAR,
topChat INTEGER, createdAt DATE);";

And i have a correctly implemented update method for when im changing the DB structure, but this particular table and field name did not change for a long time.
UPD2:
i have made an apk for the user with problems, that logs that table columns, and i did see the problematic column in the log, and user says that this version works ok.
So seems that this error does not happen 100% of times. Very strange. Maybe there is a way to check the database for integrity after creating it, and recreate tables with errors?

A: I don't believe this would be a xiaomi issue. it rather seems be the result of an unfortunate migration, where a new column had not been added and subsequently, the user might still work with the previous version of the table. and there is no other logical explanation for an absent column), simply because either the CREATE TABLE statement works - or it doesn't.
one can still work around it with ALTER TABLE. eg. when that SQLiteException occurs, addColumnIfNotExists("dialogues", "topChat", "INTEGER DEFAULT 0"); ...in order not to cause data-loss by dropping the table, only because it lacks some column.
public void addColumnIfNotExists(String tableName, String columnName, String dataType) {
    Cursor cursor = null;
    try {
        cursor = db.rawQuery("SELECT * FROM " + tableName, null);
        if(! Arrays.asList(cursor.getColumnNames()).contains(columnName)) {
            db.execSQL(String.format("ALTER TABLE %s ADD COLUMN %s %s", tableName, columnName, dataType));
        }
    } finally {
        if(cursor != null) {
            cursor.close();
        }
    }
}


text:
Q: In-app purchase in application I have several in-app purchases in application. I use this code:
@IBAction func purchaseFull(_ sender: Any) {

        purchase = "purchaseFull"

        product_id = "purchaseFull"

        print("About to fetch the product...")
        //self.loading.startAnimating()
        SKPaymentQueue.default().add(self)
        // Can make payments
        if (SKPaymentQueue.canMakePayments())
        {
            let productID:NSSet = NSSet(object: self.product_id!);
            let productsRequest:SKProductsRequest = SKProductsRequest(productIdentifiers: productID as! Set<String>);
            productsRequest.delegate = self;
            productsRequest.start();
            print("Fetching Products");
        }else{
            print("Can't make purchases");
        }
    }

@IBAction func purchase(_ sender: Any) {

        purchase = "purchase"

        product_id = "purchase\(index)"

        print("About to fetch the product...")
        //self.loading.startAnimating()
        SKPaymentQueue.default().add(self)
        // Can make payments
        if (SKPaymentQueue.canMakePayments())
        {
            let productID:NSSet = NSSet(object: self.product_id!);
            let productsRequest:SKProductsRequest = SKProductsRequest(productIdentifiers: productID as! Set<String>);
            productsRequest.delegate = self;
            productsRequest.start();
            print("Fetching Products");
        }else{
            print("Can't make purchases");
        }
    }

func productsRequest (_ request: SKProductsRequest, didReceive response: SKProductsResponse) {

        let count : Int = response.products.count
        if (count>0) {
            let validProduct: SKProduct = response.products[0] as SKProduct
            if (validProduct.productIdentifier == self.product_id) {
                print(validProduct.localizedTitle)
                print(validProduct.localizedDescription)
                print(validProduct.price)
                buyProduct(product: validProduct);

            } else {
                print(validProduct.productIdentifier)
            }
        } else {
            print("nothing")
        }
    }

    func buyProduct(product: SKProduct){
        print("Sending the Payment Request to Apple");
        let payment = SKPayment(product: product)
        SKPaymentQueue.default().add(payment);
        //self.loading.stopAnimating()
    }

    func request(_ request: SKRequest, didFailWithError error: Error) {
        print("Error Fetching product information");
        //self.loading.stopAnimating()
    }

    func paymentQueue(_ queue: SKPaymentQueue,
                      updatedTransactions transactions: [SKPaymentTransaction]) {
        print("Received Payment Transaction Response from Apple");

        for transaction:AnyObject in transactions {
            if let trans:SKPaymentTransaction = transaction as? SKPaymentTransaction{
                switch trans.transactionState {
                case .purchased:
                    print("Product Purchased");
                    SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
                    // Handle the purchase

                    if purchase == "purchase" {
                        UserDefaults.standard.set(true , forKey: "purchase\(index)")
                    }

                    if purchase == "purchaseFull" {
                        UserDefaults.standard.set(true , forKey: "purchaseFull")
                    }

                    viewDidLoad()
                    break;
                case .failed:
                    print("Purchased Failed");
                    SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
                    break;

                case .restored:
                    print("Already Purchased");
                    SKPaymentQueue.default().restoreCompletedTransactions()
                    // Handle the purchase
                    //UserDefaults.standard.set(true , forKey: "purchased")
                    viewDidLoad()
                    break;
                default:
                    break;
                }
            }
        }
    }

    @IBAction func restoreAction(_ sender: Any) {
        SKPaymentQueue.default().add(self)
        if (SKPaymentQueue.canMakePayments()) {
            SKPaymentQueue.default().restoreCompletedTransactions()
        }
    }

    func requestDidFinish(_ request: SKRequest) {

    }

    func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
        print("transactions restored")
        for transaction in queue.transactions {
            let t: SKPaymentTransaction = transaction
            let prodID = t.payment.productIdentifier as String

            if prodID == "purchaseFull" {
                print("action for restored")
                queue.finishTransaction(t)
                UserDefaults.standard.set(true , forKey: "purchaseFull")
            } else if prodID == "purchase0" {
                print("action0")
                queue.finishTransaction(t)
                UserDefaults.standard.set(true , forKey: "purchase0")
            } else if prodID == "purchase1" {
                print("action1")
                queue.finishTransaction(t)
                UserDefaults.standard.set(true , forKey: "purchase1")
            } else if prodID == "purchase2" {
                print("action2")
                queue.finishTransaction(t)
                UserDefaults.standard.set(true , forKey: "purchase2")
            } else if prodID == "purchase3" {
                print("action3")
                queue.finishTransaction(t)
                UserDefaults.standard.set(true , forKey: "purchase3")
            } else if prodID == "purchase4" {
                print("action4")
                queue.finishTransaction(t)
                UserDefaults.standard.set(true , forKey: "purchase4")
            } else if prodID == "purchase5" {
                print("action5")
                queue.finishTransaction(t)
                UserDefaults.standard.set(true , forKey: "purchase5")
            }
        }
        cancelAction((Any).self)
    }

But I have a problem. When I click on my purchase button my code call this function - paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) and if else check works. And my Userdefaults set true for key. As a result user unblock content but not pay for purchases. How to fix it?

A: It's a little hard to debug what you're doing as you're updating UserDefaults in two places and your purchase tracking code is tightly coupled to your purchasing code.
I would separate the concerns of purchasing and tracking purchases so you only have to keep track of and update or unlock them in one place. Something like this...
First off I'd separate all the iTunesConnect purchasing code into separate discreet classes (one for the iTunesStore, and one for the iTunesStore callback observer), create models to represent the purchase states and error states and create callbacks to notify the app of significant actions that happen during the product validation and purchase flow.
The callback protocols would look something like this:
import StoreKit

/// Defines callbacks that will occur when products are being validated with the iTunes Store.
protocol iTunesProductStatusReceiver: class {
    func didValidateProducts(_ products: [SKProduct])
    func didReceiveInvalidProductIdentifiers(_ identifiers: [String])
}

/// Defines callbacks that occur during the purchase or restore process
protocol iTunesPurchaseStatusReceiver: class {
    func purchaseStatusDidUpdate(_ status: PurchaseStatus)
    func restoreStatusDidUpdate(_ status: PurchaseStatus)
}

My iTunesStore class would look like this, and it would handle all interactions with iTunesConnect (or AppStoreConnect now):
import Foundation
import StoreKit

class iTunesStore: NSObject, SKProductsRequestDelegate {

    weak var delegate: (iTunesProductStatusReceiver & iTunesPurchaseStatusReceiver)?

    var transactionObserver: IAPObserver = IAPObserver()
    var availableProducts: [SKProduct] = []
    var invalidProductIDs: [String] = []

    deinit {
        SKPaymentQueue.default().remove(self.transactionObserver)
    }

    override init() {
        super.init()
        transactionObserver.delegate = self
    }

    func fetchStoreProducts(identifiers:Set<String>) {
        print("Sending products request to ITC")
        let request:SKProductsRequest = SKProductsRequest.init(productIdentifiers: identifiers)
        request.delegate = self
        request.start()
    }

    func purchaseProduct(identifier:String) {
        guard let product = self.product(identifier: identifier) else {
            print("No products found with identifier: \(identifier)")

            // fire purchase status: failed notification
            delegate?.purchaseStatusDidUpdate(PurchaseStatus.init(state: .failed, error: PurchaseError.productNotFound, transaction: nil, message:"An error occured"))
            return
        }

        guard SKPaymentQueue.canMakePayments() else {
            print("Unable to make purchases...")
            delegate?.purchaseStatusDidUpdate(PurchaseStatus.init(state: .failed, error: PurchaseError.unableToPurchase, transaction: nil, message:"An error occured"))
            return
        }

        // Fire purchase began notification
        delegate?.purchaseStatusDidUpdate(PurchaseStatus.init(state: .initiated, error: nil, transaction: nil, message:"Processing Purchase"))

        let payment = SKPayment.init(product: product)
        SKPaymentQueue.default().add(payment)

    }

    func restorePurchases() {
        // Fire purchase began notification
        delegate?.restoreStatusDidUpdate(PurchaseStatus.init(state: .initiated, error: nil, transaction: nil, message:"Restoring Purchases"))
        SKPaymentQueue.default().restoreCompletedTransactions()
    }

    // returns a product for a given identifier if it exists in our available products array
    func product(identifier:String) -> SKProduct? {
        for product in availableProducts {
            if product.productIdentifier == identifier {
                return product
            }
        }

        return nil
    }

}

// Receives purchase status notifications and forwards them to this classes delegate
extension iTunesStore: iTunesPurchaseStatusReceiver {
    func purchaseStatusDidUpdate(_ status: PurchaseStatus) {
        delegate?.purchaseStatusDidUpdate(status)
    }

    func restoreStatusDidUpdate(_ status: PurchaseStatus) {
        delegate?.restoreStatusDidUpdate(status)
    }
}

// MARK: SKProductsRequest Delegate Methods
extension iTunesStore {
    @objc(productsRequest:didReceiveResponse:) func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        // set new products
        availableProducts = response.products

        // set invalid product id's
        invalidProductIDs = response.invalidProductIdentifiers
        if invalidProductIDs.isEmpty == false {
            // call delegate if we received any invalid identifiers
            delegate?.didReceiveInvalidProductIdentifiers(invalidProductIDs)
        }
        print("iTunes Store: Invalid product IDs: \(response.invalidProductIdentifiers)")

        // call delegate with available products.
        delegate?.didValidateProducts(availableProducts)
    }
}

You'll notice this class makes use of PurchaseStatus, PurchaseState, and PurchaseError objects to communicate status changes and updates to the app.
These classes look like this:
import Foundation
import StoreKit

enum PurchaseState {
    case initiated
    case complete
    case cancelled
    case failed
}

class PurchaseStatus {
    var state:PurchaseState
    var error:Error?
    var transaction:SKPaymentTransaction?
    var message:String

    init(state:PurchaseState, error:Error?, transaction:SKPaymentTransaction?, message:String) {
        self.state = state
        self.error = error
        self.transaction = transaction
        self.message = message
    }
}

public enum PurchaseError: Error {
    case productNotFound
    case unableToPurchase

    public var code: Int {
        switch self {
        case .productNotFound:
            return 100101
        case .unableToPurchase:
            return 100101
        }
    }

    public var description: String {
        switch self {
        case .productNotFound:
            return "No products found for the requested product ID."
        case .unableToPurchase:
            return "Unable to make purchases. Check to make sure you are signed into a valid itunes account and that you are allowed to make purchases."
        }
    }

    public var title: String {
        switch self {
        case .productNotFound:
            return "Product Not Found"
        case .unableToPurchase:
            return "Unable to Purchase"
        }
    }

    public var domain: String {
        return "com.myAppId.purchaseError"
    }

    public var recoverySuggestion: String {
        switch self {
        case .productNotFound:
            return "Try again later."
        case .unableToPurchase:
            return "Check to make sure you are signed into a valid itunes account and that you are allowed to make purchases."
        }
    }
}

With these classes in place we only have two more pieces to setup our store and make it easily reusable across apps without having to re-write large portions every time we want to add in app purchase in an app.
The next piece is the observer that receives callbacks from StoreKit, the iTunesStore class should be the only class that uses this:
import Foundation
import StoreKit

class IAPObserver: NSObject, SKPaymentTransactionObserver {

    // delegate to propagate status update up
    weak var delegate: iTunesPurchaseStatusReceiver?

    override init() {
        super.init()
        SKPaymentQueue.default().add(self)
    }

    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {
            switch transaction.transactionState {
                case .purchasing:   // Transaction is being added to the server queue
                    break

                case .purchased:    // Transaction is in queue, user has been charged. Complete transaction now
                    // Notify purchase complete status
                    delegate?.purchaseStatusDidUpdate(PurchaseStatus.init(state: .complete, error: nil, transaction: transaction, message:"Purchase Complete."))
                    SKPaymentQueue.default().finishTransaction(transaction)

                case .failed:   // Transaction was cancelled or failed before being added to the server queue
                        // An error occured, notify
                    delegate?.purchaseStatusDidUpdate(PurchaseStatus.init(state: .failed, error: transaction.error, transaction: transaction, message:"An error occured."))
                    SKPaymentQueue.default().finishTransaction(transaction)

                case .restored: // transaction was rewtored from the users purchase history. Complete transaction now.
                    // notify purchase completed with status... success
                    delegate?.restoreStatusDidUpdate(PurchaseStatus.init(state: .complete, error: nil, transaction: transaction, message:"Restore Success!"))
                    SKPaymentQueue.default().finishTransaction(transaction)

                case .deferred: // transaction is in the queue, but it's final status is pending user/external action
                    break
            }
        }
    }

    func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
        guard queue.transactions.count > 0 else {
            // Queue does not include any transactions, so either user has not yet made a purchase
            // or the user's prior purchase is unavailable, so notify app (and user) accordingly.

            print("restore queue.transaction.count === 0")
            return
        }

        for transaction in queue.transactions {
            // TODO: provide content access here??
            print("Product restored with id: \(String(describing: transaction.original?.payment.productIdentifier))")
            SKPaymentQueue.default().finishTransaction(transaction)
        }
    }

    func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
        // fire notification to dismiss spinner, restore error
        delegate?.restoreStatusDidUpdate(PurchaseStatus.init(state: .failed, error: error, transaction: nil, message:"Restore Failed."))
    }
}

The last piece is a store class that manages triggering purchases and handles granting access to purchased products:
enum ProductIdentifier: String {
    case one = "com.myprefix.id1"
    case two = "com.myprefix.id2"

    static func from(rawValue: String) -> ProductIdentifier? {
        switch rawValue {
        case one.rawValue: return .one
        case two.rawValue: return .two
        default: return nil
        }
    }
}

class Store {
    static let shared = Store()

    // purchase processor
    var paymentProcessor: iTunesStore = iTunesStore()

    init() {
        // register for purchase status update callbacks
        paymentProcessor.delegate = self

        validateProducts()
    }

    // validates products with the iTunesConnect store for faster purchase processing
    // when a user wants to buy
    internal func validateProducts() {

        // all products to validate
        let products = [
            ProductIdentifier.one.rawValue,
            ProductIdentifier.two.rawValue
        ]

        paymentProcessor.fetchStoreProducts(identifiers: Set.init(products))
    }

    /// Purchase a product by specifying the product identifier.
    ///
    /// - Parameter identifier: The product identifier for the product being purchased. This must belong to a valid product in the 'products' array, as this array is searched for a product with the specified identifier. If none are found this function bails.
    func purchaseProduct(identifier: ProductIdentifier) {
        print("purchase product: \(identifier)")

        self.paymentProcessor.purchaseProduct(identifier: identifier.rawValue)
    }

    /// Initiates restore purchases functionality.
    func restorePurchases() {
        self.paymentProcessor.restorePurchases()
    }

    /// This function is called during the purchase/restore purchase process with each status change in the flow. If the status is complete then access to the product should be granted at this point.
    ///
    /// - Parameter status: The current status of the transaction.
    internal func processPurchaseStatus(_ status: PurchaseStatus) {
        switch status.state {
        case .initiated:
            // TODO: show alert that purchase is in progress...
            break
        case .complete:
            if let productID = status.transaction?.payment.productIdentifier {
                // Store product id in UserDefaults or some other method of tracking purchases
                UserDefaults.standard.set(true , forKey: productID)
                UserDefaults.standard.synchronize()
            }
        case .cancelled:
            break
        case .failed:
            // TODO: notify user with alert...
            break
        }
    }
}

extension Store: iTunesPurchaseStatusReceiver, iTunesProductStatusReceiver {
    func purchaseStatusDidUpdate(_ status: PurchaseStatus) {
        // process based on received status
        processPurchaseStatus(status)
    }

    func restoreStatusDidUpdate(_ status: PurchaseStatus) {
        // pass this into the same flow as purchasing for unlocking products
        processPurchaseStatus(status)
    }

    func didValidateProducts(_ products: [SKProduct]) {
        print("Product identifier validation complete with products: \(products)")
        // TODO: if you have a local representation of your products you could
        // sync them up with the itc version here
    }

    func didReceiveInvalidProductIdentifiers(_ identifiers: [String]) {
        // TODO: filter out invalid products? maybe... by default isActive is false
    }
}

By using this approach you'll be able to put all the iTunesConnect related classes in a folder and use them across projects and only have to update your ProductIdentifer enum and Store class for each project you want to use it in.
Good luck! Hope this helps!
EDIT: Here's a sample application (Swift 4) with everything integrated showing how to use it - https://github.com/appteur/eziap
EDIT 2: (Answer to comment regarding displaying alert)
There are several ways you can display an alert notifying the user.
You could trigger an alert in any view controller by sending a Notification and having the view controller listen for it. You could setup a delegate chain to the appropriate view controller, you could also create closures that would be passed to the Store object and updated on state changes.
I would probably create an optional custom alert view controller and set a variable in the Store class of it's type and present it on the top most view controller.
I would present it in the internal func processPurchaseStatus(_ status: PurchaseStatus) function on the initiated state and update it when the state changes in the same function.
I would update the label on the alert view with the current status and have it automatically dismiss on successful purchase or display a success screen. If the transaction failed I would update the alert message with the error and reveal a button to dismiss the alert view.
I use an extension like this to get the top most view controller:
import UIKit

extension UIApplication {
    static func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let navigationController = controller as? UINavigationController {
            return topViewController(controller: navigationController.visibleViewController)
        }
        if let tabController = controller as? UITabBarController {
            if let selected = tabController.selectedViewController {
                return topViewController(controller: selected)
            }
        }
        if let presented = controller?.presentedViewController {
            return topViewController(controller: presented)
        }
        return controller
    }
}

Using this method you would probably have a function something like this:
internal func showAlert() {

    // do UI stuff on the main thread
    DispatchQueue.main.async { [weak self] in

        // load alert from storyboard, nib, or some method, get the topmost view controller in the controller hierarchy, only use it if it's not being dismissed
        guard let alertVC = MyAlertClass.fromNib(), let topVC = UIApplication.topViewController(), topVC.isBeingDismissed == false else {
            return
        }

        // set our local variable so we can update the message later and dismiss it more easily
        self.myAlertController = alertVC

        // Present the alert view controller
        topVC.present(alertVC, animated: true, completion: nil)
    }
}

Instead of doing a custom alert view controller you could also just create a view subclass with your alert UI and add it to the view of the top most view controller.


text:
Q: exclude a certain path from all user searches Unfortunately we have a special folder named "_archive" in our repository everywhere.
This folder has its purpose. But: When searching for content/documents we want to exclude it and every content beneath "_archive".
So, what i want is to exclude the path and its member from all user searches. Syntax is easy with fts:
your_query AND -PATH:"//cm:_archive//*"

to test:
https://www.docdroid.net/RmKj9gB/search-test.pdf.html
take the pdf, put it into your repo twice:

*

*/some_random_path/search-test.pdf

*/some_random_path/_archive/search-test.pdf

In node-browser everything works as expected:
TEXT:"HODOR" AND -PATH:"//cm:_archive//*"
= 1 result

TEXT:"HODOR"
= 2 results

So, my idea was to edit search.get.config.xml and add the exclusion to the list of properties:
<search>
    <default-operator>AND</default-operator>
    <default-query-template>%(cm:name cm:title cm:description ia:whatEvent
        ia:descriptionEvent lnk:title lnk:description TEXT TAG) AND -PATH:"//cm:_archive//*"
    </default-query-template>
</search>

But it does not work as intended! As soon as i am using 'text:' or 'name:' in the search field, the exclusion seems to be ignored.
What other option do i have? Basically just want to add the exclusion to the base query after the default query template is used.
Version is Alfresco Community 5.0.d
thanks!

A: I guess you're mistaken what query templates are meant for. Take a look at the Wiki.
So what you're basically doing is programmatically saying I've got a keyword and I want to match the keywords to the following metadata fields.
Default it will match cm:name cm:title cm:description etc. This can be changed to a custom field or in other cases to ALL.
So putting an extra AND or here of whatever won't work, cause this isn't the actual query which will be built. I can go on more about the query templates, but that won't do you any good.
In your case you'll need to modify the search.get webscript of Alfresco and the method called function getSearchResults(params) in search.lib.js (which get's imported).
Somewhere in at the end of the method it will do the following:
ftsQuery = '(' + ftsQuery + ') AND -TYPE:"cm:thumbnail" AND -TYPE:"cm:failedThumbnail" AND -TYPE:"cm:rating" AND -TYPE:"st:site"' + ' AND -ASPECT:"st:siteContainer" AND -ASPECT:"sys:hidden" AND -cm:creator:system AND -QNAME:comment\\-*';

Just add your path to query to it and that will do.