LilyPond: auto horizontal space for dynamic text

Question: I am missing something basic, I spent hours searching for docs for no avail. Sometimes LilyPond can be really frustrating.
Look at this picture:

Obviously, ppp overlaps with the bar line. According to documentation, I tried using DynamicText.extra-spacing-width, but it has zero effect. Here's the code:
\version "2.22.1"
\language "italiano"

common = {
    \key sol \minor
    \time 4/4
    \tempo "Largo [Широко]"
}

right = \relative do'' {
    \key sol \major
    sol8 (fad re mi sol fad re4) |
    sol8 (fad re mib sol fad re4)
}

left = \relative do' {
    \key sol \major
    sol,8 (re' si' re,) sol, (re' do' re,) |
    sol, (re' sib' re,) sol, (re' do' re,) |
}

dynamics = {
    s1 |
    \override DynamicText.extra-spacing-width = #'(-1 . 1)
    s8 \ppp s8 s8 s8 s8 s8 s4
}

\score {
    \new PianoStaff <<
        \new Staff = "right" \right
        \new Dynamics \dynamics
        \new Staff = "left" { \clef bass \left }
    >>
}

If I move \override ... right in the front of \ppp, it doesn't overlap, but LilyPond complains then with "Unattached AbsoluteDynamicEvent".
Answer: I run into this a lot.  I find that using an X-offset works:
dynamics = {
    s1 |
    \override DynamicText.X-offset = 0
    s8 \ppp s8 s8 s8 s8 s8 s4
}

Comment: Very intuitive :)
Answer: This looks like a bug to me. For extra-spacing-width to work, both of the objects that should avoid each other must have some width and some height. You can visualize the "skylines" that LilyPond uses for distancing using
#(ly:set-option 'debug-skylines)
\layout {
  \context {
    \Score
    \override PaperColumn.stencil = #ly:separation-item::print
    \override NonMusicalPaperColumn.stencil = #ly:separation-item::print
  }
}

(it's expected that the ones from the lower staff are vertically off by some amount; horizontal skylines are built before line breaking, when we only have an estimation of the distance between the two staves).
This gives:

You can see that the problem is the SpanBar not receiving skylines; this is because it has no height, so the interval on which it is considered to collide is not known.
For now a workaround seems to be
\layout {
  \context {
    \Score
    \override SpanBar.Y-extent = #axis-group-interface::height
    \override SpanBar.meta.object-callbacks.pure-Y-common =
      #ly:axis-group-interface::calc-pure-y-common
    \override SpanBar.meta.object-callbacks.pure-relevant-grobs =
      #ly:axis-group-interface::calc-pure-relevant-grobs
  }
}

(there must be a reason why it is not in the current code, so be aware that it could have bad effects in cases that I have no considered).
Comment: Not fully. Spanners do not participate in horizontal spacing the same way as items with skylines, only via minimum-distance and minimum-distance-after-break as far as I can see. At least, my pending merge request https://gitlab.com/lilypond/lilypond/-/merge_requests/842 does not solve the case`\version "2.23.4"

\layout {
  \context {
    \Score
    \override BarLine.bar-extent = #'(-10 . 10)
    \override Parentheses.font-size = 10
  }
}

\new StaffGroup <<
  { c1\parenthesize\< 1\! }
  { c1 1 }`
>>
Comment: Ok,

- SpanBar is the grob that draws the part of the bar line between staves. To understand, try

\version "2.22.1" \new StaffGroup \with { \override SpanBar.color = red } << { c1 } { c1 } >>

- Skylines are outlines of objects. They are used to resolve collisions. You can view them as pieces of metal in the score, with space between them; LilyPond could compress the score until the pieces are touching each other. This applies to horizontal and vertical spacing.

- The code is not supposed to be understandable. It's a horrible low-level hack.
Comment: Would this same SpanBar issue explain the problem is this question?: [LilyPond: parenthesized hairpin](https://music.stackexchange.com/q/116313/70803).
Comment: I don't understand practically anything in this post. I don't understand the code, the term "skylines", how to interpret the picture, and what is SpanBar.
Comment: @JeanAbouSamra Your SpanBar workaround has a strange side effect. It changes the paging; the resulting score has very sparse systems on the page.


heroku Error: ENOENT, stat '/app/build/index.html'

Question: Im trying to deploy to heroku but Im getting Error: ENOENT, stat '/app/build/index.html' when I go to my address. Otherwise the application deployment does not give me any error. Can somebody explain what Im doing wrong. Here is my code and code structure.
server.js
var express = require('express'),
    server = express(),
    bodyParser = require('body-parser'),
    logger = require('morgan'),
    methodOverride = require('method-override'); // for heroku

var port = process.env.PORT || 5000;

server.use(express.static(__dirname + '/build'));
server.use('/src', express.static(__dirname + '/build/src'));       // js
server.use('/assets', express.static(__dirname + '/build/assets')); // css, images
server.use('/vendor', express.static(__dirname + '/build/vendor')); // other

server.use(logger('dev'));

server.get('/', function(req, res, next) {
  res.sendfile('index.html', { root: __dirname + '/build' });
});

server.listen(port, function() {
  console.log("Listening on " + port);
});

Structure in app
├── Gruntfile.js
├── LICENSE
├── Procfile
├── README.md
├── bower.json
├── build
│   └── ....
├── build.config.js
├── config
│   └── db.js
├── karma
│   └── karma-unit.tpl.js
├── module.prefix
├── module.suffix
├── node_modules
│   └── ...
├── package.json
├── server.js
├── src
│   ├── app
│   ├── assets
│   ├── common
│   ├── index.html
│   └── less
└── vendor

Structure in app/build
├── assets
│   ├── O-viu-0.0.1.css
│   └── README.md
├── index.html
├── karma-unit.js
├── src
│   └── app
│       ├── about
│       │   └── about.js
│       ├── app.js
│       └── home
│           └── home.js
├── templates-app.js
├── templates-common.js
└── vendor
    ├── angular
    │   └── angular.js
    ├── angular-bootstrap
    │   └── ui-bootstrap-tpls.min.js
    ├── angular-ui-router
    │   └── release
    │       └── angular-ui-router.js
    └── placeholders
        └── angular-placeholders-0.0.1-SNAPSHOT.min.js

Answer: Figured it out. It was my .gitignore file where I included the /build folder.
Comment: I have been pulling my hair out for over a day on this problem and it all came down to just including my build folder. Thank you! Ended up using Git instead of Heroku's git system so I was able to visualize better what files where being added or removed.
Comment: Glad it was helpful!
Answer: Try somthing like this:
res.sendfile( __dirname + '/build/index.html' );


How can you assign a single track to multiple outputs on Cubase 5?

Question: Hello all I'm a drummer and I'm having a problem with cubase (noob),
I'm trying to setup my jamming studio.
Equipment:

Laptop + USB Sound card interface (with 2 stereo outs or 4 mono)
Amp
Cubase 5
3x mixers

Playback Tracks:

Symphonic track
Guitars Track
Click Track

Current Setup
The drums are spread over 2 mixers and out to the 3rd.
Cubase on the laptop outputs through the sound interface.
The rest of the instruments like keyboards and lead guitar go through 3 3rd mixer.
The output goes to the Amp and My headphones.
The Desired output
Whilst jamming, we need the symphony & guitars (cubase tracks) and everything else except the click to come out the amp.
However in my headphones, I need the Symphony and the click only.
All I'm stuck with, is trying to output a single track to multiple outputs on cubase, I can isolate the click to my headphones through cubase, but I cannot play the symphony on the headphones because it outs to the Amp, I've tried some tricks I found online, but couldn't get it to work, and doubt that they will.
How can you assign a single track to multiple outputs on Cubase 5?
Comment: It's been a while since I used v5 - I'm currently testing 8... but investigate the Control Room options. Manual here if you don't have it - https://www.steinberg.net/en/support/downloads/downloads_cubase_5.html
Answer: Screenshots are from Nuendo 4, the coeval of Cubase 5. So it should be similar.
In the "VST Connections" menu add two stereo busses for each stereo-out of your USB sound card. I called them "Main" and "Headphones".

On channel settings pick "Main" for Symphony and Guitar channel outs.

If your click is the default Cubase click, in the "VST Connections" menu, disable it for the "Main", and enable it for the "Headphone".

If your click is not the default Cubase click but an individual click track, pick "No Bus" for the Click channel out.

"Main" outs are set. Now we should set the sends for "Headphone".
Go to "Sends" of channel Symphony (and the Click track if there is one) and add "Headphone" to one of the sends.

By default, sends are added "disabled with volume fader minimized". Don't forget to both enable and increase the volume after adding a send. At the end it should look like this:

You can solo the tracks and use the main mixer to check visually if the channel routings work as expected.
Answer: I believe what you're looking for is what's referred to as a "bus track" (though I've really only heard it called a "bus"). On the amp bus, you'll have everything (minus the click). On the headphones bus, you'll have the symphony and click (though you may need to render/bounce the click down to its own audio track. Offhand, I don't know how to route the click to a specific track/bus on its own.)
Here is a link that explains how to set these up in Cubase 6. I think it's similar enough in Cubase 5 to figure it out from these steps. If not, let me know and I'll try to post an update with instructions specific to 5.
Comment: Thank you, I've attempted this for a couple of days and couldn't get it to work, I ended up duplicating the track


Well-definedness of the integral of a simple function

Question: A simple function $f:X \to \mathbb{C}$ on a measure space $(X,\mu)$ is a measurable function with a finite range. Let $\mathrm{ran}(f) = \{z_1,\dots,z_n\}$. Then the standard representation of $f$ is given by $$f = \sum_{k = 1}^n z_k \chi_{f^{-1}(\{z_k\})}$$ according to the book by Folland. He defines the $\mu$-integral of a nonnegative simple function $f: X \to [0,\infty]$ as $$\int_X f d\mu := \sum_{k = 1}^n z_k \mu\left(f^{-1}(\{z_k\})\right)$$ However, for example Cohn or Elstrodt (and my professor) now proove, that this integral is independent of the representation of $f$. I think, if we do define the standard representation like Folland, this is an unnecessary task, since the standard representation is unique. Am I right?
Comment: It's not clear that that this integral only depends on $f$ from the definition, but if it were then it would be clear that it didn't matter how $f$ were represented.
Comment: Even though the standard representation is unique, it would not be satisfactory to define the integral in terms of it, unless every other representation gave the $same$ result. Hence, the proofs in Cohn, et al-
Comment: @Chilango Ah I see what you mean. But if we define it invoking the standard representation it is not mandatory (but nice to know, or satisfacting) to show the independence of the representation. In Cohn, et. al it is called well-definedness, but the main point here is (defining it with the standard representation), that it is already well-defined. Thanks.
Comment: I think the main point is that one may use the standard representation to define the integral precisely because $any$ two representations give the same result. Were this not the case, a satisfactory theory could not be developed. So, at some point, you need to prove the independence, much in the same way that $1/2$ for example is simply a representative of an equivalence class of ordered pairs.
Answer: A nice answer to this question can be found in the Real Analysis book by Stein and Shakarchi, page 50-52.


R.Layout.mylayout is giving the wrong integer - Android

Question: I'm making an Android app. It was working fine, I was fiddling around with stuff, editing the layout xml files, when suddenly it started creating the wrong activities whenever an activity was made. for example, if I want to get the stats.xml layout, I try setContentView(R.layout.stats);, but that gives me a different page (the one before alphabetically, called signup.xml).
It works if I use setContentView(R.layout.stats + 1); but it's pretty worrying to have to do this! Is there some way I can tell the AndroidManifest.xml file to recalculate all the R.layout integers or something? And what might I have done to cause this bug (assuming this isn't a feature!)?
Comment: Have you tried cleaning your project *(`Project -> Clean ...` in eclipse)*?
Comment: despite of suggested cleaning: do you use libraries? have you restarted eclipse? have you changed your build target?
Comment: I tried cleaning - it changed it, but it's still wrong. It may have changed the transposition though.  @RafaelT I do use libraries in some of my code, but well after the point where it's already gone wrong. I have restarted eclipse. How would I change my build target, what to and what from?
Comment: do these libs have their own resources? They could cause naming conflicts, and have you cleaned every Project depending?
Answer: Clean the project or delete the R class manually.
Comment: Ah - it instantly created an identical R.java file, giving the same error. Cleaning also didn't work... *Edit*: I tell a lie! I was fooled by my earlier attempts to try to compensate for the error, adding one to the R.layout.stats integer. Deleting R.java seemed to do the trick. Thanks!
Comment: No problem, I did not do anything ;-)


Exclude taxonomy terms from being choosen in facets

Question: I am working on a search field with a facet which has a list of taxonomy terms.
Some taxonomy terms I want to exclude from being choosen, because it is not relevant for people to know about.
How can I exclude taxonomy terms in a facet so people can't choose them while searching?
Answer: I found it.
At this page: /admin/config/search/facets/(facet name)/edit, there's something called Exclude specified items.
That's the place where I can exclude taxonomy terms.


dllexport a type with a std container of std::unique_ptr results in error C2280

Question: I'm trying to dllexport a type with a std container of std::unique_ptr member, f.e.
struct __declspec(dllexport) C {
    std::vector<std::unique_ptr<int>> c_;
};

but whatever i try, msvc always complains about
msvc/14.33.31629/include\xutility(4145): error C2280: 'std::unique_ptr<int,std::default_delete<int>> &std::unique_ptr<int,std::default_delete<int>>::operator =(const std::unique_ptr<int,std::default_delete<int>> &)': attempting to reference a deleted function

The container type doesn't matter; the error is almost identical (always C2280) for vector, map, and others.
However, as soon as a std::unique_ptr member is added to the type, f.e.
struct __declspec(dllexport) C {
    std::vector<std::unique_ptr<int>> c_;
    std::unique_ptr<int> rup;
};

the error disappears.
I have no clue if this is the intended behavior, what causes this problem and how it can be fixed without adding a random std::unique_ptr member. What am i missing?
Demo
Comment: The short answer really is: Don't. The C++ Standard Library makes no ABI stability guarantees. If you want to have a `std::unique_ptr` cross a DLL boundary, then both sides have to agree on the concrete implementation: Same compiler, same version. This is a hard requirement that's next to impossible to enforce. Only use types with well defined ABI layout at the interface, and even then you're [not entirely safe](https://learn.microsoft.com/en-us/cpp/c-runtime-library/potential-errors-passing-crt-objects-across-dll-boundaries).
Answer: When you have a member std::vector<std::unique_ptr<int>> c_;, the compiler will provide a copy assignment operator C& operator=(const C&) that will try to copy the c_ member. This will fail to compile if it is actually used, since the elements of c_ can't be copied.
__declspec(dllexport) seems to try to create this implicitly-declared function (maybe to export it? Though it doesn't seem to actually do that), which fails.
When you add std::unique_ptr<int> rup;, this is a type without a copy constructor at all, so the implicit operator=(const C&) is suppressed (The move assign operator C& operator=(C&&) can still be used).
You can get rid of the implicit copy-assign operator by declaring a move-assign operator or a move constructor:
struct __declspec(dllexport) C {
    std::vector<std::unique_ptr<int>> c_;
    C(C&&) = default;
};

Or by inheriting from a move-only type/having a move-only member:
struct move_only { constexpr move_only(move_only&&) noexcept = default; };

struct __declspec(dllexport) C : private move_only {
    std::vector<std::unique_ptr<int>> c_;
};

Answer: unique_ptr is not a copyable type (or else it wouldn't be unique). The error message is complaining that something is trying to access the unique_ptr's copy assignment operator, which has been disabled.
In your first example, your C struct has only copyable members, so a default copy constructor and copy assignment operator are generated for it by the compiler. Which then fails if they are invoked since unique_ptr can't be copied.
Whereas in your second example, your C struct has a non-copyable member, so the default copy constructor and copy assignment operator are not generated by the compiler.


How can I interpret what I get out of PCA?

Question: As part of a University assignment, I have to conduct data pre-processing on a fairly huge, multivariate (>10) raw data set. I'm not a statistician in any sense of the word, so I'm a little confused as to what's going on.  Apologies in advance for what is probably a laughably simple question - my head's spinning after looking at various answers and trying to wade through the stats-speak.
I've read that:

PCA allows me to reduce the dimensionality of my data
It does so by merging / removing attributes / dimensions that correlate a lot (and thus are a little unnecessary)
It does so by finding eigenvectors on covariance data (thanks to a nice tutorial I followed through to learn this)

Which is great.
However, I'm really struggling to see how I can apply this practically to my data. For instance (this is not the data set I'll be using, but an attempt at a decent example people can work with), if I were to have a data set with something like...
PersonID     Sex     Age Range    Hours Studied     Hours Spent on TV      Test Score     Coursework Score
1            1       2            5                 7                      60             75
2            1       3            8                 2                      70             85
3            2       2            6                 6                      50             77
...          ...     ...          ...               ...                    ...            ...

I'm not quite sure how I would interpret any results.
Most of the tutorials I've seen online seem to give me a very mathematical view of PCA. I've done some research into it and followed them through - but I'm still not entirely sure what this means for me, who's just trying to extract some form of meaning from this pile of data I have in front of me.
Simply performing PCA on my data (using a stats package) spits out an NxN matrix of numbers (where N is the number of original dimensions), which is entirely greek to me.
How can I do PCA and take what I get in a way I can then put into plain english in terms of the original dimensions?
Comment: Your example data shows a mixture of data types: Sex is dichotomous, Age is ordinal, the other 3 are interval (and those being in different units). Doing linear PCA is right for interval data (but you have first to z-standardize those variables, because of the units). It is debatable whether PCA is appropriate for [binary or dichotomous](http://stats.stackexchange.com/q/16331/3277) data. You should not use ordinal data in linear PCA. But the main question with your example data: why _at all_ to do PCA with it; what sense could it make in this case?
Comment: I only can recommend you, at present, to read more on PCA (on this site, too). Many uncertainties will surely go away.
Comment: (Please correct me if I'm wrong) I believe that PCA is/can be very useful for helping to find trends in the data and to figure out which attributes can relate to which (which I guess in the end would lead to figuring out patterns and the like). My assignment details that I have this massive data set and I just have to apply clustering and classifiers, and one of the steps it lists as vital to pre-processing is PCA. Would it help if I tried to extract some second order attributes from the data set I have to try and get them all in interval data?
Comment: This pdf is useful for the [application of PCA](http://www.cs.otago.ac.nz/cosc453/student_tutorials/principal_components.pdf). The other posts here do a good job as describing the "meaning" of your PCA results.
Comment: Many fine links above, here is a short example that "could" give you a good feel about PCA in terms of regression, with a practical example and very few, if at all, technical terms. http://sites.stat.psu.edu/~ajw13/stat505/fa06/16_princomp/10_princomp_reg_example.htm
Comment: ttnphn's comment about the varying types of data in your set is important. PCA works best when the variables are of the same type. You might get credit for being aware of the risks of preprocessing the data in a way liable to produce poor results.
Answer: Pages 13-20 of the tutorial you posted provide a very intuitive geometric explanation of how PCA is used for dimensionality reduction.
The 13x13 matrix you mention is probably the "loading" or "rotation" matrix (I'm guessing your original data had 13 variables?) which can be interpreted in one of two (equivalent) ways:

The (absolute values of the) columns of your loading matrix describe how much each variable proportionally "contributes" to each component.
The rotation matrix rotates your data onto the basis defined by your rotation matrix. So if you have 2-D data and multiply your data by your rotation matrix, your new X-axis will be the first principal component and the new Y-axis will be the second principal component.

EDIT: This question gets asked a lot, so I'm just going to lay out a detailed visual explanation of what is going on when we use PCA for dimensionality reduction.
Consider a sample of 50 points generated from y=x + noise. The first principal component will lie along the line y=x and the second component will lie along the line y=-x, as shown below.

The aspect ratio messes it up a little, but take my word for it that the components are orthogonal. Applying PCA will rotate our data so the components become the x and y axes:

The data before the transformation are circles, the data after are crosses. In this particular example, the data wasn't rotated so much as it was flipped across the line y=-2x, but we could have just as easily inverted the y-axis to make this truly a rotation without loss of generality as described here.
The bulk of the variance, i.e. the information in the data, is spread along the first principal component (which is represented by the x-axis after we have transformed the data). There's a little variance along the second component (now the y-axis), but we can drop this component entirely without significant loss of information. So to collapse this from two dimensions into 1, we let the projection of the data onto the first principal component completely describe our data.

We can partially recover our original data by rotating (ok, projecting) it back onto the original axes.

The dark blue points are the "recovered" data, whereas the empty points are the original data. As you can see, we have lost some of the information from the original data, specifically the variance in the direction of the second principal component. But for many purposes, this compressed description (using the projection along the first principal component) may suit our needs.
Here's the code I used to generate this example in case you want to replicate it yourself. If you reduce the variance of the noise component on the second line, the amount of data lost by the PCA transformation will decrease as well because the data will converge onto the first principal component:
set.seed(123)
y2 = x + rnorm(n,0,.2)
mydata = cbind(x,y2)
m2 = colMeans(mydata)

p2 = prcomp(mydata, center=F, scale=F)
reduced2= cbind(p2$x[,1], rep(0, nrow(p2$x)))
recovered = reduced2 %*% p2$rotation

plot(mydata, xlim=c(-1.5,1.5), ylim=c(-1.5,1.5), main='Data with principal component vectors')
arrows(x0=m2[1], y0=m2[2]
       ,x1=m2[1]+abs(p2$rotation[1,1])
       ,y1=m2[2]+abs(p2$rotation[2,1])
       , col='red')
arrows(x0=m2[1], y0=m2[2]
       ,x1=m2[1]+p2$rotation[1,2]
       ,y1=m2[2]+p2$rotation[2,2]
       , col='blue')

plot(mydata, xlim=c(-1.5,1.5), ylim=c(-1.5,1.5), main='Data after PCA transformation')
points(p2$x, col='black', pch=3)
arrows(x0=m2[1], y0=m2[2]
       ,x1=m2[1]+abs(p2$rotation[1,1])
       ,y1=m2[2]+abs(p2$rotation[2,1])
       , col='red')
arrows(x0=m2[1], y0=m2[2]
       ,x1=m2[1]+p2$rotation[1,2]
       ,y1=m2[2]+p2$rotation[2,2]
       , col='blue')
arrows(x0=mean(p2$x[,1])
      ,y0=0
      ,x1=mean(p2$x[,1])
      ,y1=1
      ,col='blue'
       )
arrows(x0=mean(p2$x[,1])
       ,y0=0
       ,x1=-1.5
       ,y1=0
       ,col='red'
)
lines(x=c(-1,1), y=c(2,-2), lty=2)

plot(p2$x, xlim=c(-1.5,1.5), ylim=c(-1.5,1.5), main='PCA dimensionality reduction')
points(reduced2, pch=20, col="blue")
for(i in 1:n){
  lines(rbind(reduced2[i,], p2$x[i,]), col='blue')
}

plot(mydata, xlim=c(-1.5,1.5), ylim=c(-1.5,1.5), main='Lossy data recovery after PCA transformation')
arrows(x0=m2[1], y0=m2[2]
       ,x1=m2[1]+abs(p2$rotation[1,1])
       ,y1=m2[2]+abs(p2$rotation[2,1])
       , col='red')
arrows(x0=m2[1], y0=m2[2]
       ,x1=m2[1]+p2$rotation[1,2]
       ,y1=m2[2]+p2$rotation[2,2]
       , col='blue')
for(i in 1:n){
  lines(rbind(recovered[i,], mydata[i,]), col='blue')
}
points(recovered, col='blue', pch=20)

Comment: David, please, refrain from use terms "rotation matrix" (aka eigenvectors) and "loading matrix" interchangeably. For purity and not to mislead people. Loadings in PCA are eigenvectors _after_ normalizing by their eigenvalues. Thank you.
Comment: Sorry, but I would disagree. Reason: remember that loadings are both meaningful (and in the same sense!) to PCA and factor analysis. Loadings are directly comparable to the correlations/covariances. Eigenvectors are the rotation cosines. In factor analysis, many methods do not deal with rotation (_at_ extraction phase). So, mixing the two terms are indeed misleading to students and should be avoided.
Comment: @ttphns I think it completely depends on what package you use. Often these terms are completely interchangeable. Consider the usage of "loadings" here: http://www.utdallas.edu/~herve/abdi-awPCA2010.pdf. Also reference the R function `prcomp` where the loadings matrix is just the matrix whose columns are unit eigenvectors. I think you are being unnecessarily technical, and in most cases I believe these terms are used interchangeably.
Comment: Another visual can be found here http://setosa.io/ev/principal-component-analysis/
Comment: Smaller point: correct spelling is always and only "principal", not "principle". I've edited accordingly, but one image I can't edit.
Answer: I would say your question is a qualified question not only in cross validated but also in stack overflow, where you will be told how to implement dimension reduction in R(..etc.) to effectively help you identify which column/variable contribute the better to the variance of the whole dataset.
The PCA(Principal Component Analysis) has the same functionality as SVD(Singular Value Decomposition), and they are actually the exact same process after applying scale/the z-transformation to the dataset.
Here are some resources that you can go through in half an hour to get much better understanding.
I am not capable to give a vivid coding solution to help you understand how to implement svd and what each component does, but people are awesome, here are some very informative posts that I used to catch up with the application side of SVD even if I know how to hand calculate a 3by3 SVD problem.. :)

Coursera Data Analysis Class by Jeff Leek: Video Lecture / Class Notes
A Very Informative student post
A post from American Mathematical Society.
Comment: Jeff Leek's class is very good for getting a feeling of what you can do with PCA. The good thing is that it does not get into complex mathematical/statistical details (which can be found in plenty of other places) but rather provides an hands-on approach showing how to really use it on data.
Answer: In PCA you want to describe the data in fewer variables. You can get the same information in fewer variables than with all the variables. For example, hours studied and test score might be correlated and we do not have to include both.
In your example, let's say your objective is to measure how "good" a student/person is. Looking at all these variables, it can be confusing to see how to do this. PCA allows us to clearly see which students are good/bad.
If the first principal component explains most of the variation of the data, then this is all we need. You would find the correlation between this component and all the variables. "Large" correlations signify important variables. For example, the first component might be strongly correlated with hours studied and test score. So high values of the first component indicate high values of study time and test score.


How does AMOS or other SEM/path analysis software estimate missing data?

Question: I'm currently writing a paper as a hopeful publication. I'm using AMOS to run path models. But I think my question can apply when utilizing other path analytical software.
I have one path model that had missing data in the dependent variable so I had to allow Amos to 'estimate means and intercepts'
How does AMOS or other SEM/path analysis software estimate missing data?
Using a multiple regression allegory, does it run the analysis without the missing data, finds the beta's and intercepts, and use that to estimate the missing dependent variable data? And then run the analysis again with the full dataset of both missing subbed with the estimates and the non-missing data?
Answer: SEM programs (generally) use full information maximum likelihood (FIML) estimation. It doesn't really think about missing data as it calculates a likelihood for all of the data points that exist, it does not try to estimate what the missing values are. What you are describing is a little like multiple imputation (MI), which is asymptotically equivalent to FIML, but FIML can be model dependent, where MI is not.
Some people argue that the Full Information part is redundant, as ML should use full information (e.g. mixed models estimated with ML are equivalent to SEM models with FIML estimation, but people don't talk about FIML with mixed models, just ML).
Using your favorite search engine, you'll find lots of information on SEM and FIML, including some answers on this site, e.g. Full information maximum likelihood for missing data in R . The level of technical sophistication required to read papers on FIML varies a lot - so if you don't find things at your level, keep looking. However, the book chapter that first helped me to understand it (although it's getting a bit old now) is this one: Arbuckle, J. L. (1996). Full information estimation in the presence of incomplete data. In G. A.
Marcoulides & R. E. Schumacker (Eds.), Advanced structural equation modeling (pp. 243–
277). Mahwah, NJ: Lawrence Erlbaum Associates, Inc.


How should I recover from Ovirt and GlusterFS partial failure?

Question: I am managing a 3 node Ovirt 4.3.7 cluster with a hosted engine appliance; the nodes are also glusterfs nodes. The systems are:

ovirt1 (node at 192.168.40.193)
ovirt2 (node at 192.168.40.194)
ovirt3 (node at 192.168.40.195)
ovirt-engine (engine at 192.168.40.196)

The services ovirt-ha-agent and ovirt-ha-broker are continually restarting on ovirt1 and ovirt3, and this does not seem healthy (the first notice we had of this problem were the logs for these services filling on these systems).
All indications from the GUI consoles are that overt-engine is running on ovirt3. I tried migrating overt-engine to ovirt2, but got a failure without further explanation.
Users are able to create, start, and stop VMs on all three nodes without issue.
I am seeing the following output from gluster-eventaapi status and hosted-engine --vm-status on each of the nodes:
ovirt1:
[root@ovirt1 ~]# gluster-eventsapi status
Webhooks:
http://ovirt-engine.low.mdds.tcs-sec.com:80/ovirt-engine/services/glusterevents

+---------------+-------------+-----------------------+
|      NODE     | NODE STATUS | GLUSTEREVENTSD STATUS |
+---------------+-------------+-----------------------+
| 192.168.5.194 |          UP |                    OK |
| 192.168.5.195 |          UP |                    OK |
|   localhost   |          UP |                    OK |
+---------------+-------------+-----------------------+
[root@ovirt1 ~]# hosted-engine --vm-status
The hosted engine configuration has not been retrieved from shared storage. Please ensure that ovirt-ha-agent is running and the storage server is reachable.

ovirt2:
[root@ovirt2 ~]# gluster-eventsapi status
Webhooks:
http://ovirt-engine.low.mdds.tcs-sec.com:80/ovirt-engine/services/glusterevents

+---------------+-------------+-----------------------+
|      NODE     | NODE STATUS | GLUSTEREVENTSD STATUS |
+---------------+-------------+-----------------------+
| 192.168.5.195 |          UP |                    OK |
| 192.168.5.193 |          UP |                    OK |
|   localhost   |          UP |                    OK |
+---------------+-------------+-----------------------+
[root@ovirt2 ~]# hosted-engine --vm-status

--== Host ovirt2.low.mdds.tcs-sec.com (id: 1) status ==--

conf_on_shared_storage             : True
Status up-to-date                  : True
Hostname                           : ovirt2.low.mdds.tcs-sec.com
Host ID                            : 1
Engine status                      : {"reason": "vm not running on this host", "health": "bad", "vm": "down_unexpected", "detail": "unknown"}
Score                              : 0
stopped                            : False
Local maintenance                  : False
crc32                              : e564d06b
local_conf_timestamp               : 9753700
Host timestamp                     : 9753700
Extra metadata (valid at timestamp):
    metadata_parse_version=1
    metadata_feature_version=1
    timestamp=9753700 (Wed Mar 25 17:45:50 2020)
    host-id=1
    score=0
    vm_conf_refresh_time=9753700 (Wed Mar 25 17:45:50 2020)
    conf_on_shared_storage=True
    maintenance=False
    state=EngineUnexpectedlyDown
    stopped=False
    timeout=Thu Apr 23 21:29:10 1970

--== Host ovirt3.low.mdds.tcs-sec.com (id: 3) status ==--

conf_on_shared_storage             : True
Status up-to-date                  : False
Hostname                           : ovirt3.low.mdds.tcs-sec.com
Host ID                            : 3
Engine status                      : unknown stale-data
Score                              : 3400
stopped                            : False
Local maintenance                  : False
crc32                              : 620c8566
local_conf_timestamp               : 1208310
Host timestamp                     : 1208310
Extra metadata (valid at timestamp):
    metadata_parse_version=1
    metadata_feature_version=1
    timestamp=1208310 (Mon Dec 16 21:14:24 2019)
    host-id=3
    score=3400
    vm_conf_refresh_time=1208310 (Mon Dec 16 21:14:24 2019)
    conf_on_shared_storage=True
    maintenance=False
    state=GlobalMaintenance
    stopped=False

ovirt3:
[root@ovirt3 ~]# gluster-eventsapi status
Webhooks:
http://ovirt-engine.low.mdds.tcs-sec.com:80/ovirt-engine/services/glusterevents

+---------------+-------------+-----------------------+
|      NODE     | NODE STATUS | GLUSTEREVENTSD STATUS |
+---------------+-------------+-----------------------+
| 192.168.5.193 |        DOWN |           NOT OK: N/A |
| 192.168.5.194 |          UP |                    OK |
|   localhost   |          UP |                    OK |
+---------------+-------------+-----------------------+
[root@ovirt3 ~]# hosted-engine --vm-status
The hosted engine configuration has not been retrieved from shared storage. Please ensure that ovirt-ha-agent is running and the storage server is reachable.

The steps I've taken so far are:

find that logs for the ovirt-ha-agent and ovirt-ha-broker service are not rotating correctly on nodes ovirt1 and ovirt3; the logs show the same failure on both nodes. The broker.log contains this statement repeated frequently:

MainThread::WARNING::2020-03-25 18:03:28,846::storage_broker::97::ovirt_hosted_engine_ha.broker.storage_broker.StorageBroker::(__init__) Can't connect vdsm storage: [Errno 5] Input/output error: '/rhev/data-center/mnt/glusterSD/ovirt2:_engine/182a4a94-743f-4941-89c1-dc2008ae1cf5/ha_agent/hosted-engine.lockspace'

find that the RHEV documentation suggests running hosted-engine --vm-status to understand the problem; that output (above) suggests that ovirt1 is not completely part of the cluster.
I asked on the Ovirt forum yesterday morning, but since I am new there, my question needs a moderator review, and that hasn't happened yet (if the users of this cluster weren't all suddenly working from home, and suddenly dependent upon it, I wouldn't be worried about waiting a few days).

How should I recover from this situation? (I think I need to recover something in the glusterfs cluster first, but can't find a hint or don't have the language to form the right query.)
UPDATE: After restarting glusterd on ovirt3, the glusterfs cluster appears to be healthy, but with no change in behavior on the ovirt services.
Answer: The steps required to recover from the above situation amounted to running the following on ovirt3:
hosted-engine --vm-shutdown
hosted-engine --reinitialize-lockspace
hosted-engine --vm-start

This caused ovirt-engine to start on ovirt2. After that, I restarted the services ovirt-ha-broker.service and ovirt-ha-agent.service on ovirt3.


Limitations of HockeyApp for iOS Enterprise App distribution

Question: I was looking for platforms which can host over-the-air distribution of iOS enterprise App. I came to know about HockeyApp but I dont know the limitations. Can anyone clarify following points:

Is there any trial period for free account?
Is there any expiry date for distribution URL?
How many members, developers, testers and owners can be added to a free account?
How many Apps can be added to free account?
How many new invites can be sent to members?
Comment: Did you visit https://hockeyapp.net/ I guess here (pricing/FAQ) you can find all answers that you're looking. here are the answer according to my current understanding.
 1. `NO` 2. `expiration date of your provisioning profile` 3. `No Limit` 4. `10` 5.`No limit`
Comment: I went through your suggested link. I was helpful. thnks.
Comment: Point #2 - I'm using enterprise build for ios, so i think it wont expire.. Right??
Comment: Yes I didn't face but it's depends on expiration date of your developer profile.
Answer:
There was previously but starting January 1st, 2018, HockeyApp will be completely free: https://www.hockeyapp.net/blog/2017/12/19/hockeyApp-is-now-free-for-all-developers.html
There is no expiration date on the URLs
See 1.; from January 1st, it will all be unlimited.
See 1.; from January 1st, there will be no limit.
There is no limit.


Interpreting two linear regression outputs - one generic, one "faceted" (R, ggplot)

Question: I am trying to analyse the potential relationship between Unemployment Rate and the occurrences of three types of crime (namely Anti-social behaviour, Theft, and Violence & Sexual Offences).
First, I plotted a linear regression model of Unemployment rate and ALL crime types (indistinctively).
PLOT 1:

OUTPUT:
Call:
lm(formula = Crime_occurrences ~ Unemployment_rate, data = df)

Residuals:
   Min     1Q Median     3Q    Max
-27148  -7191   2708   6467  33154

Coefficients:
                  Estimate Std. Error t value Pr(>|t|)
(Intercept)          70916      23671   2.996  0.00389 **
Unemployment_rate    -3508       5835  -0.601  0.54989
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 11550 on 64 degrees of freedom
Multiple R-squared:  0.005614,  Adjusted R-squared:  -0.009923
F-statistic: 0.3613 on 1 and 64 DF,  p-value: 0.5499

My interpretation:
There is no apparent relationship between the two variables because:

t value is extremely low
Pr(>|t|) is >0.05
Residual standard error is considerably high
Multiple R-squared is extremely low (i.e. residuals are all over the place)
F value is extremely low
p value is > 0.05

Question: What else can I add to my interpretation? Also, what does it mean if the intercept Pr(>|t|)  is <0.05?
Plotting a faceted scatter plot and linear regression for each crime type proved more difficult:
PLOT 2:

Output 2:
Call:
lm(formula = Crime_occurrences ~ Unemployment_rate + Crime, data = df)

Residuals:
   Min     1Q Median     3Q    Max
-20871  -6755    362   4597  32818

Coefficients:
                                  Estimate Std. Error t value Pr(>|t|)
(Intercept)                          71252      21686   3.286  0.00168 **
Unemployment_rate                    -3508       5327  -0.658  0.51267
CrimeTheft                           -6613       3180  -2.080  0.04169 *
CrimeViolence and sexual offences     5606       3180   1.763  0.08287 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 10550 on 62 degrees of freedom
Multiple R-squared:  0.1972,    Adjusted R-squared:  0.1584
F-statistic: 5.077 on 3 and 62 DF,  p-value: 0.003301

My interpretation:

The only significancy I can see is with THEFT since Pr(>|t|) is <0.05
However, why is t value negative? That should suggest no relationship, but it clashes with Pr(>|t|)

Questions:

Where is Anti-Social behaviour? It is in the data frame df I specified in the code but not in the output
The p value is < 0.05, which suggests significancy, but which crime type does it suggest significancy with? Is it theft?

Any help would be greatly appreciated!!!
Comment: Please register &/or merge your accounts (you can find information on how to do
this in the **My Account** section of our [help]), then you will be able to
edit & comment on your own question.
Answer: A few suggestions with respect to working with crime data.
First, your plot is investigating the relationship between unemployment rates and total crime counts across many geographic regions. It is unclear what a "region" represents, but it appears they are rather large aerial units (e.g., counties, states, countries, etc.). Some regions experience nearly 40,000 – 60,000 total occurrences of theft/larceny in a given time period. Large aggregate counts suggests you're sampling crime occurrences by U.S. State in one year. If this is so, I would normalize the data. Expressing your outcome $y$ as a crime rate per 100,000 inhabitants is appropriate. Imagine trying to compare total reports of larceny in the State of New York with those reported in Louisiana. Before looking at the data, you might suspect a greater number of larcenies reported in the State of New York, assuming a large number of larcenies occurred within the five boroughs. Once you normalize by the state population, for example, you should find per capita thefts in Louisiana far exceeding per capita thefts in the State of New York. It's a twofold difference. Though your plot's title indicates you're working with per capita rates, the actual numerical quantities plotted suggest otherwise.
Second, I suspect in your first plot each point represents a region's total number of crime occurrences. Total crime occurrences should equal the sum of all incidents within a particular region within a given period of time. This amounts to one data point per jurisdiction. I only mention this because it appears you plotted three separate points for each jurisdiction—one for each crime type. The disaggregated plots suggest you have approximately 22 – 25 independent pieces of information, not 60+ as your first model suggests.
Third, crime counts often exhibit a discernible right skew. For example, theft rates in the District of Columbia will be far out in the right tail of a distribution. Try winnowing your $x$-axis to regions with unemployment rates between 3.75% – 4.25% and note the wide variation within this interval. The variability is particularly pronounced across regions. Differences in "reporting practices" might explain some of this variation across jurisdictions.
As for your interpretation of the first plot, which I assume is your composite crime outcome (i.e., all crimes merged), you are making all the correct observations, but without much substance.

There is no apparent relationship between the two variables.

Correct.
Your bivariate model suggests unemployment does not effect total incidents of crime. However, I wouldn't derive too much causal value from this model. Note that all of your variation is between regions (e.g., states). Try reestimating your base model but now with each region's per capita value. This is very useful when comparing jurisdictions with widely different population sizes.
Your bullet points simply regurgitate your summary output. For example, you note the $F$-statistic is low. This is correct. But what does it mean? For starters, it is a measure of overall significance. It tells you, in simple terms, whether your linear regression model provides a better fit than a model including no independent variables. The $p$-value associated with the test statistic supports a null hypothesis which states that your model which includes the unemployment rate as a predictor does not fit better than one that excludes it (i.e., 'intercept-only' model). I don't want to get too caught up in the weeds here, but the point is, don't simply say a statistic is low without any further explication.

What else can I add to my interpretation? Also, what does it mean if the intercept Pr(>|t|) is < 0.05?

The intercept has little interpretive value. It is the average number of total crime occurrences in a jurisdiction with an unemployment rate at 0%. Is there a region where the percentage of unemployed workers in the total labor force is exactly 0? In sum, the intercept is usually not of substantive interest.
As for your second output, your faceted plot and model summary do not agree. Faceting your data is looking at the relationship between unemployment and crime across different subsets of your data.

Plotting a faceted scatter plot and linear regression for each crime type proved more difficult.

Why did it prove more difficult? It appears you faceted by crime type (i.e., facet_wrap(~ crime)), which produces a bivariate plot of crime ~ unemployment for each crime type. In other words, as you move from left to right, you're running a linear model on different subsets of your data.
Again, the plots do not agree with your output. In fact, your second model is misspecified. You're regressing total crime on the unemployment rate and all sub-categories of crime and expecting software to return a coefficient for each crime type. Unless I am mistaken, the sum of each subtype on the right-hand side is equal to your outcome. Let $Crime^{t}_i$ equal the total number of incidents reported in a particular jurisdiction $i$ in one year; the $t$ superscript denotes the composite sum of all disaggregated crime metrics. Here is your equation expressed mathematically:
$$
Crime^{t}_i = \alpha + \gamma UR_i + Sub^1_i + Sub^2_i + Sub^3_i + \epsilon_i
$$
where $UR_i$ is the unemployment rate in region $i$; it is the primary independent variable of interest. Here, each sub-category of crime, which comprises total crime, is expressed on the right-hand side of the equation. By definition, $Crime^{t} = Sub^1 + Sub^2 + Sub^3$ for any $i$. If you know all sub-categories of total crime then you can perfectly predict total crime. What do you hope to gain from this model? Your crime metrics are your outcomes of interest.

Where is Anti-Social behaviour? It is in the data frame df I specified in the code but not in the output.

Your model must drop one of your disaggregated crime metrics. R orders the factor levels in abecedarian sequence, unless you tell it otherwise, and so it drops the first category which starts with the letter A.

However, why is t value negative? That should suggest no relationship, but it clashes with Pr(>|t|)

The $p$-value is a probability value and by the axioms of probability it is bounded between 0 and 1. The $t$-value, on the other hand, is unbounded. They're different but also inextricably linked. Their signs do not have to agree.

The p value is < 0.05, which suggests significancy, but which crime type does it suggest significancy with? Is it theft?

As a recommendation, I would estimate separate linear models with each crime outcome on the left-hand side. That amounts to four separate calls in R using your four different outcomes: (1) total crime rate, (2) anti-social behavior offense rate, (3) larceny rate, and (4) violence and sexual assault offense rate. Again the total crime rate is the sum of all your disaggregated crime metrics; it is a composite measure of all crime in a particular region. I think you may have estimated your linear model on a data frame where each outcome for each region is stacked. This is understandable in settings where you transform your data into long format to facilitate faceting. If you want separate summary output for each outcome then before running lm() you must create separate columns for each outcome. Once it is in this format, then you can feed each crime outcome to the left-hand side of a standard linear model (i.e., lm(crime ~ unemployment)).

As a final word, anti-social behavior is very broad and is likely to vary considerably by jurisdiction. Take good measure to note any obvious differences in reporting practices across agencies. Also, why combine "violent acts" and "sexual offenses"? Though the nexus between violence and sexual predation is obvious, the term violence is very broad, encompassing crimes such as robbery and other acts of felonious assault. In some cases, multiple offenses may be associated with one incident. For example, possessions forcibly removed from a person is, in some circumstances, a violent theft (e.g., assault + theft). Will you disambiguate between multiple offenses in your crime rate calculations or should only one violent offense take precedence? Some jurisdictions may only report the top charge, which invariably gives more weight to "serious" (i.e., violent) offenses. I only note such concerns because they often arise when working with crime data.
I hope this information helps!
Answer: I am quite sure you use the dataset in the related post here. So you are dealing with time series data. Therefore some of the suggestions made in the previous post can't be used, as regional variation was assumed. Nevertheless, your concrete questions were correctly answered. That's why I want to give you a more general suggestion, how you can analyse the dataset with regard to your research question - the relationship between Unemployment and Crime.
First, when you have time series data, you should not treat it as cross-sectional data. Instead, time series data is more prone to draw false conclusions about the relationships between variables. At the beginning, you should always have a look at the development of your data over time:
dat %>% pivot_wider(names_from = 2, values_from = 3) %>%
  mutate(Unemployment_rate_rescaled = Unemployment_rate * 10000) %>%
  select(-Unemployment_rate) %>%
  pivot_longer(cols = -1, names_to = "variable") %>%
  ggplot(aes(x = Date, y = value, col = variable)) + geom_line()

As we can see, the unemployment rate is more or less stable until July 2020 and steadily increasing afterwards. The crime rates do not show any noticeable development after July 2020. So at least visually there is no clear relationship. However, visual analysis is subjective and only a starting point. So we need statistics to go further.
As you are interested in the bivariate relationships between unemployment rate and occurrences per crime type, looking at the correlations is a good first step:
dat %>% pivot_wider(names_from = 2, values_from = 3) %>%
  select_if(is.numeric) %>% cor %>% .[1,-1]

# Anti-social behaviour    Theft          Violence and sexual offences
# -0.1198733               -0.1421524     0.1414995

The correlation coefficients are obviously quite low. Nevertheless you might want to test for statistical significance. However, this requires some assumptions about the data to be fulfilled. The most important one is stationarity, see here.
Thinking about it in a less technical way: You don't want to know if the time series follow a similar 'meta-pattern', e.g. sharing a similar long-term trend.
A fast way to get rid of those effects and ensure you stationarize the time series is to estimate stationary ARIMA-models for each variable and then analyse the relationships between the residuals. By that you isolate the 'unexpected' changes in the time series and test for significant correlations between your variables of interest:
library(forecast)
get_arima_residuals <- function(x){
  arima_model <- auto.arima(x, stationary = TRUE)
  arima_res <- arima_model$residuals %>% as.numeric()
  return(arima_res)
}

dat_res <- dat %>% pivot_wider(names_from = 2, values_from = 3) %>%
  mutate_if(is.numeric, get_arima_residuals)

x_vars <- c("Anti-social behaviour", "Theft", "Violence and sexual
  offences")
map_dfr(x_vars, ~{
  cor_test <- cor.test(dat_res$Unemployment_rate, dat_wide_res[[.x]])
  data.frame(variable = .x, estimate = cor_test$estimate, p_value =
  cor_test$p.value)
})

#                         variable           estimate    p_value
# cor...1        Anti-social behaviour     -0.15468638  0.4918640
# cor...2                        Theft      0.16526242  0.4623521
# cor...3 Violence and sexual offences     -0.04819431  0.8313429

So, to summarise, there is no statistically significant relationship between crime-occurrences and unemployment-rate.


Pandas comparing dataframes and changing column value based on number of similar rows in another dataframe

Question: Suppose I have two dataframes:
df1:
    Person Number Type
0   Kyle   12     Male
1   Jacob  15     Male
2   Jacob  15     Male

df2:
A much larger dataset with similar format except there is a count column that needs to increment based on df1
    Person Number Type    Count
0   Kyle   12     Male    0
1   Jacob  15     Male    0
3   Sally  43     Female  0
4   Mary   15     Female  5

What I am looking to do is increase the count column based on the number of occurrences of the same person in df1
Excepted output for this example:
    Person Number  Type    Count
0   Kyle   12     Male    1
1   Jacob  15     Male    2
3   Sally  43     Female  0
4   Mary   15     Female  5

Increase count to 1 for Kyle because there is one instance, increase count to 2 because there are two instances for Jacob. Don't change value for Sally and Mary and keep the value the same.
How do I do this? I have tried using .loc but I can't figure out how to account for two instances of the same row. Meaning that I can only get count to increase by one for Jacob even though there are two Jacobs in df1.
I have tried
df2.loc[df2['Person'].values == df1['Person'].values, 'Count'] += 1
However this does not account for duplicates.
Answer: df1 = df1.groupby(df.columns.tolist(), as_index=False).size().to_frame('Count').reset_index()

df1 = df1.set_index(['Person','Number','Type'])
df2 = df2.set_index(['Person','Number','Type'])

df1.add(df2, fill_value=0).reset_index()

Or
df1 = df1.groupby(df.columns.tolist(), as_index=False).size().to_frame('Count').reset_index()
df2.merge(df1, on=['Person','Number','Type'], how='left').set_index(['Person','Number','Type']).sum(axis=1).to_frame('Count').reset_index()

Answer: value_counts + Index alignment.
u = df2.set_index("Person")
u.assign(Count=df1["Person"].value_counts().add(u["Count"], fill_value=0))

        Number    Type  Count
Person
Kyle        12    Male    1.0
Jacob       15    Male    2.0
Sally       43  Female    0.0
Mary        15  Female    5.0


aws lambda cannot start step functions in eu-west-1

Question: I have lambda function that starts AWS Step Functions. Step Function is defined in eu-west-1. My lambda function is in eu-central-1 and I am able to launch step functions from lambda.
I copy/paste lambda function to eu-west-1, assign same role but step function is not started. When I hit test, I get wait cursor and after specified timeout, execution of lambda is stopped. Code blocks at startExecution
var stepfunctions = new aws.StepFunctions();
console.log("params: " + JSON.stringify(params)); // This is printed
let result = await stepfunctions.startExecution(params, function(err, data) {

To emphasize once more. Same code, same role works in eu-central-1 but not in eu-west-1. In both case runtime is Node.js 12.x
Answer: Problem was in VPC configuration. VPC was asigned to lambda. It disables access to AWS services. Endpoint to com.amazonaws.eu-west-1.states should be added to VPC.


Developing Cordova + Ionic in Android Studio [Ionic Serve]

Question: I'm new in developing with Ionic. I want to develop for android devices. I have loaded the android folder below in Android Studio and started developing. From there I can easily run the application on my connected device. But for developing a bit more faster, i want to develop in browser. When I navigate to the project with CMD and execute ionic serve i always get the "Ionic Blank Starter" Page. I guess he is accessing on the www folder in main root, but how I can execute the project under platforms/android in browser?
Answer: Please refer to
http://ionicframework.com/docs/guide/testing.html
$ cordova prepare android

want to help you.
Comment: Didn't helped, this just added a new android project within my ionic project. I want only test my application, which im developing for android in a browser.
Comment: Have you considered using this?
[link](http://taco.visualstudio.com/en-us/docs/run-app-ripple-simulator/)
Answer: Had same problem, and in the end I was forced to move/overwrite www folder from android to the root of Ionic project. Then 'ionic serve' will work. If you will need to launch Android; run 'cordova prepare android' as was mentioned before. Do it with attention - 'prepare android' will overwrite old android project and its www folder.
Answer: Ionic runs within the file structure which is created by itself.
The content in platforms is generated (and ovewrited) by ionic when you run ionic serve based on the contents on www folder and the files in the root project folder.
I still don't know a way to get an actually app built from Android Studio and convert to ionic, it will be a good find.


How can I create a custom service?

Question: I've been following instructions on the web on creating a new service, but I can't seem to get it to work.
In my controller:
namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

class MyController extends ControllerBase {
  public function myroute() {
      $db = \Drupal::service('mymodule.db');
      return array('DEBUG');
  }
}

In my mymodule.services.yml:
services:
  mymodule.db:
    class: Drupal\mymodule\mymoduleDB

In my service class:
namespace Drupal\mymodule;

class mymoduleDB {
  public function dosomething() {
    return 'data...';
  }
}

In my controller, when I comment out the line that calls \Drupal::service, then the controller works, so it's an issue with calling the service.
I'm getting a HTTP 500 error.
Answer: Create mymodule.services.yml
services:
  mymodule.custom_services:
    class: Drupal\mymodule\Services\CustomService
    arguments: []

Now create Services folder under your mymodule/src. After that create CustomService.php in Service folder.
In CustomService.php
<?php

namespace Drupal\mymodule\Services;

/**
 * Class CustomService.
 */
class CustomService {

  /**
   * Constructs a new CustomService object.
   */
  public function __construct() {

  }

  public function getServiceData() {
    //Do something here to get any data.
  }
  /**
   * Here you can pass your values as $array.
   */
  public function postServiceData($array) {
    //Do something here to post any data.
  }
}

And for accessing service in your module file
$service = \Drupal::service('mymodule.custom_services');
$service->getServiceData();

Comment: I just created a service in my module and I didn't have to create a directory named Services. I also just searched all my codebase, and a directory named Services is nowhere to be found. What was your source?
Comment: @Kartagis that's just personal preference, as long as it's in the src folder and the paths are correct.
Answer: Use dependency injection
namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
class MyController extends ControllerBase implements ContainerInjectionInterface{
  protected $moduleDB;

  /**
   * Constructs a MyController object
   *
   *   The module handler service.
   */
  public function __construct($moduleDB) {
    $this->moduleDB = $moduleDB;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('mymodule.db')
    );
  }

  public function myroute() {
    $db = $this->moduleDB;
    return array('DEBUG');
  }
}

Answer: The answer from A Reddy was pretty much what I had set up, so I stripped the code further.  I had a line where I was calling:
$resp = new stdClass();

I removed it and it works.  I need to research why this doesn't work, but my original setup was correct.

How can I create a custom service?


Zabbix Discovery JSON values

Question: I have multiple Zabbix agents (Windows agent) and I need to check software license's details on each agent via a localhost JSON URL.
On each agent we can see license information on local web URL like this http://localhost/license/GetAllActiveLicenses
And this URL shows details in JSON format like this:
<code>{"GetAllActiveLicenseResult":
    {"Licenses":[
        {"LicenseName":"ImageServer","Enabled":true,"Remaining":"383 Day","StringExpireDate":"27-4-2020 00:00:00"},
        {"LicenseName":"WebReview","Enabled":true,"Remaining":"383 Day","StringExpireDate":"27-4-2020 00:00:00"},
        {"LicenseName":"Portal","Enabled":true,"Remaining":"774 Day","StringExpireDate":"23-5-2021 00:00:00"}
    ]}
}
</code>
I need to create a discovery rule to read each license field.
Comment: anyway this is my url output. are you have any recommendation ?
Comment: Maybe i can generate vali json data, But i need help to create discovery rule for this. Can you help me about this ?
Comment: Is this an actual output of the service? It's not valid JSON.
Comment: You don't state what's not working. I won't write the zabbix template/item for you, just wanted to point out that your posted information is no valid JSON array, so that might cause some trouble.
Comment: Looks like the only thing messing up the JSON is the missing doublequote before the second "Remaining".
Answer: This site is not geared towards writing solutions for you, but we can look at the possible approaches to solve this.

If you have Zabbix 4.2 or later, you can use pre-processing in LLD rules to turn this JSON into a Zabbix LLD JSON (after ensuring it is a valid JSON, see comments on the question).
If you have an older version, you might need a script to perform that conversion.

Zabbix Discovery JSON values


Causality in correlations between multiple variables

Question: Let's say I have 4 or 5 variables of interest which I measured for each of about 500 people. So, imagine a 500x5 matrix. Because of the nature of these variables, it is obvious that there must be (and indeed there is) a correlation between each possible pair of these variables, i.e. columns of the matrix. Is there any way of testing the causality? I used to think no, but then I heard something about Structural Equation Modelling, which to me sounded like a claim that there may be a way. But I really don't have a clue about this topic, and I don't know how and where to begin.
To make my question more concrete, I have a hypothesis that variables A and B determine variable C to a large degree, and variable D is largely determined by variable C, and this is why they are all correlated (because A depends on B as well). An alternative hypothesis might be that variables A, B, and C all determine variable D directly and that is why they are all correlated (because A and C depend on B as well). Obviously, none of the correlations are perfect, and there's always some statistical noise in each relationship. For clarity, I made a sketch of the two competing hypotheses (models) in my example.
Is there a pragmatic way (SEM or other) to show whether the data favours one of these models over the other? If yes, what's the best or most pragmatic way to implement this procedure, e.g. in R?
Comment: Excellent question! So glad you included a causal diagram - way too few causal questions on this site include a diagram. One fairly straightforward way you could determine if the model on the right is viable is to condition on $C,$ and see if causal information can still flow from $A$ and $B$ to $D.$ If you condition on $C,$ and the model on the right is correct, then $A$ and $B$ should not be able to causally influence $D.$
Answer: It depends what your research question is. I appreciate that you have a causal theory in mind, but it is always good to keep in mind that generally, at least with regression you need to decide what is the main exposure - and you will be typically wanting to estimate the total causal effect for that variable on the outcome. If you want to look at the whole picture and see all the direct and indirect estimates then a structural equation model (path diagram in this case) would be a better approach. However, regression is usually the approach most people choose:
In the model on the left, if $B$ is the main exposure then $A$ and $C$ are mediators and should not be conditioned on. However if $C$ is the main exposure then $B$ is a confounder of the path $C\rightarrow D$  and should be conditioned on. $A$ is a decendent of $B$ so this can be treated as a competing exposure and will increase the precision of the estimate for $B$. Similar logic applies if $A$ is the main exposure.
In the model on the right, if $C$ is the main exposure then you don't condition on either $A$ or $B$ because they are upstream. If A is the main exposure then $B$ confounds the $A\rightarrow C$ path  (and hence $A \rightarrow C \rightarrow D$ and) should be conditioned on. If $B$ is the main exposure then $A$ is a mediator and should not be conditioned on.
Take a look here for more on this.
So as to the main question:

Is there a pragmatic way (SEM or other) to show whether the data favours one of these models over the other? If yes, what's the best or most pragmatic way to implement this procedure, e.g. in R?

So bearing the above in mind, yes, you can consider C to be the main exposure. Let's do a simple simulation. First for the model on the left:
rm(list=ls())
N <- 100
B <- rnorm(N)
A <- B + rnorm(N)
C <- B + rnorm(N)
D <- A + B + C + rnorm(N)

as per the discussion above, in this case we condition on B and A:
summary(lm(D ~ C + B + A))

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  -0.1293     0.1210  -1.069    0.288
C             0.9208     0.1252   7.355 6.41e-11 ***
B             0.9741     0.2163   4.503 1.88e-05 ***
A             1.0682     0.1181   9.048 1.65e-14 ***

And we get signficant contributions from A and B, as expected.
Now, with the model on the right, A and B still have the same causal structure, so we just need to simular a new C and D:
C1 <- B + A + rnorm(N)
D1 <- C1 + rnorm(N)

Now, if we just wanted the causal effect of C1 on D1 we would not control for A and B, bue here we want to compare the same model we used above:
summary(lm(D1 ~ C1 + A + B))

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.031499   0.107806   0.292   0.7708
C1          0.851798   0.104286   8.168 1.25e-12 ***
A           0.005409   0.166517   0.032   0.9742
B           0.291614   0.169539   1.720   0.0886 .

...and now we find the contibutions from A and B drop out.
With an SEM approach:
library(lavaan)

dt1 <- data.frame(A,B,C,D)

m1.true <- '
  D ~ A + B + C
  C ~ A
  A ~ B'

m1.true.res <- sem(m1, dt1)
summary(m1.true.res)

we obtain:
Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)
  D ~
    A                 1.068    0.116    9.234    0.000
    B                 0.974    0.212    4.596    0.000
    C                 0.921    0.123    7.507    0.000
  C ~
    A                -0.080    0.094   -0.855    0.393
    B                 0.996    0.141    7.057    0.000

and all of this is consistent with the first model. But if we try to fit the second model we get:
m1.false <- '
  D ~ C
  C ~ A + B
  A ~ B'

m1.false.res <- sem(m1.false, dt1)
summary(m1.false.res)

Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)
  D ~
    C                 2.057    0.173   11.880    0.000
  C ~
    A                -0.080    0.094   -0.855    0.393
    B                 0.996    0.141    7.057    0.000
  A ~
    B                 1.139    0.098   11.622    0.000

and from this we can see the estimate for C ~ A is small and non significant which is not consistent with the 2nd model. We also see that the estimate for D ~ C is larger then we expected - but we would not know this if we hadn't simulated the data.
Comment: Does this answer your question ? If so, please consider marking it as accepted. Thanks !


Two network access

Question: I have the following conf:
A Win XP machine connected to a network having the following settings:
ip:      192.168.20.50
subnet:  255.255.255.0
gateway: 192.168.20.1

And I use this network to connect to an application for warehousing storage & logistics (a local network that has no internet access). I do not have access to change any settings on that network, I am just provided with a link and an application that specifically requires me to have those settings.
Now on the same computer I would like to have both access to this network and internet access. I can get internet access thru my router having the following settings:
ip:      192.168.1.2
subnet:  255.255.255.0
gateway: 192.168.1.1

So I have purchased an additional network card, and one is used for the local network, and the other for internet access.
My problem is that I cannot have parallel internet and access to the local application. Right now I disable one network adapter, and so on. But it is not practical.
Is there a way so that I can have both simultaneous access?
All help is appriciated
Answer: I'm assuming that the link to the warehousing software is on the 192.168.20.0/24 network?  If so, you don't need a default gateway on that network so remove the default gateway from the 192.168.20.50 network adapter.
It's likely that the metric is lower for the warehousing network's gateway so all your non-local traffic is going out through the 192.168.20.1 gateway, which won't work, as there's no Internet to route to.
If you can't change the network adapter settings, you'll have to run route commands to temporarily make changes to your routing table to direct non-local traffic (destination IPs that are not on either the 192.168.20.0/24 or 192.168.1.0/24) to the 192.168.1.1 default gateway.  Not entirely sure if the route command can be executing by users that do not have local administrator rights, however.
Answer: I found an article on the that explain your problem. You'll only have to edit your different interface with their own network. Windows should adapt his routing information.
Answer: If this is what you network looks like logically
_____
NIC  |--192.168.20.0 /24--Server
     |
PC   |
     |
NIC  |--192.168.1.0 /24--Router--Internet
------

then, as has been suggested, configure the 192.168.20.0 /24 interface without a default gateway and
configure the 192.168.1.0 /24 interface with a default gateway of 192.168.1.1.
Answer: Remove the default gateway 192.168.20.0/24 network. If there are other subnets within that network that you need to access then create routes for just those networks.
For example 192.168.30.0 255.255.255.0 nexthop 192.168.20.1

Two network access


another INSERT INTO overwrites existing data

Question: why does INSERT INTO overwrites existing rows in my table instead of adding them?
i got a simple query https://www.db-fiddle.com/f/pAVBB86LCZ8qUe5Jy4ZV6s/1
here is my log from the import:
191011 17:11:16     21 Query    SET NAMES 'utf8'
            21 Query    # ************************************************************
# Sequel Pro SQL dump
# Version 4541
#
# http://www.sequelpro.com/
# https://github.com/sequelpro/sequelpro
#
# Host: xxx (MySQL 5.6.19-67.0-log)
# Database: xxx
# Generation Time: xxx
# ************************************************************

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */
            21 Query    /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */
            21 Query    /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */
            21 Query    /*!40101 SET NAMES utf8 */
            21 Query    /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */
            21 Query    /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */
            21 Query    /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */
            21 Query    # Dump of table options
# ------------------------------------------------------------

DROP TABLE IF EXISTS `options`
            21 Query    /*!40101 SET @saved_cs_client     = @@character_set_client */
            21 Query    /*!40101 SET character_set_client = 'utf8mb4' */
            21 Query    CREATE TABLE `options` (
      `option_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
      `option_name` varchar(191) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT '',
      `option_value` longtext COLLATE utf8mb4_unicode_520_ci NOT NULL,
      `autoload` varchar(20) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT 'yes',
      PRIMARY KEY (`option_id`),
      UNIQUE KEY `option_name` (`option_name`)
    ) ENGINE=InnoDB AUTO_INCREMENT=69226 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci
            21 Query    /*!40101 SET character_set_client = @saved_cs_client */
            21 Query    --
    -- Backup data for table `options`
    --

    LOCK TABLES `options` WRITE
            21 Query    /*!40000 ALTER TABLE `options` DISABLE KEYS */
            21 Query    INSERT INTO `options` (`option_id`, `option_name`, `option_value`, `autoload`) VALUES
    (1, 'siteurl', 'https://www.example.de', 'yes')
            21 Query    INSERT INTO `options` (`option_id`, `option_name`, `option_value`, `autoload`) VALUES
    (2, 'home', 'https://www.example.de/home', 'yes')
            21 Query    /*!40000 ALTER TABLE `options` ENABLE KEYS */
            21 Query    UNLOCK TABLES
            21 Query    /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */
            21 Query    /*!40101 SET SQL_MODE=@OLD_SQL_MODE */
            21 Query    /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */
            21 Query    /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */
            21 Query    /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */
            21 Query    /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */
            21 Query    SET NAMES 'utf8mb4'
            21 Query    SET NAMES 'utf8'
            21 Query    SHOW DATABASES
            21 Query    SET NAMES 'utf8mb4'
            21 Query    SELECT DATABASE()
            21 Query    SET NAMES 'utf8'
            21 Query    SHOW /*!50002 FULL*/ TABLES
            21 Query    SELECT * FROM information_schema.routines WHERE routine_schema = 'test' ORDER BY routine_name
            21 Query    SET NAMES 'utf8mb4'
            21 Query    SET NAMES 'utf8'
            21 Query    SHOW TABLE STATUS LIKE 'options'
            21 Query    SHOW CREATE TABLE `options`
            21 Query    SET NAMES 'utf8mb4'
            22 Query    SHOW FULL COLUMNS FROM `options` FROM `test`
            22 Query    SELECT SPECIFIC_NAME, ROUTINE_TYPE, DTD_IDENTIFIER, IS_DETERMINISTIC, SQL_DATA_ACCESS, SECURITY_TYPE, DEFINER FROM `information_schema`.`ROUTINES` WHERE `ROUTINE_SCHEMA` = 'test'
            21 Query    SELECT * FROM `options` LIMIT 0,1000
191011 17:11:17     22 Query    SHOW FULL COLUMNS FROM `options` FROM `test`
            22 Query    SELECT SPECIFIC_NAME, ROUTINE_TYPE, DTD_IDENTIFIER, IS_DETERMINISTIC, SQL_DATA_ACCESS, SECURITY_TYPE, DEFINER FROM `information_schema`.`ROUTINES` WHERE `ROUTINE_SCHEMA` = 'test'

here we have my my.cnf file
# Default Homebrew MySQL server config
[mysqld]
# Only allow connections from localhost
bind-address = 127.0.0.1

Problem
As result i just have one row with the ID 2 in my created table after an import.
| option_id | option_name | option_value                | autoload |
| --------- | ----------- | --------------------------- | -------- |
| 2         | home        | https://www.example.de/home | yes      |

Comment: See the `DROP TABLE`?  It could have been suppressed when creating the dump.
Answer: it was the case that the socket file could not get connected

Error: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

That was the only thing which helped in the end: https://serverfault.com/a/459403/316405

Try using one of the following to see if you can connect without a
socket file
mysql -u root -p -h127.0.0.1
mysql -u root -p -h127.0.0.1 --protocol=tcp
If you can connect with one of these, the shutdown mysql like this
mysqladmin -u root -p -h127.0.0.1 --protocol=tcp shutdown


every time i run an program i get error: there is an error in your program: expected an indented bloak

Question:     #
import swampy
    from swampy.TurtleWorld import *
    world = TurtleWorld()
    bob = Turtle()
    def polygon(t, n, length):
    angle = 360.0 / n
    for i in range(n):
    fd(t, length)
    lt(t, angle)
    polygon(bob, 7, 70)

expected an indented bloak
every time i run program i get this error
Comment: This is because python cares about indentation unlike other languages. https://docs.python.org/2.0/ref/indentation.html
Comment: Ladies and Gentlemen, this human is about to quit Python because they don't like indentation. Thank you.
Comment: So, what's your question? It tells you that you need to indent; why don't you?
Comment: Are you expecting to be able to write Python without even having learnt the first thing about it? Start withe the link in@Zack Tarr's comment.
Comment: You need to left shift all your lines from line 2. There should not be any space . Read about python basics in some document and then start programs
Comment: as a beginner in python i have no hint about this error, so can u explain it...? and what was wrong in my program..? there is any missing statement
Answer: Try running this code:
import swampy
from swampy.TurtleWorld import *
world = TurtleWorld()
bob = Turtle()
def polygon(t, n, length):
    angle = 360.0 / n
    for i in range(n):
        fd(t, length)
        lt(t, angle)
polygon(bob, 7, 70)

Answer: You're asking so much and you're not understanding so I'll try here...
Python is a programming language that; unlike other languages actually cares about indentation inside the code. This means that all things you write must be indented correctly otherwise it will throw an error at you.
In your code you have indented parts where you don't need indentation and you have no indentation where you need it. Here is the correctly indented code:
import swampy
from swampy.TurtleWorld import *
world = TurtleWorld()
bob = Turtle()
def polygon(t, n, length):
    angle = 360.0 / n
    for i in range(n):
        fd(t, length)
        lt(t, angle)
polygon(bob, 7, 70)

Here it is clear that your base code has no indents but as soon as you define your function it gets indented to show that anything else indented in the same way is part of the function. This is the same with your for loop: Anything indented with your for loop is part of your for loop. That's why the function call isn't also looped.
To also add, indentation is considered because there are no calls to end the loop or end a function like VB.NET for example. In VB.NET, you have a start of the function and you can call the end.


DrupalQueue worker callback in separate file

Question: This is my first time using the DrupalQueue class, and I have two questions.
Does hook_cron_queue_info() HAVE to go in my mymodule.module file? I had some weird behavior before finally trying that, and it seems to be the culprit.
Can I put the queue worker callback in a separate file? I'm trying to keep all my queue functions in their own file, but it doesn't seem like I can do a file attribute like with a lot of other callback types; I just keep getting function undefined errors.
I tried...
function mymodule_cron_queue_info() {
  $queues['autopilot'] = array(
    'time' => 60,
    'worker callback' => '_mymodule_queue_handler',
    'file' => array('type' => 'inc', 'module' => 'mymodule', 'name' => 'includes/mymodule.queue'),
  );
  return $queues;
}

and
function mymodule_cron_queue_info() {
 module_load_include('module', 'mymodule', 'includes/mymodule.queue.inc');
  $queues['autopilot'] = array(
    'time' => 60,
    'worker callback' => '_mymodule_queue_handler',
  );
  return $queues;
}

but neither seem to work.
Answer: I was looking for this too. Turns out that it is not supported, judging from source in drupal_cron_run(). If your queue worker is sizable, one option is to create an intermediary worker callback in your .module file, then include and execute the mymodule.queue.inc worker from that function.


Laravel - Rota "insegura"

Question: Estou fazendo uma função para avaliar a uma transação entre um cliente (empresa) e o cliente dele (consumidor final). Aí é enviado um email/sms para o consumidor final com um link para ele avaliar a transação rapidamente pelo celular mesmo. Pensei em fazer o url cair direto na transação sem pedir login, mas para ter um mínimo de segurança, pensei em identificar essa transação no link pelo UUID ou HashMd5 de alguns dados dessa informação.
Quais seriam os prós e contras de cada solução?
Qual é o melhor pacote para UUID em laravel mesmo ou para php geral?
Answer: Uma solução que eu adoptei recentemente, para não ter tantos passos do lado do utilizador foi:

Produz o link para o consumidor final associado à transação e com timestamp
O cliente recebe um link com uma HASH. Usei SHA1 com email, um salt (palavra random fixa) e id único calculado no momento e guardado no perfil.
Executa um JOB paralelo que verifica todos os hash criados há mais de 1 dia. Ai pode criar um novo hash e relembrar ou simplesmente apagar.
Clica no link e valida o HASH

Para o salt com id tem a função uniqid() do php que o pode ajudar.

Laravel - Rota "insegura"


Does anyone know if this is notated properly, or how to properly notate this rhythm?

Question: I wrote this little melody/riff here:

And while it sounds correct, I'm not sure if it's notated properly, with the correct time signatures and all. Could both the first 3/4 bars and the 2/4 bar be condensed into a 4/4 somehow, or how does all that work?
Answer: It looks fine to me. It would also fit into 4/4 but the main difference is where the accents fall. Usually, you want the downbeat to be the strongest beat in the measure. Combining the first line into two 4/4 bars would mean that the second beat of your current 2/4 bar would become a downbeat. If that doesn't seem right to you, I would keep it the way you have it. It's hard to say for sure without hearing it in the context of a piece of music, but I think it is fine the way it is.
Also, I'm not familiar with ukulele so I might be mistaken, but it looks like you have a notation error on the last chord. Outside of a few wacky 20th century composers, sharps and flats carry through the measure -- you have a C# repeated in the score while it looks like the tab says to play a C natural. Sorry if I'm off-base here.
Comment: Hey! Thanks for the answer. Not sure if you're still there but wrote some drums that i think fit with it and slowed it down since it feels more cloudy that way.

[Here](https://gyazo.com/147f89ec1e5c02603103877b5af07570)

Now, are those drums in a specific time signature or i can just roll with that? (I mean i know i can just roll with that, but idk who knows i want it to be properly notated). Also dw about the actual key and all that since i wrote it on the tab first, but you are most likely correct since it switches key at the end.

[Here's](https://clyp.it/widoylvj) how it sounds
Comment: Your audio gave me a not found error (maybe I got to it too late), but those drums don't look like they're particularly strongly 4/4 to me, and if anything, I'm even more convinced that it's fine how you already have it.
Answer: Bar 7 is an F minor seventh triad, and should be written with flats (F-A♭-C-E♭). Most of the time, that A♯ note in bar 8 should be a B♭. Bar 8's G♯ should be an A♭, in my opinion. Same in Bar 9 to make the D diminished triad. Bar 10 has that weird chord. What is that? It's fine, but generally that would use D♭ as the root (D♭ diminished?)?. Rhythmwise, it looks good to me!
You said it switches key at the end. In the sheet music, this should probably be notated in the key signature. Sounds good!


If $\sum a_n$ and $\sum b_n$ are both convergent series with positive terms, then $\sum a_n b_n$ is convergent.

Question: The only approach I can think of is using the fact that $\{a_n\}$ and $\{b_n\}$ are both bounded as they are convergent then applying it to $\sum a_n b_n$ and saying it is bounded and increasing/dec and monotonic. However, I don't think we are allowed to prove using the Cauchy product and I'm unsure how to go about this approach (if it is even right)
Comment: hint: Boundness of $b_n$ with direct comparison test. It has nothing to do with Cauchy product.
Comment: lemma : if $|f(n+1)| \le |f(n)|$ and $\sum_n |a_n| < \infty$ then $\sum_n |f(n) a_n| < \infty$. now, given that the order of summation doesn't matter for absolutely convergent series, sort $b_n$ such that $b_{n+1} \le b_n$, and you are done
Answer:
Since $\sum_{n=1}^\infty b_n$ converges, there exists such $N$ that $\forall n\geq{N}\,\,b_n\leq{1}$.
Convergence of $\sum_{n=1}^\infty a_nb_n$ is equivalent to convergence of $\sum_{n=N}^\infty a_nb_n$.

Can you take it from here?
Comment: @Joemans The policy of this site is not to provide complete solutions to problems like this (thus discouraging any motivation to learn and think for yourself), but to give advice to encourage the learning process. The hints that I (and the other respondents) gave you are more than enough to finish the job.
Comment: @AndresMejia cheers! Funnily enough, I, on the other hand, like your hint more...
Comment: im confused, can you give me the answer
Comment: @Vossler I want to say +1 for sticking to your guns, but really I just like this hint better than mine.
Comment: @Vossler It looks nicer, but yours makes sense really of the *proof* for my hint (or at least gets you going in the right direction): http://math.stackexchange.com/questions/202467/cauchy-product-of-two-absolutely-convergent-series-is-absolutely-convergent-ru
Answer: hint: $\sum a_n b_n \leq (\sum a_n)(\sum b_n)$
since $a_n \geq 0$ and $b_n \geq 0$ for all $n \in \mathbb{N}$, and since both series converge, we have boundedness, so we are almost done!
Comment: thank you! I've seen you before: http://math.stackexchange.com/questions/1611560/why-are-all-k-cells-convex/1611571#1611571.
Answer: For all sufficiently large $n$ we have $0<b_n<1$ so for all sufficiently large $n$ we have $0<a_nb_n<a_n$ so $$\lim_{n\to \infty}\sup_{m\geq 0}|\sum_{j=0}^{j=m}a_{n+j}b_{n+j}|\leq \lim_{n\to \infty}\sup_{m\geq 0}|\sum_{j=0}^{j=m}a_n|=0.$$ With some appropriate changes from $<$ to $\leq$ we  see that this also holds if $a_n$ and $b_n$ are non-negative.


Send wrong values to the next activity in search

Question: i have problem with search, when user type something, listview will change, so the next activity will recive wrong values.
my code:
<code>    package com.example.finaltest;

import java.util.ArrayList;
import java.util.HashMap;

import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.text.TextWatcher;
import android.view.View;

public class Search extends ActionBarActivity {

    // List view
    private ListView lv;

    // Listview Adapter
    ArrayAdapter<String> adapter;

    // Search EditText
    EditText inputSearch;

    // ArrayList for Listview
    ArrayList<HashMap<String, String>> productList;

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

                // Listview Data
        String products[] = getResources().getStringArray(R.array.search);

        lv = (ListView) findViewById(R.id.list_view);
        inputSearch = (EditText) findViewById(R.id.inputSearch);

        // Adding items to listview
        adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.subject_name, products);
        lv.setAdapter(adapter);

        /**
         * Enabling Search Filter
         * */
        inputSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                // When user changed the Text

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub
                Search.this.adapter.getFilter().filter(arg0);
            }
        });

        // after click
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, final View view,
                int position, long id) {

                final String item = lv.getItemAtPosition(position).toString();
                int total_number = 50;
                for(int x = 1; x < total_number+1; x = x+1) {
                        String SubjectName = "subject_" + String.valueOf(x);
                        int resID = getResources().getIdentifier(SubjectName, "string", getPackageName());
                        String subject = getResources().getString(resID);

                        if(item.equals(subject)) {
                                String StringClass = "com.example.finaltest.Subject_" + String.valueOf(x);
                                Class<?> c = null;
                                if(StringClass != null) {
                                    try {
                                        c = Class.forName(StringClass);
                                    } catch (ClassNotFoundException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                }
                                Intent i = new Intent(getApplicationContext(), Show_Subjects.class);
                                String Subject_number = String.valueOf(position+1);
                                i.putExtra("subject_number", Subject_number);
                                startActivity(i);
                        }
                }

            }

          });
        }

        @Override
        public void onResume() {
            super.onResume();
            adapter.notifyDataSetChanged();
        }

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

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            switch (id) {
                case R.id.action_settings:
                    Intent delIntent = new Intent(Search.this, Settings.class);
                    Search.this.startActivity(delIntent);
                    return true;
                case R.id.action_favorites:
                    Intent delItemIntent = new Intent(Search.this, Favorites.class);
                    Search.this.startActivity(delItemIntent);
                    return true;
            }
            return id == R.id.action_settings || super.onOptionsItemSelected(item);
        }
    }
</code>
my string names are Subject_N , i want to send values of N to next activity(from item row number)
my language is persian ,also i have an other problem, search field only support english ! change language is Inactive
Comment: hi first of all x=x+1 and x++ meaning are same by convention we wrote the latter one mostly while using for loop moreover, if you can provide details like what is the current output and what is the expected one than it can be more easy  to help you
Comment: my string names are Subject_N , i want to send values of N to next activity
Comment: from item row number
Answer: <code>//outside the for loop
ArrayList<String> ArraySubject_number = new ArrayList<String>();
String Subject_number;

//initialize your arraylist inside the loop for each row
//use something like
//for each row
Subject_number = String.valueOf(position+1);
ArraySubject_number.add(Subject_number);

//outside for loop
Intent intent= new Intent(getApplicationContext(), Show_Subjects.class);
intent.putExtras("subject_number", ArraySubject_number);
</code>
then in your other activity use this code to access them
<code>ArrayList<String> ArraySubject_number = (ArrayList<String>) getIntent().getSerializableExtra("subject_number");
</code>
Comment: can you give me full code pls?! i don`t have problem with get values in next activity, just give full search code pls. tnx
Comment: i can make one for you,if you can give me some details like what you want the code to do  terms of functionality
Comment: i want to show search in listview, my list view must show my string with name Subject_N in string.xml, and send position(item row) befor changing after search to next activity. for ex. Subject_6 is In the sixth row at the first (befor user do search), but after search it will be In the first row, i need to send i=6 to next activity. i have 50strings, and i use a class with name Globals to define subject_total_number(50)
Comment: also i can don`t show the listview, just search in my string with name Subject_N, and send N values to next activity


Error: Node Sass does not yet support your current environment: Linux 64-bit with Unsupported runtime (72)

Question: Error: Node Sass does not yet support your current environment: Linux 64-bit with Unsupported runtime (72)
I faced this issue when I used the latest version of node.js i.e, 12.6.0 and npm version 6.9.0.
which version of node-sass is compatible with above mentioned node and npm versions.
node-sass version: 4.5.3
Answer: Use the following command:
npm rebuild node-sass

You likely copied the node_modules from a Windows or OSX system. Rebuilding it builds the right version for your system.
Comment: This failed miserably - so many errors!
gyp ERR! stack     at ChildProcess.emit (events.js:209:13)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:272:12)
gyp ERR! System Linux 4.19.0-6-amd64
gyp ERR! command "/usr/bin/node" "/home/sobs/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd /home/sobs/node_modules/node-sass
gyp ERR! node -v v12.10.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
Build failed with error code: 1
Comment: @muztheaxe - Every error in Node looks like it failed miserably, so much output and red `ERR`. Though, this error shows not much. Is it an excerpt?
Comment: I had to get some help to fix this.  This was a fresh install of everything, however it was Debian 9 rather than Debian 10.  We started again (from a fresh install) with Debian 10 and this then worked.
Answer: We list this at the top of the README https://github.com/sass/node-sass#supported-nodejs-versions-vary-by-release-please-consult-the-releases-page-below-is-a-quick-guide-for-minimium-support
For Node 12, you need node-sass 4.12
Answer: Run this command to solve this issue.
npm install --save-dev node-sass