What does it mean when a Data Matrix has full rank?

Question: Suppose I have a matrix of observations $X \in \mathbb{R}^{n \times p}$. So I have $n$ observations that each have dimension $p$. Lets suppose also that we have more data points than dimensions to them, so $n > p$. Is there an intuitive interpretation for the matrix to have full rank?
Comment: Another interpretation: if X has full rank, then the least squares loss function is strictly convex and looks like a bowl. If X has rank that is one lower, the loss function looks like a taco. Each rank deficiency is another independent direction where the loss function is flat.
Comment: Additional remark, rank-deficiency and regularisation are closely related concepts, that's why rank is such an important concept.
Comment: Given the model is $Y = X\beta + \varepsilon$, $\mathrm{rank}(X) = p$ is a necessary and sufficient condition for the parameter $\beta$ is *estimable*, or the model is *identifiable*. If $\mathrm{rank}(X) < p$, then there would be infinitely many $\hat{\beta}$ can be served as the least-square estimate, which is not desirable from the (classical) inference perspective.
Comment: @bjb568 I understand that the loss function SHOULD become non-strictly-convex as you mentioned when the LS problem (which is always convex, either strictly when X is full rank or non-strictly in case of rank deficiency) yields infinite solutions. I understand this from an optimization point of view, but can you explain logically / mathematically why the loss function is not strictly convex when X is rank deficient?
Answer: If the matrix has full rank, i.e. $rank(M) = p$ and $n > p$, the p variables are linearly independent and therefore there is no redundancy in the data. If instead the $rank(M) < p$ some columns can be recreated by linearly combining the others. In this latter case, you couldn't use all the columns of M as explanatory variables in a linear model (you could of course but it wouldn't make sense).
For example, in R:
library(Matrix)
set.seed(1234)
options(digits= 3)

M <- matrix(data= rnorm(n= 15), ncol= 3)
M
       [,1]   [,2]    [,3]
[1,] -1.207  0.506 -0.4772
[2,]  0.277 -0.575 -0.9984
[3,]  1.084 -0.547 -0.7763
[4,] -2.346 -0.564  0.0645
[5,]  0.429 -0.890  0.9595

rankMatrix(M) # -> rank 3

# 4th column is a linear combination of column 1 and 2 - there is redundancy
M2 <- cbind(M, M[,1] + M[,2])
M2
       [,1]   [,2]    [,3]   [,4]
[1,] -1.207  0.506 -0.4772 -0.701
[2,]  0.277 -0.575 -0.9984 -0.297
[3,]  1.084 -0.547 -0.7763  0.538
[4,] -2.346 -0.564  0.0645 -2.910
[5,]  0.429 -0.890  0.9595 -0.461

rankMatrix(M2) # still rank 3 even if you have four columns

Try to fit a linear model on y using M or M2 as explanatory variables.

# A dummy response variable
y <- M[,1] + rnorm(n= nrow(M))

# Ok, the coefficients of all the  variables in M can be estimated
lm(y ~ M)

# Coefficients:
# (Intercept)           M1           M2           M3
#     -0.6786       1.0682      -0.0178      -0.7026

# Here the coefficient of 4th variable cannot be estimated no
# matter how many observations (rows) you have
lm(y ~ M2)

# Coefficients:
# (Intercept)          M21          M22          M23          M24
#     -0.6786       1.0682      -0.0178      -0.7026           NA

I guess that a geometric interpretation of the linear model example is that the response matrix M
defines the space where the vector of coefficient can be fitted. More variables in M means more
dimensions available. However, if a variable in M is a linear combination of other
variables, like in M2, there is no real increase in additional dimensions (or space available)

As noted by @SingleMalt, a matrix can be full rank and still be redundant for practical purposes. For example, if you add some minimal jitter to column 4 of M2 you obtain full rank (4). You could use M2 as predictor in a linear model and estimate all 4 coefficients but the results would be very unstable and unreliable. As shown here the estimated coefficient have "gone crazy":
# Add some minimal jitter to column 4
M2[,4] <- M2[,4] + rnorm(n= nrow(M2), sd= 0.0001)

rankMatrix(M2) # <- 4 Full rank

lm(y ~ M2)

# Coefficients:
# (Intercept)          M21          M22          M23          M24
#      -0.267    36603.840    36604.443        1.318   -36603.504

Returning to the geometric interpretation, this means that column 4 does add a fourth dimension available to the vector of coefficients. But the increase in space is so small that some dimensions almost perfectly overlap and cannot be estimated with any reliable accuracy.

That's my interpretation - hope it helps...
Comment: This is a clear answer. The Matrix package documentation says of function rankMatrix: "Compute 'the' matrix rank, a well-defined functional in theory, somewhat ambiguous in practice". Thus a small amount of jitter when creating M2 would generally yield a rank of four (although I have not verified this in terms of this particular R function).
Comment: @SingleMalt I think you are right - I edited my answer to include this practical consideration.
Answer: I want to connect the concept of identifiability with the rank of the design matrix in linear regression, as well as take a more linear algebraic look at the problem, since you mention you have a math background.
Some parameter in our regression model is called identifiable if it's possible for us to even guess what it is. To contrast this with the typical case, we'll never know the exact value of any parameter if there's any randomness in the process, but the least squares estimates can give a good guess if there's enough good data. But when a parameter is not identified, it's absolutely impossible to have any idea what it is: no matter what value the parameter is set to, the data that's coming out will look the exact same. And since we use the data to guess what the parameters are, if there's no influence on the data from a certain parameter, the data are not providing us any information about it.
A good example is the situation where we have categorical factors, for instance:
we want to compare medical treatment Treatment A to Treatment B to Treatment C:

We've also compared the patient's weights. The treatment outcomes ("y's") are not shown; they don't play into identifiability at all.
Here's the problem: Treatment A and C were always given to the same people. We can tell because their columns have exactly the same data in them. Inuitively, we already know we're in trouble: if those patients recover more than usual, it could be the case that Treatment A is doing all the work, and Treatment C is inert. Or maybe Treatment A is actually harmfull, but Treatment C is super beneficial and makes up for it. There are infinite possibilities, and we can't be sure what's going on with Treatment A and C individually.
A more subtle version of this is the general unidentifiable case. To see the general case, let's now bring rank into the picture. A key consequence of Rank from linear algebra is that a matrix with less than full rank turns some set of vectors that aren't zero into the zero vector: $\mathbf{X}\mathbf{b} =  \mathbf{0}$ (these vectors are said to belong to the kernel or nullspace of $\mathbf{x}$).
In the case of the matrix above, one such vector is $c(1,0,-1,0)$:

This is the mathematical interpretation of our above discussion: we can't know how much better Treatment A is than Treatment C, since a 1 in the first entry and a -1 in the third entry is going to compute the difference between the first and third rows upon matrix multiplication.
But we haven't talked about any of our regression coefficients: we don't have a coefficient on what the different is between Treatments A and C. We have one individually on Treatments A and C. So why do we care if the difference is not identified? The problem is that we haven't actually cleared anything from unidentifiability yet.
This is because of the projection theorem from linear algebra, which states that any vector $\mathbf{v}$ in a linear space $\mathcal{L}$ can be decomposed along some subspace $\mathcal{S}$ as $\mathbf{v} = \mathbf{v}_{\mathcal{S}} + \mathbf{v}_{\mathcal{S}^\perp}$, where $\mathbf{v}_{\mathcal{S}} \in \mathcal{S}$ and $\mathbf{v}_{\mathcal{S}^\perp}$ is orthogonal to that space. So thinking of input parameters as unit vectors, they can be decomposed as $\mathbf{e}_i = \mathbf{v}_{\mathcal{N}} + \mathbf{v}_{\mathcal{N}^\perp} $, where $\mathbf{v}_{\mathcal{N}}$ is in the nullspace of $\mathbf{X}$ and $\mathbf{v}_{\mathcal{N}^\perp}$ is orthogonal to that.
With this decomposition, we see that it's not just $c(1,0,-1,0)$ that we can't estimate: whenever the component $\mathbf{v}_{\mathcal{N}}$ is not the zero vector, it can't be estimated. On the contrary, any vector which is orthogonal to the vector $c(1,0,-1,0)$, or in general, orthogonal to the nullspace, will be identifiable. Recall from Gil Strang's fundamental theorem of linear algebra that the subspace orthogonal to matrix's kernel is that same matrix's rowspace. Thus the rowspace of our design matrix can still be estimated even if our matrix is less than full rank. Intuitively, we should have been able to estimate the effect of "Treatment A and Treatment B", and we can verify that their sum is indeed in the rowspace and hence identifiable.
TLDR: If your matrix is less than full rank, it will send some vector to zero. This means that changing regression coefficients along that direction results in no change to the data, and we can't learn anything about what that linear combination of our parameters are, and thus what the parameters that contributed are themselves.
Answer: Suppose you have a $10×10$ matrix $X$, and $rank(X) = 1$, which is stored somewhere on your memory disk. For some reason, your memory disk was damaged, and so was the matrix. Some rows remained intact, whereas in other rows several digits were lost. The question is, how many full rows do you need to know in order to restore the entire matrix?
The minimum number of rows you need is equal to the rank of the matrix. This is due to the fact that rank represents the number of linearly independent rows. All other rows can be obtained by multiplying that one row by an arbitrary number.
E.g., if our damaged matrix looks like this:
$\begin{bmatrix}
1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\
 & 6 & & 12 & & & & & & \\
 & & & & 20 & 24 & & & & \\
7 & & & & & & & & & 70 \\
& & & & \dots\ & & & & \\
\end{bmatrix}$
Then, we already know that our matrix is:
$\begin{bmatrix}
1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\
3 & 6 & 9 & 12 & 15 & 18 & 21 & 24 & 27 & 30 \\
4 & 8 & 12 & 16 & 20 & 24 & 28 & 32 & 36 & 40 \\
7 & 14 & 21 & 28 & 35 & 42 & 49 & 56 & 63 & 70 \\
& & & & \dots\ & & & & \\
\end{bmatrix}$
Were $rank(X) = 2$, that woudn't work because we would need at least two full rows. Finally, if matrix $X$ had full rank (i.e. $rank(X) = 10$), we would be in a world of trouble. Since all rows are linearly independent, not a single lost digit could be restored.
This is one way to look at the concept of matrix rank.
Comment: Thank you, that is quite a good answer for what it generally means for a matrix to not have full rank. I have a mathematics background so this interpretation I was aware of. My question was more in regards to what it tells me about the observations when I have a data matrix for modelling specifically


relay email using postfix

Question: I'm in over my head, and became in charge of a Linux server that runs a tomcat application.  The application currently is configured to send email directly to a postfix relay server.  I was asked if it would be possible to set up Postfix locally on the server and have the app send mail to it, and then have Postfix deliver to the mail relay server.  I said "sure!", but now I'm not sure how to do this.  Can someone point me in the right direction?  I'm not sure what the terminology I need to search for is.  If the mail relay server is down, will the local Postfix instance queue the mail until it can be delivered?
thanks for the help.
Answer: what you need is to specify the relayhost parameter in main.cf (usually /etc/postmaster/main.cf):
relayhost = [relayserver]
after editing the file, reload postfix:
<code># postfix reload [enter]
</code>

relay email using postfix


Why is $L(z)=\phi(z) - z \left(1 - \Phi(z)\right) \ge 0$? Why is it (sorta) linear?

Question: In this question, OP is interested, apparently, in a loss function with the ambiguous name "normal loss function" which is defined as
$$
L(z) =\phi(z) - z \left(1 - \Phi(z)\right).
$$
Based on this quick plot, the function is nonnegative and essentially linear for sufficiently small values $z$.

It's not obvious to me why this must be non-negative, nor is it obvious why it must be essentially linear for small $z$. Is there an intuitive explanation for this behavior?
Comment: This result is contained in the extensive results reported by Cardinal at https://stats.stackexchange.com/questions/7200/evaluate-definite-interval-of-normal-distribution/7206#7206.
Answer: Since on the interval $x \in [z, \infty)$ it is clear that $x \ge z,$ use the fact that $\phi^\prime(x) = -x \phi(x)$ to conclude
$$\phi(z) = \int_z^\infty (-\phi^\prime(x))dx = \int_{z}^\infty x \phi(x) dx \ge z \int_z^\infty \phi(x) dx = z(1-\Phi(z)),$$
QED.

Concerning the second question, observe that $$L^\prime(z) = \phi^\prime(z) + z\phi(z) - (1-\Phi(z)) = 1-\Phi(z),$$ yielding $L$ as an integral $$L(z)=\int_{\infty}^z (1-\Phi(x))dx \gt 0,$$ which provides another solution to the first question.  Since $1-\Phi(z) \approx 1$ for $z\ll 0,$ $L$ approaches an asymptote with slope $-1$ as $z\to-\infty.$


SharePoint list view created from multiple lists on the same site

Question: I want to create a SharePoint list/ view comprimised of multiple columns from different lists on the same site.
Do I have to create a separate list for this or can I simply create a view? The reason why I am doing this is to be able to use reporting webparts that require a single list as input.
Answer: You can use the Data view webpart available in SPD to join multiple list data in a single view or you create a separate list


Error when passing data between views

Question:
Possible Duplicate:
How to pass data to detail view after being selected in a table view?

I'm using a plist (array of dictionaries) to populate a tableview. Now, when a cell i pressed, I want to pass the reprecented dictionary to the detail view with a segue. It's working properly to fill the tableview, but how do I send the same value to the detail view? This is my try:
#import "WinesViewController.h"
#import "WineObject.h"
#import "WineCell.h"
#import "WinesDetailViewController.h"

@interface WinesViewController ()

@end

@implementation WinesViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (void)viewWillAppear:(BOOL)animated {
    wine = [[WineObject alloc] initWithLibraryName:@"Wine"];
    self.title = @"Vinene";
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [wine libraryCount];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"wineCell";

    WineCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Configure the cell...

    cell.nameLabel.text = [[wine libraryItemAtIndex:indexPath.row] valueForKey:@"Name"];
    cell.districtLabel.text = [[wine libraryItemAtIndex:indexPath.row] valueForKey:@"District"];
    cell.countryLabel.text = [[wine libraryItemAtIndex:indexPath.row] valueForKey:@"Country"];
    cell.bottleImageView.image = [UIImage imageNamed:[[wine libraryItemAtIndex:indexPath.row] valueForKey:@"Image"]];
    cell.flagImageView.image = [UIImage imageNamed:[[wine libraryItemAtIndex:indexPath.row] valueForKey:@"Flag"]];
    cell.fyldeImageView.image = [UIImage imageNamed:[[wine libraryItemAtIndex:indexPath.row] valueForKey:@"Fylde"]];
    cell.friskhetImageView.image = [UIImage imageNamed:[[wine libraryItemAtIndex:indexPath.row] valueForKey:@"Friskhet"]];
    cell.garvesyreImageView.image = [UIImage imageNamed:[[wine libraryItemAtIndex:indexPath.row] valueForKey:@"Garvesyre"]];

    return cell;
}

#pragma mark - Table view delegate

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([[segue identifier] isEqualToString:@"DetailSegue"]) {

        NSIndexPath *selectedRowIndex = [self.tableView indexPathForSelectedRow];
        WinesDetailViewController *winesdetailViewController = [segue destinationViewController];
        //Here comes the error line:
        winesdetailViewController.winedetailName = [wine objectAtIndex:indexPath.row] valueForKey:@"Name"];
    }
}

I get one error for:
winesdetailViewController.winedetailName = [wine objectAtIndex:indexPath.row] valueForKey:@"Name"];

Use of undeclaired identifier: indexPath. did you mean NSIndexPath? I think I've missed something important here..
Answer: Instead of indexPath.row (which doesn't exist in this function like it does in your tableView:cellForRowAtIndexPath: function where it is passed as an argument) use selectedRowIndex like this:
 winesdetailViewController.winedetailName = [wine objectAtIndex:selectedRowIndex.row] valueForKey:@"Name"];

Or, even better yet, change your detail view controller to just accept the whole dictionary, pass the dictionary, and let it set its' own values:
 winesdetailViewController.winedetail = [wine objectAtIndex:selectedRowIndex.row];

Answer: The error is correct, there is no variable indexPath defined there. However, just a couple lines above that line you define selectedRowIndex which probably has the value that you're after.

Error when passing data between views


do older ears with diminished hearing have a problem distinguishing intonation on guitar strings

Question: I have changed strings, corrected neck relief etc, on my Les Paul and tuned and checked intonation using a Peterson strobe tuner, but when I play I'm hearing strings out of tune and intonation problems.  Also I play with 10's with a wound 3rd string.  Any thoughts on what's causing this?
Edit:
I have had a fair amount of experience in setting up guitars and on this one I checked the frets with two separate straight edges along with a notched straight edge to check the neck separately. I checked the intonation open, 1st fret, 12th fret and a harmonic on the 12th fret. All recordings sound in tune. Only certain strings appear to be out (they mostly sound flat to me) usually it's the d and g strings that sound out of tune. When playing I have noticed that if I adjust one then it will have an effect on how the other sounds.
Thanks so much for your thoughts.
Comment: Exactly how did you check intonation? Having the best tool helps, but needs utilising properly. I have an excellent scalpel, but my brain surgery is still a little scrappy!
Comment: Can you be more specific than "strings out of tune" and "intonation problems"? Is it all strings, fretted or open? Or just fretted strings? Or just some fretted notes? And what sort of intonation problems. There's not enough info at the moment to know whether it's your guitar or your ears...
Answer: This article seems to suggest that losing intonation with age does indeed happen. However I have never witnessed what you are describing even though many of the musicians I know are quite old (over age 60). I recommend you go to a doctor for a hearing exam just to be sure. Regardless of how often something happens in general your case is unique.
I am assuming that if you went as far as to use a strobe tuner to test intonation that you checked the intonation of individual frets. Have you tried listening to different guitars? Do your favorite recordings sound in tune? IF they do then the problem might indeed rest in your guitar rather than you.
Update:
If recordings sounds like they are in tune then it probably isn't your ears that have the problem but rather the guitar(s) you are working on.
I'm no luthier, but on the stringed instruments tuning stings usually affects the tuning of other strings. The tuning process is done repeatedly until all of the strings are more or less in tune. Even if you are experienced it probably won't hurt to take your guitars to a shop. While you're there have a go on other instruments in the store and have them check yours out.
I'm glad recordings still sounds in tune to you. That suggests that your hearing probably isn't what's at fault in this case.
Answer: If you, at almost any age, can hear that something's out of tune, for whatever reason, then most likely it is out of tune. Listening to anything else, I would imagine you feel it's in tune, especially recorded stuff.
So, there's probably nothing wrong with old ears. Certainly hope not - mine aren't as young as they used to be, but I wish I'd been sensibly wearing earplugs far more!
I suspect the accuracy of the intonation process, with due respect. Or the fact that something has gone awry with the guitar. New strings can take a while to settle in, changes in temperature and humidity will take their toll on tuning also.
Answer: Adding to the answers given before I'd like to mention the following:
From the theoretical point of view Guitar tuning is much more complicated than piano tuning. Or in other words: It is more a compromise than tuning a keyboard instrument, as you have to consider each fret separately and simultaniously for all strings. This may be the reason that the 12-tone equal tempered tuning (short 12-tet) has been first reported in the wester music tradition as the solution to the problem of lute division.
As a secound point is related to just intonation. You can express the sound of one string by different frequencies. As a good approximation you can consider the inner ear as a gammatone filter bank with 3000 to 4000 frequencies, a Fourier series is often resonable, too. A just fifth/fourth as the difference between g and d is not very robust against mistuning. According to some authors (e.g. Martin Vogel) the just noticable difference of two sine tones (about 1-2ct) is also noticable in the timbre of two strings tuned a fifth apart when played together. This explains why the two strings interact with each other.
The third thing is related to the aging process you are referring to: The natural learning curve is not linear. At the beginning you are lerning to understand the problem. This is the first noticable phase of learning. Later on you learn from variation. This means that you do not notice any progress. I assume that you try to avoid variation in the tuning result. So collectiong variation might be difficult and a long process. After you collected enough variation there may be the point where you suddenly reach a new quality of your task – in this case the listening to the tuning of your guitar.
Finally I'd like come back to the physical behaviour of your guitar. Preferably the corpus has no undamped resonance frequency. I own a guitar which has a relatively strong weakly damped resonance frequency, which makes it hard to tune a particular string. Depending on your hearnig skills you may even notice the difference in the degree of different partials of your guitar strings. Sometimes these can be caused by the strings themselves (e.g. nylon strings may loose homogeneity over time).
As a conclusion your description sounds to me as if you somehow got another instrument, your instrument needs some maintenance (e.g. new strings), or you improved your hearings skills over time. It might be also a combination of these things.


reading mbox files using python and batch

Question: Hello I have the following two scripts where a batch script calls a python script that prints the last email in a mbox file.But an error pops up in command window

name msg is not defined

How can I initialize an mbox variable to execute my script? Below the two scripts i wrote
import mailbox
import sys
for msg in mailbox.mbox(sys.argv[1]):
    pass

print(msg)

And here is my batch script
@echo off
python get_last_mail.py C:\\Users\\hmk\Desktop\\emails-enron.mbox
pause

I really need your help.Thank you
Comment: Well, `msg` exists only in the scope of the `for` loop, but `print(msg)` is not placed in the loop body...
Comment: Your goal is just to print the last email? Or to print all emails?
Comment: the last email.
Answer: I could figure it out. The error resides in the way to define the argument
The new batch script is the following
@echo off
set var= "C:\Users\hmk\Desktop\emails-enron.mbox"
python "get_last_mail.py" %var% >last
pause


Recreate shape as in xml file by using code and set width programmatically

Question: I already have shape code and now I need to draw the same programmatically and set its width according to the length of texts in an array. I am not able to reproduce the same using path data.
This is the code:
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:viewportWidth="2778"
    android:viewportHeight="1250"
    android:width="250.0002dp"
    android:height="112.5dp">
    <path
        android:pathData="M2764 1250L0 1250 0 0l2256 0 4 4 513 468 4 4 0 774 -14 0 0 0zm-2737 -27l2723 0 0 -736L2245 26 27 26 27 1222Z"
        android:fillColor="#FF6E00" />
</vector>

Output shape should be this
Please help me on this..
Answer: Method 1: By Creating custom shape:
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.shapes.Shape;

public class RectangleCutCorner extends Shape {
    private int backgroundColor  = Color.BLACK;
    private float strokeWidth = 1.0f;
    private static final float CORNER = 35.0f;

    private final Paint border = new Paint();
    private final Path  path;

    public RectangleCutCorner() {
        path = new Path();
        border.setColor(backgroundColor);
        border.setStyle(Paint.Style.FILL);
        border.setStrokeWidth(strokeWidth);
        border.setAntiAlias(true);
        border.setDither(true);
        border.setStrokeJoin(Paint.Join.ROUND);
        border.setStrokeCap(Paint.Cap.ROUND);
    }

    //for setting stroke width programmatically
    public void setStrokeWidthToLayout(float strokeWidth){
        this.strokeWidth = strokeWidth;
        border.setStrokeWidth(strokeWidth);
    }

    //for setting background/stroke color programmatically
    public void setBackgroundColor(int backgroundColor){
        this.backgroundColor = backgroundColor;
        border.setColor(backgroundColor);
    }

    //for setting background filled or not programmatically
    public void setBackgroundFill(boolean isFilled){
      if(isFilled){
          border.setStyle(Paint.Style.FILL);
      }else{
          border.setStyle(Paint.Style.STROKE);
      }
    }

    @Override
    protected void onResize(float width, float height) {
        super.onResize(width, height);

        float dx = strokeWidth/2.0f;
        float dy = strokeWidth/2.0f;
        float x  = dx;
        float y  = dy;
        float w  = width  - dx;
        float h  = height - dy;
        path.reset();
        path.moveTo(x + CORNER,y);
        path.lineTo(w - CORNER,y);
        path.lineTo(w,y + CORNER);
        path.lineTo(w, h);
        path.lineTo(x + CORNER,h);
        path.lineTo(dx,h);
        path.lineTo(dx,y);
        path.close();
    }

    @Override
    public void draw(Canvas canvas, Paint paint) {
        // TODO Auto-generated method stub
        canvas.drawPath(path,border);
    }
}

How to use this programmatically:
    RectangleCutCorner rectangleCutCorner = new RectangleCutCorner();
    // set color
    rectangleCutCorner.setBackgroundColor(R.color.black);
    //set fill background (true/false)
    rectangleCutCorner.setBackgroundFill(false);
    // set stroke width
    rectangleCutCorner.setStrokeWidthToLayout(2.5f);
    // set background to view
    view.setBackground(new ShapeDrawable(rectangleCutCorner));

Output for above code is:

Method 2: By Using Material Shape Drawable:
Add this dependency into build.gradle(app) file:
implementation 'com.google.android.material:material:1.3.0'
How to use:
    ShapeAppearanceModel shapeAppearanceModel = new ShapeAppearanceModel()
            .toBuilder()
            .setTopRightCorner(CornerFamily.CUT, 20)
            .build();
    MaterialShapeDrawable shapeDrawable = new MaterialShapeDrawable(shapeAppearanceModel);
    int[][] states = new int[][] {
            new int[] { android.R.attr.state_enabled},
    };
    int[] colors = new int[] {
            Color.WHITE,
    };
    ColorStateList myList = new ColorStateList(states, colors);
    // set background to drawable
    shapeDrawable.setFillColor(myList);
    // set stroke and to view
    shapeDrawable.setStroke(1.5f, Color.BLACK);
    // set background to view
    ViewCompat.setBackground(tvUrl, shapeDrawable);

Output for above code is:
Comment: Thanks a lot! @Android Geek the solution was perfect.. is it possible to add width and height to this shape while creating? Because i need to calculate the length of the text and measure it in dp and assign width and height to shape in dp..
Comment: i need 15 reputation i guess to mark answer as correct.. @Android Geek Thanks a lot!
Comment: the first one is working great.. when i tried the second solution, it works fine in Android 10, then i tried the same in Android Marshmallow, the color was different.. For both transparent and light brown color(#FF6E00), the background was only black.. so i am going with first solution.. Thanks again @android-geek


Como fazer uma soma em Lambda com lógica recursiva usando sucessor e antecessor?

Question: Estou tentando montar uma Soma com lógica de recursividade usando apenas sucessor e antecessor em Lambda. Mas não estão conseguindo...
No caso:
suc = λx.x+1

ant = λx.x-1

Fiz já algo do tipo:
{λx.[λy.(x-1)+(y+1)][λy.(x-1)+(y+1)]}

Mas não sei se isso está certo... Não tem código de erro, pois eu não cheguei a implementar, estou querendo montar a logica.
Comment: Olá bem vindo ao StackOverflow. Amigo recomendo que leia o Tour do Stack Overflow, irá te ajudar a ser mais claro em suas perguntas. http://pt.stackoverflow.com/tour
Comment: Sua pergunta é sobre python ou lambda-calculus?
Comment: Escrever funções lambda recursivas é um pouco difícil, já que as funções não tem nome. Você vai precisar usar um operador de ponto fixo ou trocar a sua definição de números (se vc usar numerais de church ao invés de inteiros de Python fica mais fázil fazer a soma)
Comment: Tanto faz na verdade, pois é possível se fazer em Python.
Comment: Teve algum código de erro? Ou o resultado não foi o esperado?
Comment: Não, pois eu não cheguei a implementar eu estou querendo montar a logica.
Answer: Conforme a resposta no SO em inglês:
https://stackoverflow.com/questions/481692/can-a-lambda-function-call-itself-recursively-in-python
É possível montar uma soma lógica (ou outros algoritmos) com recursividade utilizando funções lambda em Python.
Um ponto importante sobre funções recursivas é que, obrigatóriamente, elas devem ter uma condição de parada, ou seja, em algum momento, o algoritmo deve retornar para evitar um looping infinito (referências no final da resposta).
Conforme a resposta acima, existem várias formas para criar essas expressões.
Os exemplos abaixo, efetuam (recursivamente) o cálculo:
x=10
soma = 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 55

Exemplos:
a) Atribuir um nome à função lambda criada (mais fácil):
soma = lambda x: 1 if x == 1 else x+soma(x-1)

Resultado:
>>> soma = lambda x: 1 if x == 1 else x+soma(x-1)
>>> soma(10)
55

A variável soma recebe o valor de uma função anônima (lambda)
e retorna caso o parâmetro da função seja 1 (condição de parada).
Caso o valor seja maior que 1, ela soma o valor do parâmetro x
ao resultado de uma chamada recursiva com parâmetro x-1,
feita através da referência armazenada na variável soma.

b) Utilizando uma função auxiliar:
def soma(f, *p, **kw):
    return f(f, *p, **kw)

soma( (lambda fr, x: 1 if x == 1 else x + fr(fr, x-1)), 10 )

Resultado:
>>> soma( (lambda fr, x: 1 if x == 1 else x + fr(fr, x-1)), 10 )
55

Este tipo de função é conhecido como Combinador de ponto fixo (ver referências) ou Y-combinator de Lemmy.
A função auxiliar soma recebe 3 parâmetros:

f - irá receber uma função anônima

*p - recebe uma lista de parâmetros posicionais

**kw - recebe uma lista de parâmetros nomeados

consultar: Keyword Arguments - Documentação Python  (em inglês)
Ao chamar a função soma, o primeiro parâmetro informado é uma função lambda que recebe 2 parâmetros: a própria função (em fr) e o valor 10.
A chamada recursiva ocorre em: x + fr(fr, x-1) e, posteriormente em return f(f, *p, **kw).
A condição de parada é a mesma que a anterior.

c) Apenas com funções anônimas (mais complexo):
(lambda f1: lambda v1: f1(f1, v1))(lambda f, x: 1 if x == 1 else x+f(f, x-1))(10)

Resultado:
>>> (lambda f1: lambda v1: f1(f1, v1))(lambda f, x: 1 if x == 1 else x+f(f, x-1))(10)
55

Esta função também é uma variação do Y-combinator de Lemmy.
Dividindo a linha do comando em 3 partes:
1) A primeira parte equivale à função auxiliar do exemplo (b) acima.
O parâmetro f1 recebe a função do item 2 (abaixo) e o parâmetro v1 irá receber o valor 10, a partir da chamada recursiva f1(f1, v1):
(lambda f1: lambda v1: f1(f1, v1))

2) A segunda parte é a função que executa o cálculo:
(lambda f, x: 1 if x == 1 else x+f(f, x-1))

3) A terceira parte é valor 10, que será enviado ao parâmetro v1, e, posteriormente a x:
(10)

Para facilitar o entendimento deste exemplo, o comando é equivalente ao exemplo (a) da seguinte forma:
f1 = lambda f, x: 1 if x == 1 else x+f(f, x-1)
v1 = 10
f1(f1, v1)

Para os testes, foi utilizado Python 2.7.11.
Importante: conforme as referências, este tipo de de código tem utilidade acadêmica e, provavelmente, o uso em ambientes de produção não é recomendado.
Referências:
Wikilivros - Algoritmos e Estruturas de Dados/Recursividade
Wikipedia - Recursividade - ciência da computação
Wikipedia - Cálculo lambda
Wikipedia - Combinador de ponto fixo


VBA module functions not defined access 2010

Question: I want to use some functions I created in another .mdb in the project i'm currently working on.
I first went in VBA editor (alt+f11) and right clicked -> export... -> save as module1.bas on my desktop
then I opened my other project and right clicked -> import -> module1.bas
I now see the module1 within my other modules so I use some functions in my code, I clicked save and compile.
Compile Error Sub or Function  not defined.

It points functions defined in the module I just exported. If I write :
module1.functionName parameter

It compiles but I usually don't have to type the reference like that. Why is this happening?
How to reference my module to my project?
Comment: Thanks for letting us know. Please consider posting your findings as an answer to show that the issue has been resolved.
Comment: edit: edit:
Found my mistake by myself. Shamefully Sharing as a reminder to check your code carefully. Subs and Functions were Private in my module.
Comment: edit : nevermind it's still not working
Answer: Subs and Function were defined as Private in my module.
Fixed by putting Public instead.
ie:
Public Sub subName ()


how to make fewer http requests

Question: I'm use YSlow to optimize my web pages it says:
This page has 34 external Javascript scripts. Try combining them into one.
This page has 5 external stylesheets. Try combining them into one.
but all I have in this page is some blocks and menus and a nivo slider which I think is the main reason of this issue!!
so I think nivo slider sends all this requests!!
How can I improve it?
Comment: 34 javascript files sounds like a lot, maybe you could just enable core CSS & JS aggregation at admin > config > development > performance.
Comment: those are enable!!
Answer: There are couple of things you can do,

install labjs module: it is a JavaScript loader, used by Twitter, Vimeo, examiner.com... which loads (and executes) all scripts in parallel as fast as the browser will allow.
Enable gzip compression: It reduces the size of files sent from server to increase the speed. You have to enable it in .htaccess file, for more information visit this page.
As @2pha said Advanced CSS/JS Aggregation is very effective effort.
Install optimize_db module: it handles the issue with fast-growing table cache_form.

Anyway, gtmetrix  suggests many techniques to improve your website performance.
Comment: thanks a lot! I should choose one of this suggestions or I must do all of theme in parallel?
Comment: Use all of the in parallel.
Comment: thanks Drupalist. these approaches helped in other ways but doesn't reduce the external http requests!
Answer: What have you tried already?
I use the Advanced CSS/JS Aggregation module which combines js and css file together making for fewer http requests. It also has some other features including moving js and css to the footer.
Comment: You are setting it up wrong. Did you read the [readme](http://cgit.drupalcode.org/advagg/tree/README.txt) file?
Comment: I've tried to combine all css files together. same for js files. but I afraid making a worse trouble anyway. have you tested this module?
Comment: I have used this module on over 30 sites. My answer is specific to JS, there are many other optimizations one can do to speed up a drupal site. Doing a quick search on google for 'drupal perfomance' will yield many results
Comment: before installing or enabling this module you should uncheck css/js aggregation in performance setting. otherwise your theme will be vanished. this happened for me and I was furious!
Comment: This page has 12 external Javascript scripts. Try combining them into one.
This page has 31 external stylesheets. Try combining them into one. why it get worse using this module?
Comment: This page has 17 external Javascript scripts. Try combining them into one.
This page has 37 external stylesheets. Try combining them into one. why it does not change after lots of setting?
Comment: How can we know? We cant see your site. Do you have external scripts? These can not be aggregated.
Comment: this is my website url http://www.etgmco.ir/pilot-project/ppr-2
Comment: Viewing the source, javascript and css is being included on the page with `@import`. This says to me that you have not checked the options under 'bandwidth optimisation' page at: admin/config/development/performance. These checkboxes need to be selected.
Comment: this is the main problem 2pha! when I enable theme my theme vanishes and none of the js run!! what should I do? I need urgent help please

how to make fewer http requests


Change title name in Twitter API using Android?

Question: When you use Twitter API and develop your first simple Twitter client, and post a comment to Twitter - it says "from API". Using the Twitter web it says "from the web". Using Siesmic it says "from Seesmic".
How do you the set the application name/title so it shows up like "from myApp" using Android?
Thanx for listening! Answers will be rewarded.
Answer: See this question: Twitter REST change "from API" to something meaningful


Can't assign value to an object's property in a foreach loop?

Question: I have an object defined as
public class EmailData
    {
        public string TemplateId { get; set;}
        public IEnumerable<Recipient> To { get; set; }
        public IEnumerable<Recipient> CC { get; set; }
        public IEnumerable<Recipient> BCC { get; set; }
    }

public class Recipient
{
    public string Key { get; set; }
    public string Type { get; set; }
    public string Email { get; set; }
    public string Id { get; set; }
}

I have that populated in a constructor, then I need to finish populating the Recipient values and in a nutshell I'm going this (after various attempts):
public EmailData EmailObject;

public void BuildEmailData()
{
   EmailDataBuilder builder = new EmailDataBuilder(EmailObject,CSGTemplateId);
   EmailObject = builder.BuildObject();
}

public void PopulateEmailAddresses()
{
   SetToValues();
}

private void SetToValues()
{
   foreach (Recipient t in EmailObject.To)
   {
       var _user = RepoUser.GetUserById(t.Key);
       t.Email = _user.Email;
       t.Id = _user.Id;
   }
}

So you see that I have an object and I need to populate a couple more fields on it.  Now, I get that the foreach look creates a variable that I'm using so when I assign the Email value, it's not the the data arg, but rather to the variable.  But how do I get around that?  Am I missing something simpler with the foreach?
Many thanks, this was bombing my unit tests before I realized that the assignments weren't working.
What I've gotten working that I don't like is to use a collection of Recipients instead of the IEnumerable directly:
public class EmailData
    {
        public string TemplateId { get; set;}
        public RecipientCollection To { get; set; }
        public RecipientCollection CC { get; set; }
        public RecipientCollection BCC { get; set; }
    }

 public class RecipientCollection: IEnumerable<Recipient>
    {
        private readonly List<Recipient> variableList = new List<Recipient>();

        public IEnumerator<Recipient> GetEnumerator()
        {
            return variableList.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public void Add(Recipient v)
        {
            variableList.Add(v);
        }
    }

 public EmailData BuildObject()
        {
            // get the template.
            EmailObj.TemplateId = _templateRepo.GetCSGEmailTemplate(CSGTemplateId).TemplateId;

            // populate the people
            RecipientCollection _toCollection = new RecipientCollection();
            RecipientCollection _ccCollection = new RecipientCollection();
            RecipientCollection _bccCollection = new RecipientCollection();

            foreach (var r in _recipRepo.GetRecipientByAction("To"))
            { _toCollection.Add(r); }
            EmailObj.To = _toCollection;

            foreach (var r in _recipRepo.GetRecipientByAction("CC"))
            { _ccCollection.Add(r); }
            EmailObj.CC = _ccCollection;

            foreach (var r in _recipRepo.GetRecipientByAction("BCC"))
            { _bccCollection.Add(r); }
            EmailObj.BCC = _bccCollection;

            return EmailObj;
        }

 public void BuildEmailData()
        {
            EmailDataBuilder builder = new EmailDataBuilder(EmailObject,CSGTemplateId);
            EmailObject = builder.BuildObject();
        }

public void PopulateEmailAddresses()
        {
            foreach (Recipient t in EmailObject.To)
            {
               var _user = RepoUser.GetUserById(t.Key);
               t.Email = _user.Email;
               t.Id = _user.Id;
             }
        }

It's not ideal as is breaks another piece to this which uses Linq to XML but I can figure that out.
Comment: Honestly I'd like to do this via Linq but I can't seem to find a way to assign values as such.
Comment: Hm ... sometimes you need a plain old for loop with indices instead of foreach, but I do not have a great answer. Also, what are the actual types? Could you temporarily stop using `var`? What type do you have to use then? http://stackoverflow.com/questions/2196638/c-cannot-assign-to-foreach-iteration-variable
Answer: Is Recipient a Struct? Change it to a class perhaps.
Answer: Since .To has set, do:

create a new list of recipients
foreach original recipient construct new and insert it into the new list
assign new list to .To

That should work.


CodeIgniter form_open_multipart, como usar

Question: Estou usando o CodeIgniter em um projeto mas estou com uma dificuldade para fazer o envio das informações, tenho uma view que contém um formulário com os campos de cadastro:

            <?php

             echo form_open_multipart('Controller_site/cadastro_form');

             ?>

            <input type="text" class="input-text" name="pais" placeholder="País">

Dentro dessa view eu tenho vários outros campos que estão sendo "embrulhados" com divs (Bootstrap) para montar o layout.Estou fechando o formulário na última div:

    <button type="button" class="btn btn-success">Cadastrar</button>

    <?php
     echo form_close();

     ?>

No Controller_site tenho a seguinte função:
 public function cadastro_form(){

    $data = 'null';

        $data = array(
            'pais' => $this->input->post('pais'),
            'name_users' => $this->input->post('name_users'),
            'last_name' => $this->input->post('last_name'),
            'date_nasc' => $this->input->post('date_nasc'),
            'sexo' => $this->input->post('sexo'),
            'cpf' => $this->input->post('cpf'),
            'mail' => $this->input->post('mail'),
            'phone' => $this->input->post('phone'),
            'cep' => $this->input->post('cep'),
            'logradouro' => $this->input->post('logradouro'),
            'bairro' => $this->input->post('bairro'),
            'num' => $this->input->post('num'),
            'city' => $this->input->post('city'),
            'state' => $this->input->post('state'),
            'payment' => $this->input->post('payment'),
            'num_cart' => $this->input->post('num_cart'),
            'validade' => $this->input->post('validade'),
            'agencia' => $this->input->post('agencia'),
            'conta' => $this->input->post('conta'),
            'cvv' => $this->input->post('cvv'),
            'login' => $this->input->post('login'),
            'senha' => $this->input->post('senha'),
            'confirmar_senha' => $this->input->post('confirmar_senha'),

        );

        $this->Model_site->cadastro($data);

        redirect("index", 'redirect');

    }
}

No model:
     public function cadastro ($data){
    return $this->db->insert('tb_users',$data);
}
}

Eu preencho os dados do formulário e nada acontece a página fica do mesmo jeito o botão "parece" nem ter efeito de botão.
Obs: O arquivo do banco de dados já está configurado.
Comment: Botão com `type="button"` não submete formulário. Coloque `type="submit"`
Comment: Deu certo! Muito Obrigada (; Poderia me ajudar em outra coisa, a url está duplicando sabe como posso resolver:  http://localhost/superbat/index.php/Controller_site/localhost/Superbat/Controller_site/cadastro_form
Answer: O problema é que você colocou
<button type="button" class="btn btn-success">Cadastrar</button>

O elemento <button> com type="button" não faz a submissão do formulário. Ele é mais utilizado quando irá efetuar uma requisição AJAX ou executar alguma ação na própria página.
Para fazer a submissão do formulário, altere para type="submit":
<button type="submit" class="btn btn-success">Cadastrar</button>

Comment: +1 Muito Obrigada!


Erro quando tento executar nls

Question: Aparece o seguinte erro:
"Error in numericDeriv(form[[3L]], names(ind), env, ifelse(internalPars <  :
  Obtido valor faltante ou infinito quando avaliando o modelo"
Quando eu tento executar um nls pela seguinte fórmula:
ca=max(df$y)
    eps <- .Machine$double.eps^0.5
    fit <- nls(y ~ a*(1 - exp(-b*x))^c, data = df,
               start = list(a = ca, b = 0.05, c = 1),
               algorithm = 'port',
               control = nls.control(maxiter = 100,tol = eps))

Dados usados:
y<-c(79,86,9,10,49,45,260,10,8,182,824,2,11,112)
x<-c(1.22,2.01,2.7,3,2.5,1.49,1.46,1.5,1.31,1.95,1.58,1.62,1.9,1.42)
df<-data.frame(y, x)

Qual poderia ser o problema?
Answer: Versão do R e dos pacotes minpack.lm e ggplot2.
R.version.string
#[1] "R version 4.0.1 (2020-06-06)"
packageVersion('minpack.lm')
#[1] '1.2.1'
packageVersion('ggplot2')
#[1] '3.3.0'

Versão do Ubuntu.
rui@rui:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04 LTS
Release:    20.04
Codename:   focal
rui@rui:~$

Ao tentar o código da resposta do
Carlos Eduardo Lagosta não obtive os mesmos resultados, o código deu um aviso de não convergência em 50 iterações.

Warning message:
  In nls.lm(par = start, fn = FCT, jac = jac, control = control, lower = lower,  :
    lmdif: info = -1. Number of iterations has reached `maxiter' == 50.

E, portanto, os valores dos parâmetros ajustados foram diferentes.
fit
#Nonlinear regression model
#  model: y ~ a * (1 - exp(-b * x))^c
#   data: df
#         a          b          c
# 6.783e+01  1.341e-06 -4.380e-02
# residual sum-of-squares: 605975
#
#Number of iterations till stop: 50
#Achieved convergence tolerance: 1.49e-08
#Reason stopped: Number of iterations has reached `maxiter' == 50.

Tentei então com valores diferentes para maxiter e ptol, que podem ser passados a nlsLM através de control = nls.lm.control(.).
library(minpack.lm)
library(ggplot2)

eps <- .Machine$double.eps^0.5

fit <- nlsLM(y ~ a*(1 - exp(-b*x))^c, data = df,
             start = list(a = max(df$y), b = 0.05, c = 1),
             control = nls.lm.control(maxiter = 100, ptol = eps))

summary(fit)
#
#Formula: y ~ a * (1 - exp(-b * x))^c
#
#Parameters:
#    Estimate Std. Error t value Pr(>|t|)
#a  1.297e-02  8.481e+01   0.000    1.000
#b  2.372e-05  1.715e-01   0.000    1.000
#c -9.049e-01  2.271e+00  -0.399    0.698
#
#Residual standard error: 231.9 on 11 degrees of freedom
#
#Number of iterations to convergence: 93
#Achieved convergence tolerance: 1.49e-08
#

Agora o gráfico mas com o pacote ggplot seguindo o exemplo da resposta a esta pergunta.
ggplot(df, aes(x = x, y = y)) +
  geom_point() +
  geom_smooth(method = 'nlsLM',
              formula = y ~ a*(1 - exp(-b*x))^c,
              se = FALSE,
              method.args = list(start = list(a = max(df$y), b = 0.05, c = 1),
                                 algorithm = 'port',
                                 control = nls.lm.control(maxiter = 100, ptol = eps)))

Comment: Eu usei o seu exemplo, mas a curva se ajustou igual ao exemplo do Carlos Eduardo Lagosta
Comment: @MiltondePaula Pelos vistos há diferenças de resultados se as versões do R forem diferentes. Quais as suas versões do R, SO e pacote?
Comment: a versão é a 1.2.5001, mas já notei aqui que existe uma versão mais atualizada, meu SO é o Windows 10 versão 1903 e a versão do pacote "minpack.lm" é 1.2-1...
Comment: @MiltondePaula Isso não é a versão do R, é a versão do RStudio. A minha é a 1.2.5042. Para ter a versão do R corra `R.version` ou `R.version.string`.
Comment: Agora correto: "version.string R version 3.6.1 (2019-07-05)", @RuiBarradas
Answer: O nls é particularmente suscetível a estimativas ruins dos parâmetros (ou por valores iniciais muito distantes e/ou modelos com parametrização pouco adequada aos dados). Uma alternativa no caso de não conseguir estabelecer valores iniciais razoáveis é usar a função minpack.lm::nlsLM: ela transforma a fórmula em uma função e invoca LM para otimizar os valores iniciais dos parâmetros antes de chamar o NLS:
library(minpack.lm)

fit <- nlsLM(y ~ a*(1 - exp(-b*x))^c, data = df,
             start = list(a = max(df$y), b = 0.05, c = 1))

> summary(fit)

Formula: y ~ a * (1 - exp(-b * x))^c

Parameters:
  Estimate Std. Error t value Pr(>|t|)
a 1.484e+02  5.376e+03   0.028    0.978
b 9.182e-09  1.971e-06   0.005    0.996
c 1.267e-02  2.055e+00   0.006    0.995

Residual standard error: 235.1 on 11 degrees of freedom

Number of iterations to convergence: 35
Achieved convergence tolerance: 1.49e-08

No seu caso, seria interessante rever o modelo que está usando, já que ele é pouco descritivo para seus dados:
plot(df$x, df$y)
lines(df$x, predict(fit), col = "red")

Usei minpack.lm versão 1.2-1, em um computador Debian Linux 10.4 64 bits rodando R 3.5.2.
Comment: Rs, uso um servidor para análise de dados que roda muitas coisas sensíveis em dados privados. A não ser que haja real necessidade de versão mais nova, me atenho às versões do repositório estável do Debian.
Comment: Tive problemas ao correr o seu código, veja a minha resposta.
Comment: Rodei em uma sessão limpa e rodou normal. Rodando com e sem `control = nls.control(maxiter = 100, tol = eps)` cheguei nos mesmos valores. Diferença nos sistemas/versões dos pacotes, talvez?
Comment: Acrescentei esses dados à resposta. R 4.0.1, minpack.lm 1.2.1, Ubuntu 20.04.
Comment: minpack.lm 1.2-1, R 3.5.2, Debian Linux 10.4
Comment: É hora de atualizar! (pelo menos o R, que é grátis :)).

Erro quando tento executar nls


Having some issues with setting up permissions on my web server

Question: My setup is the following:
Multiple users coding for the one website
Each user has their own username/group
Websites are located in /usr/local/ourcompany/websites/sitename/*

./websites/ is owned by me:ourcompany. I set this folder and all it's subfolders to be writable by group. chmod g+ws websites
This takes care of most the permission issues. It allows everyone in the ourcompany group to edit the website files. The problem is when uploading files via PHP.
PHP is running as www-data. This seems to break the setuid group writable setting.
I'm running Nginx, if that's relevant...
Any tips?
Comment: Just a comment as I can't offer a solution: The issue is that, although you've got group-sticky on the folders, that doesn't apply to newly created files, which take on the system-wide umask. Most common linuxes have the umask set at 0022 (= rwxr-xr-x). You could set that to 0002 (= rwxrwxr-x), But I'm going to staple the words 'Massive Security Hole' to that as a warning. It's not possible to set per-directory umasks. :)
Answer: I will do it this way:
1- Keep the working permissions as you have it.
2- Upload the files via PHP to a different (temporary) directory. This temp directory should be writable by www-data user.
3- Write a simple script to copy/move the uploaded files from the temp directory to the desired path /usr/local/ourcompany/websites/sitename/*. Then, you can chown/chmod the new files to make sure the permissions are preserved as you upload more files. This script will be executed as root as explained in the next point.
4- Add the www-data user to sudoers file. Use sudo visudo to edit it. So, the www-data user will execute the shell script (created in point 3) as super user without a password. You need to name the script in the sudoers file to restrict this permission to this signle shell script.
Answer: You PHP upload script is probably a very specific one, like /upload/up_script.php
In which case, I would create a specific location in the nginx's config, and execute those queries with a php5-cgi process runned by a member of "ourcompany" (instead of www-data).
The rest of the code can (should) still be executed by a user that doesn't have write permissions on the website files.


Logging SSL ciphersuite used in Windows Server 2008 R2

Question: Is there a way to see /log which cipher suites are (actively) being used to establish SSL connections on Windows Server 2008 R2?
Ideally on a per request basis, like an extra column in the IIS logs.
Answer: IIS logs won't help you here, since the SSL connection is negotiated before any HTTP/application layer traffic starts flowing.
But what you can do is:
<code>C:\Windows\system32>netsh trace start capture=yes

Trace configuration:
-------------------------------------------------------------------
Status:             Running
Trace File:         C:\Users\Ryan\AppData\Local\Temp\NetTraces\NetTrace.etl
Append:             Off
Circular:           On
Max Size:           250 MB
Report:             Off

C:\Windows\system32>netsh trace stop
Correlating traces ... done
Generating data collection ... done
The trace file and additional troubleshooting information have been compiled as "C:\Users\Ryan\AppData\Local\Temp\NetTraces\NetTrace.cab".
File location = C:\Users\Ryan\AppData\Local\Temp\NetTraces\NetTrace.etl
Tracing session was successfully stopped.
</code>
You can open that ETL file with Windows Performance Analyzer, and also with NetMon. (The latter will likely be more useful to you.)
http://blogs.technet.com/b/mrsnrub/archive/2009/09/10/capturing-network-traffic-in-windows-7-server-2008-r2.aspx
Here's a screenshot of that trace file I just generated:
(Open in new tab to see fullsize)

Edit: To find the exact cipher mode being used, locate the "HandShake: Server Hello" packets:

Here is a Microsoft support article telling you how to interpret the bytes of the packet manually, but Netmon will do it for you.
You could come up with a packet trace filter that only contained packets of this nature. If there's a better way to get this data I'd like to know about it.
Comment: Edited my post. Yes the precise cipher mode is in there too.
Comment: Close. I origally accepted the answer, but I can't work out from this what actual cipher suite is being used.  "TLS 1.0" is too vague.  I can see in the handshake packet a bunch of suites being offered ("TLSCipherSuites: TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA   { 0x00, 0x88 } etc", but I can't tell which one is being picked.
Comment: For extra credit - I'd prefer something that grabbed less data than ETL - all I need is a historical log of ciphersuites used.
Comment: What about constant monitoring to collect statistics about what protocol/suites are being used on server? Is trace appropriate to be running on webserver 24/7 performance wise? Ofcourse netsh can be limited to capture subset of traffic (like port, not sure if only TLS handshake can be filtered out), but what would be community opinion?


Diretório e extensão de arquivo FileStream

Question: Como especificar o diretório de criação do arquivo e a sua extensão?
byte[] vetorImagem = (byte[])cmdSelect.ExecuteScalar();
string strNomeArquivo = Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs = new FileStream(strNomeArquivo, FileMode.CreateNew, FileAccess.Write);
fs.Write(vetorImagem, 0, vetorImagem.Length);
fs.Flush();
fs.Close();
pbDefault.Visible = false;
pbUsuario.Image = Image.FromFile(strNomeArquivo);

Answer: Na verdade o que você passa como primeiro parâmetro no construtor do FileStream não é o nome do arquivo, mas o endereço (path) do arquivo.
O endereço dele deve conter o caminho, nome e extensão do arquivo em uma só string.
Portanto após obter o nome do arquivo você deveria concatenar o resto das informações para ter o endereço completo:
string strNomeArquivo = Convert.ToString(DateTime.Now.ToFileTime()),
localizacaoArquivo = "c:/",
extensaoArquivo = ".png",
enderecoArquivo = localizacaoArquivo + strNomeArquivo + extensaoArquivo;
FileStream fs = new FileStream(enderecoArquivo, FileMode.CreateNew, FileAccess.Write);
...

Note que se você quiser o caminho de alguma pasta padrão do Windows, você pode obtê-las usando o Enum de pastas especiais do sistema.
Para a pasta Minhas Imagens do usuário, por exemplo:
string localizacaoArquivo = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);

Comment: o meu sistema criou o arquivo no diretório padrão com nome ex: Cache131113874626944091 e não executou a ação esperada
Comment: `string strNomeArquivo = Convert.ToString("Cache\\" + txtUsuario.Text + DateTime.Now.ToFileTime() + ".ebtemp"),
                extensaoArquivo = "",
                enderecoArquivo = strNomeArquivo + extensaoArquivo;
                FileStream fs = new FileStream(enderecoArquivo, FileMode.Create, FileAccess.ReadWrite);
                fs.Write(vetorImagem, 0, vetorImagem.Length);
                fs.Flush();
                fs.Close();
                pbDefault.Visible = false;
                pbUsuario.Image = Image.FromFile(strNomeArquivo);`

Modifiquei e deu certo!


This is undefined em React Hooks

Question: Olá, estou criando um sistema em JS utilizando react Hooks, porém me deparei com um problema, quando eu utilizo <Route exact path ="/produto/:idProduto" component={Quiz}/>
conseguimos captar o id com const {id} = this.props.match.params (armazenando dentro de uma variável)
porém isso funciona normalmente em um "class component" exemplo:
class Quiz extends Component{
    constructor(props){
        super(props)
        this.state = {  }
    }

    componentDidMount(){
        const {id} = this.props.match.params
        console.log(id)
    }

    render(){
        return(

                oi

        )
    }
}
export default Quiz

neste exemplo é impresso no console o id que está na url, tudo certinho. porém quando utilizo react hooks, aparece "this is not defined" mesmo exemplo com hooks:
import React, { useEffect } from 'react'

function Exemplo(){

    useEffect(()=>{
        const {id} = props.match.params
        console.log(id)
    },[])

    return(

            oi

    )
}
export default Exemplo

erro:

TypeError: this is undefined
Answer: Você deve receber props como parâmetro do hook (assim como você recebe ele no construtor da classe) e usá-lo sem o this:
function Exemplo(props){
  const {id} = props.match.params

  // ...
}

Comment: Obrigado mano, funcionou!! (tirei o this)

This is undefined em React Hooks


Solve for x in logarithmic equation

Question: I'm having a lot of trouble with this problem. I don't know if it's possible but thought it would be worth asking.
Simply solve for $x$.
$$s=\left(\frac{x^2}{n}+x\right)\ln\left(\frac{n+x}{x}\right)$$
WolframAlpha doesn't solve it. I can't seem to solve it.  So I figured it might take some more advanced technique.
Comment: Are $s$, $x$ and $n$ variables or constants?
Comment: Yes you may think of them as constants.
Answer: The mix of logs and polynomials is a problem.  If $x \gg n$ you can write
$$s=\left(\frac{x^2}{n}+x\right)\ln\left(\frac{n+x}{x}\right)\\=\left(\frac{x^2}{n}+x\right)\ln\left(1+\frac{n}{x}\right)\\
\approx \left(\frac{x^2}{n}+x\right)\frac nx\\
=x+n\\
x=s-n$$
This will work when $n$ is small compared to $s$.  The error will be of order $(\frac nx)^2.$  Otherwise you are in for a numeric solution.
Answer: As Ross Millikan already answered, you will need some numerical method (such as Newton method for example) to solve this transcendental equation and this means that you will need a "good" starting point.
Assuming that $x$ could be large, we can built the $[2,2]$ Padé approximant for infinitely large values of $x$ and get by the end (after simplifications)
$$s \approx x+\frac{n (n+6 x)}{6 (n+2 x)}$$ which reduces to a quadratic equation in $x$
$$x^2+ (n-s)x+\frac{n (n-6 s)}{12} =0$$ which shows two roots since $\Delta=\frac{2 }{3}n^2+s^2 >0$. The one to keep is given by
$$x_0=\frac{s-n} 2+\frac{ \sqrt{6 n^2+9 s^2}}{6}$$
For illustration purposes, let us try using $n=123.456$ and $s=789.012$. This could give
$x_0\approx 730.49$. Now, using Newton method, the iterates would be
$$\left(
\begin{array}{cc}
 n & x_n \\
 0 & 730.490477415532 \\
 1 & 730.494365219568 \\
 2 & 730.494365219646
\end{array}
\right)$$ which is the solution for fifteen significant figures.
Keeping the same value for $n$ but using now $s=78.9012$, xe would have
$$\left(
\begin{array}{cc}
 n & x_n \\
 0 & 41.7271349671412 \\
 1 & 43.3226603413356 \\
 2 & 43.3300991145702 \\
 3 & 43.3300992693775
\end{array}
\right)$$
Edit
Assuming $x$ to be large, we could perform the Taylor series expansion of the rhs and get
$$\left(\frac{x^2}{n}+x\right)\log\left(\frac{n+x}{x}\right)=x+\frac{n}{2}-\frac{n^2}{6 x}+\frac{n^3}{12 x^2}-\frac{n^4}{20 x^3}+\frac{n^5}{30
   x^4}-\frac{n^6}{42 x^5}+O\left(\frac{1}{x^6}\right)$$ Then, using series reversion
$$x=s-\frac{n}{2}+\frac{n^2}{6 s}-\frac{7 n^4}{360 s^3}+\frac{139 n^6}{30240
   s^5}+O\left(\frac{1}{s^6}\right)$$ For the worked examples, this would give $730.494$ and $45.4946$.

Solve for x in logarithmic equation


Bug highlighting random characters on VScode Terminal?

Question: I suddenly got what appears to be some random highlights on my terminal in VScode. Whatever I try to write it just gets hidden by the yellow boxes you see in the screenshot. It even keeps the highlights in place even if I delete the characters. Has anyone experienced something similar?
Comment: It looks like you are using some sort of custom theme.  What if you change themes?
Comment: Makes no difference.
Comment: @TimothyG. I just found out that turning off Terminal > Integrated: GPU Acceleration in my settings eliminates the problem. I'm using the latest vscode 1.70.2 on a 12years old MacBook Pro running Mac OS 10.13.6 and vscode might be starting to get a bit buggy with this setup.
Comment: Good find. You should post that as an answer. I think the gpu acceleration has caused similar graphical glitches in the past too.
Answer: I just found out that turning off Terminal > Integrated: GPU Acceleration in my settings eliminates the problem. I'm using the latest vscode 1.70.2 on a 12years old MacBook Pro running Mac OS 10.13.6 and vscode might be starting to get a bit glitchy with this setup.


xslt record display

Question: I have a problem. I get the data from xml then transform it with xslt.
Let us say I have a xml file:
<?xml version="1.0"?>
 <root>
   <row id="1" fname="Dan" lname="Wahlin">
    <address type="home">
       <street>1234 Anywhere St.</street>
       <city>AnyTown</city>
       <zip>85789</zip>
     </address>
     <address type="business">
       <street>1234 LottaWork Ave.</street>
       <city>AnyTown</city>
       <zip>85786</zip>
     </address>
  </row>
   <row id="2" fname="Elaine" lname="Wahlin">
    <address type="home">
      <street>1234 Anywhere St.</street>
      <city>AnyTown</city>
       <zip>85789</zip>
     </address>
    <address type="business">
      <street>1233 Books Way</street>
       <city>AnyTown</city>
       <zip>85784</zip>
    </address>
  </row>
 </root>

And this stylesheet:
<?xml version="1.0" ?>
 <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   version="1.0">
<xsl:output method="xml" indent="yes" encoding="utf-8" omit-xml-declaration="no"/>
   <xsl:template match="/">
     <root>
        <xsl:apply-templates/>
      </root>
    </xsl:template>
    <xsl:template match="row">
          <row>
            <xsl:attribute name="id">
                    <xsl:value-of select="id"/>
               </xsl:attribute>
                <xsl:attribute name="fname">
                     <xsl:value-of select="name/fname"/>
                </xsl:attribute>
                <xsl:attribute name="lname">
                     <xsl:value-of select="name/lname"/>
              </xsl:attribute>
              <xsl:for-each select="address">
                   <xsl:copy-of select="."/>
               </xsl:for-each>           </row>
      </xsl:template>
 </xsl:stylesheet>

How can limit this to 3 records, then after 3 records it create a tr tag?
For example:

  Address1
  Address2
  Address3

   Address4
   Address5
   Address6

Comment: @crisgomez: Sorry, but your input does not match your desired output. Also, your stylesheet is doing a verbose identity transform. So, the question is not clear and you have low rate which discourages guessing.
Answer: Instead of:
<xsl:for-each select="address">
<xsl:copy-of select="."/>
</xsl:for-each>

You should have something like this:
<xsl:for-each select="address">
<xsl:if test="position() mod 3 = 1">

<xsl:call-template name="printAddress">
<xsl:with-param name="address" select="."/>
</xsl:call-template>
<xsl:call-template name="printAddress">
<xsl:with-param name="address" select="following-sibling::*[position() = 1]"/>
</xsl:call-template>
<xsl:call-template name="printAddress">
<xsl:with-param name="address" select="following-sibling::*[position() = 2]"/>
</xsl:call-template>

</xsl:if>
</xsl:for-each>

And of course you have to have template printAddress somewhere.
This should give you an idea on how to solve it. The point is to process every n-th item (chosen by position() mod n) and explicitly process n following items at once (chosen by following-sibling::*[position() = x]), wrapping them in tr. Notice that it is important to compare mod result with 1, since position starts counting from 1.
Comment: what is "galleryItem"? is this souhld exist in my stylesheet?
Comment: This is just a copy-paste from my own template which creates 3 column table of images from a simple list, which is the same situation as you have. As I wrote, it should just give you an idea of how to do it, you should be able to apply it for your situation yourself.
Comment: It is quite confusing to just post a stylesheet for totally different input.  The least you could do would be to adapt your technique for the given input data.
Comment: @Jim Garrison: You can see, that adapting it to his "totally different input" means changing 3 names. crisgomez asked a very good question, which can be tricky even to experienced developer, so it deserves an answer. But I also suspect him of not having much interest in the xsl or the community. The point was to provide a valuable answer while not doing his homework instead of him (in my work time, by the way).

xslt record display


Spring MVC no matching editors or conversion strategy found

Question: I am trying to send custom javascript object (actually, its array of JSON objects) via jquery post request to spring controller.
The server-side fails with "bla-bla no matching editors or conversion strategy found" error. It can't convert from string to server-side object.
I found this and this examples but I can't put it together to make it work.
Which methods of PropertyEditor should I override?
Does anybody knows link to any example?
Thank you.
Controller:
private class AddressFormEditor extends PropertyEditorSupport {
    protected Object convertElement(Object element)
    {
        String form = "";

        if (element instanceof String)
                form = (String) element;
        Logger logger = Logger.getLogger(getClass().getName());
        logger.warning(form);
        return form != null ? new AddressForm(form) : null;
    }
}

@InitBinder
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception
{
      binder.registerCustomEditor(AddressForm.class, new AddressFormEditor());
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
    public ModelAndView saveUser(@ModelAttribute UserForm form, HttpServletResponse response) {...}

UserForm:
public class UserForm extends BaseForm {
private Long id;
private String login;
private String password;
private String confirmPassword;
private String type;
private String franchise;
private String roles;
private String firstName;
private String lastName;
private String salutation;
private String position;
private String birthDate;
private String passportNumber;
private String passportIssueBy;
private String passportIssueDate;
private String passportExpireDate;
private String nationality;
private AddressForm[] addresses;
private String notes; ... }

jQuery request:
var data = $('#userForm').serializeObject();
        data.addresses = addresses;
        $.ajax({
            traditional: true,
            type: 'POST',
            url: url + 'save',
            data: data,
            success: function(response) {
                if (response) {
                    initializeUser(response);
                    hideWait();
                }
                else {
                    showUsers();
                    $('#closeUserBtn').click();
                }
            },
            error: function() {
                error();
                hideWait();
            }
        });

Logger writes that addresses is '[object Object]' but actually the valid array was sent to server
Comment: maybe showing some code will help
Comment: The problem is that I can't find any example of String to Server-side object property editor
Answer: Have a look at the editors under org.springframework.beans.propertyeditors (in the spring-beans jar), which contains the built-in editors provided with spring.
Basically, you need to overwrite setAsText() and getAsText(), which allow you to read the object from a String and write the object as string respectively.
CurrencyEditor could serve as a very simple example. CustomDateEditor could serve as a slightly more complex one. For an array example, have a look at the ClassArrayEditor, for example.

However, The best way to go about this is to use a JSON mapping technology instead of parsing the JSON yourself; have a look at this post.
Comment: Thanks for your reply. The problem is that if I change ModelAttribute to RequestBody so I can't response ModelAndView object (415 error). Is there any way to get @RequestBody as input param and ModelAndView as output? Thanks
Comment: There shouldn't be any problem with reading the input as `@RequestBody` and returning a `@ModelAndView`. Have you tested it ?
Comment: Thanks for replies. Its ok now, log4j helped to figure out where the problem was.


HELP with XML to XML transformation using XSLT

Question: Am a rookie trying XSLT and XML tranformations for the first time. To start off, i tried a simple sample programs.
I expected the Output in Tree format (maintaining the hierarchy) instead i just get " KING" in single line...
What could be the problem? PS: I use XMLSpy.
Any guideline would be great full. Thanks :)
Input XML:
<ROWSET>
    <ROW>
        <EMPNO>7839</EMPNO>
        <ENAME>KING</ENAME>
    </ROW>
</ROWSET>

XSL used for transformation:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="UTF-8" indent="yes" omit-xml-declaration="no"/>
<xsl:template match="/">
    <Invitation>
        <To>
            <xsl:value-of select="ROWSET/ROW/ENAME"/>
        </To>
    </Invitation>
</xsl:template>

Comment: I don't think there's anything wrong with the above - if I run in in VS2010 the output I get is:

KING
Answer: Well, the only thing that I see is that you miss the closing element </xsl:stylesheet> in the XSL. Other than that, I think the XSL is OK, and if I use it (from Java code) I get <Invitation><To>KING</To></Invitation>, which is, I presume, what you expect.


Error connecting to broker: PulsarClientException Connection Refused

Question: We saw this exception in our Pulsar client app:

Error connecting to broker:
org.apache.pulsar.client.api.PulsarClientException:
java.util.concurrent.CompletionException:
org.apache.pulsar.shade.io.netty.channel.AbstractChannel$AnnotatedConnectException:
finishConnect(..) failed: Connection refused:
myserver.mycompany.com/10.20.10.15:6651

It only randomly occurs. We can't find a way to reproduce it despite testing different client settings. What could be causing this?
Answer: This exception is thrown when the Pulsar broker the client is connected to is restarted.
Pulsar clients connect directly to the broker that is handling the topic the client is using. If that broker is restarted, the connection is broken, and that broker's topics will be unloaded and moved to other brokers. When the client reconnects, it should connect to the broker that is the new owner of that topic, and communication should resume as expected. Since this exception can occur occasionally, you can either handle the exception (e.g. with try/catch), or you can fail fast and force your app to restart, which will also re-establish the connection. I usually recommend failing fast to ensure the exception shows up in logs in case there are concerns around the incident.


XtraGrid - GrdView - Evento ao clicar

Question: Galera bom dia.
Como vai?
Estou com uma dificuldade, em implementar um evento ao clicar no GridView.
Estou utilizando os componentes do DevExpress, XtraGrid.GridView.
Bom, estou adicionando o evento:
this.gridView1.Click += new System.EventHandler(this.click_datagridview1);

que chama meu metodo:
 private void click_datagridview1(object sender, EventArgs e)
    {
        string v = Convert.ToString(gridView1.GetRowCellValue(gridView1.GetSelectedRows()[0], "ID")); //sintexe correta
        MessageBox.Show("Valor da coluna ID " + v);
    }

Porém, ao clicar na tabela, nada acontece, fui atras da documentação no site do DevExpress, e encontrei: Site Help DevExpress
The Click event occurs when the end-user clicks within a View. If clicking a grid cell activates a column editor, the Click event does not occur. Before the Click event, the MouseDown event is generated. This occurs whenever the end-user presses the mouse key.
Please refer to the Hit Information Overview topic for information on how to determine which element has been clicked.
Pelo que entendi, se a edição de colunas estiver ativada, o evento não ocorre, é isso? alguém poderia me dar esclarecida?
Obrigado.
Answer: Galera é isso ai.
Se a edição de colunas estiver ativada, o evento não ocorre.
Para o evento Click ocorrer, deve-se adicionar a linha abaixo nas opções do gridview:
AllowEdit = False

Valeu

XtraGrid - GrdView - Evento ao clicar


SpEL: how to get the type of an expression (not it's value) in

Question: I am trying to use spell to get the type of an expression not the actual instance value. I don't think it's possible, but I wanted to throw it out there.
Consider:
<code>public interface Foo {

    Integer getAge();

    String getFamilyName();

    String getGivenName();

    Set<Integer> getSomeData();

    Set<Baz> getBazez();

    Baz getAnyBaz();
}
public interface Baz {
    Integer getBat();

    Integer getWhatever();
}
</code>
Some Tests
<code>    @Test
    public void testNestedMemberDataType() throws Exception {
        ExpressionParser parser = new SpelExpressionParser();

        EvaluationContext context = new StandardEvaluationContext();

        Expression exp = parser.parseExpression("anyBaz.bat");
        Class<?> valueType = exp.getValueType(context);
        assertEquals(Integer.class,valueType);

    }

   @Test
    public void testNestedMemberDataTypeSet() throws Exception {
        ExpressionParser parser = new SpelExpressionParser();

        EvaluationContext context = new StandardEvaluationContext();
        // this is not valid spell syntax but I would like to do this
        // to indicate the type inside the collection
        Expression exp = parser.parseExpression("bazez[*].bat");
        Class<?> valueType = exp.getValueType(context);
        assertEquals(Integer.class,valueType);

    }
</code>
Answer: I ended up actually implementing it as such:
<code> @Override
    public Class<?> getDeclaredTypeFor(String attribute) {
        Class<?> finalType = entityType;
        List<String> nestings = Arrays.asList(attribute.split("\\."));
        PropertyDescriptor d = null;
        Iterator<String> iter = nestings.iterator();
        while (iter.hasNext()) {
            String nesting = iter.next();
            d = BeanUtils.getPropertyDescriptor(finalType, nesting);
            if (d == null) {
                Set<Class> allTypes = allTypesFor(finalType, new LinkedHashSet<>());
                d = allTypes.stream().map(t -> BeanUtils.getPropertyDescriptor(t, nesting)).filter(p -> p != null).findFirst().orElse(null);
                if (d == null)
                    break;
            }
            if (iter.hasNext() && isTypeACollection(d.getReadMethod().getGenericReturnType())) {
                finalType = getGenericType(d.getReadMethod().getGenericReturnType(), true);
            } else {
                finalType = d.getPropertyType();
            }
        }
        return d == null ? null : finalType;

    }

    private Class getGenericType(Type t, boolean isCollection) {
        Class clazz;
        if (isCollection) {
            Type type = ((ParameterizedType) t).getActualTypeArguments()[0];

            if (type instanceof WildcardType) {
                type = ((WildcardType) type).getUpperBounds()[0];
            } else if(type instanceof TypeVariable) {
                type = ((TypeVariable) type).getBounds()[0];
            }

            clazz = (Class) type;
        } else if (t instanceof Class) {
            clazz = (Class) t;
        } else {
            throw new RuntimeException("Don't know how to handle " + t.getClass());
        }
        return clazz;
    }

    private boolean isTypeACollection(Type t) {
        boolean isPossible = t instanceof ParameterizedType;

        if (isPossible)
            isPossible = Collection.class.isAssignableFrom((Class) ((ParameterizedType) t).getRawType());

        return isPossible;
    }

    private static Set<Class> allTypesFor(Class c, Set<Class> types) {
        types.add(c);
        Class superclass = c.getSuperclass();
        if (superclass != null)
            allTypesFor(superclass, types);

        for (Class iFace : c.getInterfaces()) {
            allTypesFor(iFace, types);
        }
        return types;
}
</code>
Comment: You can probably improve the `getGenericType` bit by using [TypeTools](https://github.com/jhalterman/typetools).


(C#) Como posso substitui um caractere especifico "x" por "y" em uma String?

Question: To querendo fazer uma função que consiga substituir um valor  em caractere( "@" ) por valor "A" dentro da string. Supondo que a entrada seja "@@bbcc@@", então a função retorna "AAbbccAA"  .
Comment: Se for caracteres específicos, por exemplo, o @ para o A, utilize a função `Replace` do C#, desta forma:
String str = "@@bbcc@@";
str = str.Replace("@", "A").Replace("Caractere", "Letra").Replace("Caractere", "...")
Answer: Tente utilizar o código abaixo.
String s = "@@bb@@@";

s = s.Replace("@", "A");

O método Replace da classe String irá substituir todas as ocorrências de @ por A.
Recomendo que vocÊ estude a documentação abaixo também.
https://docs.microsoft.com/en-us/dotnet/api/system.string.replace?view=net-5.0
Answer: Como você especificou a tag regex na sua pergunta, para fazer a mesma coisa utilizando expressão regular seria o equivalente à:
using System.Text.RegularExpressions;

string s = "@@bbb@";

string S = Regex.Replace(s, @"@", "b");

Comment: Qual foi o problema que você teve @causticroot?
Comment: Se tiver dúvidas sobre o método que houve confusão, compartilhe conosco com uma nova pergunta.
Comment: Eu utilizei a classe [RegularExpressions](https://docs.microsoft.com/pt-br/dotnet/standard/base-types/regular-expressions) tb, mas eu não consegui utiliza-lo de uma forma organizada para resolver o meu  problema ... :/
Comment: Eu encontrei uma solução meio confusa, li a documentação  mas essas classes  que manipulam  String tem uns  comportamentos bem parecidos... como comecei estudar agora pouco acabei me confundindo um pouco. Compartilhei abaixo como eu resolvi utilizando o `Regex.Replace`
Answer: O que eu estava resolvendo era isso:

Gordon Ramsay shouts. He shouts and swears. There may be something
wrong with him.
Anyway, you will be given a string of four words. Your job is to turn
them in to Gordon language.
Rules:
Obviously the words should be Caps, Every word should end with '!!!!',
Any letter 'a' or 'A' should become '@', Any other vowel should become
'*'.

Acabei achando um exemplo com o uso da classe StringBuild e foi a forma mais legível de resolver, vou compartilhar aqui os caminhos que segui:
o primeiro, meio embaraçoso e confuso:
public class Kata
{
  public static string Gordon(string a)
  {
    a = System.Text.RegularExpressions.Regex.Replace(a, "[eiou]", "*", RegexOptions.IgnoreCase).Replace("[aA]", "@");
    return a = System.Text.RegularExpressions.Regex.Replace(a, "a", "@", RegexOptions.IgnoreCase).Replace(" ", "!!!! ").ToUpper() + "!!!!";
  }
}

O segundo, mais compreensível :
public class Kata
{
    public static string Gordon(string a)
    {
        StringBuilder frase = new StringBuilder(a);
        frase.Replace("a", "@")
            .Replace("e", "*")
            .Replace("i", "*")
            .Replace("o", "*")
            .Replace("u", "*")
            .Replace(" ", "!!!! ");
        string fraseNova = string.Format("{0}!!!!", frase).ToUpper();
        return fraseNova;

    }

}

Comment: Lembrando que a minha intenção é entender como funcionava o processo, e para isso tentei buscar um exemplo que me ajudasse a entender melhor.  Ainda estudo, o meio de solucionar foi a nível  de conhecimento mesmo, não de buscar a solução menos custosa ou a mais correta, porém compreendi o seu ponto de visto, reconheço que exista formas melhores de resolver.
Comment: Um lança-foguetes contra uma formiga. Toda esta lógica é necessária para um trabalho tão simples que já vem pronto no Framework?


Alternativa a Unit of Work + Repository para compartilhamento do DbContext

Question: Já vi varias vezes as pessoas falando que não faz sentido usar Unit of Work + Repository com DbContext Unidade de trabalho (Unit of Work) com repositório
Supostamente seria "mais certo" utilizar o DbContext diretamente numa camada como a de serviço? como:
<code>public class SomeService
{
   public void SomeSaveMethod(Obj obj)
   {
       DbContext.Set<TEntity>().Add(obj);
       DbContext.SaveChanges();
   }
}
</code>
Essa abordagem não me parece melhor, já que deixa a classe de serviço menos coesa e cria uma dependência com a implementação.
Então quais são as outras alternativas? Eu uso o Repository como forma de esconder a implementação aproveitando a Herança para CRUD e o UoW para compartilhar o DbContext (que é injetado por DI na UoW).
Comment: Isso é muito relativo, depende da arquitetura que está decidir utilizar. Mas como citou as camadas, se for pra separar por camadas eu faria uma exclusiva de acesso a dados, contendo o UoW. Deixando a camada de serviço exclusiva para as regras de negócio, E através do serviço chamaria o repositório.
Comment: É exatamente assim que venho desenvolvendo meus projetos! Na verdade a pergunta é mais porque li varias pessoas que parecem ter uma certeza sobre o assunto (de não usar Unit of Work + Repository +DbContext), e até agora eu não entendi da onde isso vem....
Answer: Arquitetura é um tema complicado e polemico mesmo. Não existe uma "bala de prata" que resolve tudo.
Muitas pessoas são contra o uso de repositório quando se usa algum ORM porque ele oferece muitas facilidades no acesso e operações com dados e criar um repositório causa a impressão de repetição.
Eu não concordo com essa abordagem porque você está delegando toda sua manipulação de dados para um framework. Isso pode ocasionar problema no futuro relacionado a performance com queries linq / lambda grandes, ilegíveis e difíceis de debugar.
Há outros fatores que motiva utilizar o repositório e outras camadas em um sistema que é a escrita de testes. Se você, por exemplo, coloca na camada de domínio o acesso a dados e a resolução de regra de negócio provavelmente você vai escrever métodos grandes e complexos inviabilizando a escrita de testes unitários.
Uma aplicação web clássica dividida em camadas geralmente contém as seguintes camadas (lembre-se que pode haver várias outras soluções arquiteturais):
User Interface (Interface do Usuário)
Camada onde o ocorre a iteração com o usuário
Application (aplicação)
Uma outra camada polemica. Nela você trata as suas regras de interface como, por exemplo, transformar uma Model em ViewModel e vice-versa.
Domain (Domínio)
Nesta camada você resolve as regras de negócio da aplicação como efetuar determinado cálculo de acordo com os dados informados pelo usuário, calcular o percentual a debitar de uma venda etc.
Repository (Repositório)
Aqui você trata somente o acesso a dados. A camada de domínio "entrega" os objetos de domínio "prontos" para que você possa executar somente operações no banco.
Este é apenas um exemplo de arquitetura que é muito comum, mas como disse no início não existe bala de prata para tudo. Antes de iniciar o desenvolvimento que qualquer sistema procure entender bem os requisitos da aplicação para criar uma arquitetura aderente que atenda as necessidades da aplicação, seja fácil de entender e desenvolver.
Lembre-se que temos várias outros tipos de arquitetura como baseada em microservicos, mensageria entre outras.
Dá uma olhada nesta palestra que fala sobre a arquitetura do Stackoverflow.


Compare the approximation with the actual value of $\Delta w$

Question: Let $w=x^2y+z$
Use differentials to approximate $\Delta w$ as $(x,y,z)$ moves from $(1,2,1)$ to $(1.01, 1.98, 1.03)$
Compare your approximation with the actual value of $Delta w$

I calculated $dw=2xydx+ x^2dy+dz$
From there, how to calculate $\Delta w$ ? And how to compare?
Please show me how to calculate step by step. Please write this clearly with formulas. Do not just give the result. Thank you.
Comment: Why close? I will immediately correct if I have a mistake.
Comment: Your $dw$ is not correct. How did you arrive at that?
Comment: Sorry I forget to write 'y' @Raskolnikov
Comment: Please show me the solution @Raskolnikov
Comment: You're right, a $y$ is missing. But then you should have $\nabla w$, it's just the factors in front of $dx$,$dy$ and $dz$ put in a vector.
Comment: By the way, I think what is meant in the question is not $\nabla w$ but $\Delta w$. Hence the confusion.
Comment: Aow yeah! That you said şs true. But I dont know how to write this symbol? Please can you correct this? @Raskolnikov
Answer: They mean a linear approximation for the function $w$. But since you computed the differential $dw$, it is easy to compute an approximation for $\Delta w$ as follows:
$$\Delta w \approx 2xy \Delta x+ x^2 \Delta y+ \Delta z$$
in which
$$(\Delta x, \Delta y, \Delta z)= (1.01, 1.98, 1.03)-(1,2,1)=(0.01,-0.02,0.03)$$
and
$$(x,y,z)=(1,2,1) \; .$$
Comment: Okay got it! Thank you so much:)
Comment: I dont know this formula. I have learnt it:)


How to exclude file from Code Smells in SonarQube?

Question: I am working in Code smells in my project, but here is one class in which i don't want to change anything. This class showing in code smells, I want it should not be show in Code smells.
Using This Property to Exclude that class but didn't work for me
<code>property "sonar.exclusions", "**/*LineChart.java"
</code>
Can anyone please help me on this. How can i exclude this class from Code smells
Comment: can you post your build.gradle
Comment: Were you able to resolve this? I am facing same issue, sonar.exclusions not working for me
Answer: Maybe your class file is in sub package.
This should work:

property "sonar.exclusions", "**/**/*LineChart.java"


Text area com imagem

Question: Olá, vou fazer um form e não sei como fazer para incluir uma imagem dentro da text área, algo desse tipo.
TEXTO

TEXTO
IMAGEM
TEXTO
Algo do tipo para o usuário incluir sabe? Como é feito aqui no stack overflow, para perguntas.
Comment: Uma opção é utilizar um editor do tipo WYSIWYG, como o [TinyMCE](https://www.tinymce.com).
Comment: @AndersonCarlosWoss, responde a pergunta com essa resposta.
Comment: não entendi, teria um exemplo com imagem?
Comment: algo tipo como é aqui para perguntar.
Comment: Queria que o usuário pudesse incluir em qualquer lugar uma imagem, e pudesse logo após continuar escrevendo. Tipo, ele explica algo, e coloca uma imagem pra exemplificar, e continua escrevendo logo abaixo.
Comment: é isso ai que eu queria, muito obrigada!!!!
Comment: Você também poderia gostar de uma div contenteditable https://stackoverflow.com/questions/30279671/how-to-pass-an-image-into-a-html-textarea
Comment: Use o plugin de editor de texto CK editor.
http://ckeditor.com/
Comment: NicEdit: http://nicedit.com bem simples de usar, usei esse, atendeu minhas necessidades.
Answer: O que você deseja fazer é resolvido com editores WYSIWYG (What You See Is What You Get). Um exemplo simples desses editores é o TinyMCE. Para utilizá-lo:

Acesse a URL: https://store.ephox.com/signup/ para criar sua conta;
No menu lateral, acesse API Key Manager;
Copie a chave que aparecer (irá utilizá-la mais tarde);

Para utilizá-lo na página, você pode fazer o download da biblioteca diretamente do site. Aqui utilizarei a versão na nuvem para fins de exemplo. Adicione o arquivo JavaScript tinymce.min.js, informando sua chave da API:

e crie o elemento textarea que deseja configurar como editor. Em seu arquivo JavaScript, adicione o trecho de código que inicializa o editor:
tinymce.init({ selector:'textarea' });

Sobre a utilização de imagens no editor, você pode ler a documentação File & Image Upload.
Veja o exemplo abaixo (não funcional, pois está rodando no Snippet):

tinymce.init({ selector:'textarea' });

<textarea>Seu editor de texto</textarea>

Outros editores semelhantes:

NicEdit: http://nicedit.com
CKEditor: http://ckeditor.com
YUI Rich Text Editor: https://yuilibrary.com/yui/docs/editor/
MarkItUp: http://markitup.jaysalvat.com/home/

Text area com imagem


Why file name and uri of the file in database are different?

Question: I am uploading the files to the folder by using file_save_upload and file_move to achieve this. Its working fine but a problem arises while saving in database.  I have used FILE_EXISTS_RENAME argument, so in file_managed table filename column and uri column file name is not same. In filename column its not appending the integer value, but in uri column its appending the integer value since the file is already exist. Below is my code:
  for ($i = 0; $i < $num_files; $i++) {
      $file = file_save_upload($i, $validators, FILE_EXISTS_RENAME);
      if ($file) {
        $file->status = FILE_STATUS_PERMANENT;
        if ($file = file_move($file, 'public://feed-files/' . $foldername, FILE_EXISTS_RENAME)) {
          $form_state['values']['file'][$i] = $file;
        }
        else {
          form_set_error('file', t('Failed to write the uploaded file to the selected folder.'));
          return FALSE;
        }
      }
      else {
        form_set_error('file', t('No file was uploaded.'));
        return FALSE;
      }
    }

below is the database values:

So how can achieve that filename and uri  column file name should be same. Any suggestions will be appreciated.
Comment: Any particular reason of why you want both to be same?
Answer: The reason for difference is that multiple files with same name can be uploaded in Drupal, so when you upload a file, it adds a counter at the end of filename so that if a file with same name is uploaded again, then it doesn't replace another one.
Also the filename column contains the exact name of the uploaded file as it is used while downloading the file (the file will be downloaded with this name).