Rename Mongo Shard

Question: Can I, and if I can, how can I rename a shard in Mongo?
Like if I wanted to change the instances of rs0 to rep0 below:
mongos> sh.status()
--- Sharding Status ---
  sharding version: {
    "_id" : 1,
    "version" : 4,
    "minCompatibleVersion" : 4,
    "currentVersion" : 5,
    "clusterId" : ObjectId("111111111111")
}
  shards:
    {  "_id" : "rs0",  "host" : "rs0/mongo0a:27017,mongo0b:27017" }
...

I have thought about removing and re-adding the shard, but I'm not sure how I'd do that without having to drain the shard and drop dbs.
Currently 0 of the collections have sharding enabled, I just have a few standalones added as shards.
Thanks
Answer: No, there is no supported way to rename a shard at present, though as you mention you could remove and re-add.  Even then it is not as simple as you might think because although you can specify a name when adding a shard, it does not end there - there is the replica set itself to worry about.  The name specification when adding is just the value of the _id, see the following example (my replica set is rs0, like yours):
mongos> db.adminCommand({addShard : "rs0/host.example.com:27017,host.example.com:27018", name : "rep0"});

mongos> sh.status()
--- Sharding Status ---
  sharding version: {
    "_id" : 1,
    "version" : 4,
    "minCompatibleVersion" : 4,
    "currentVersion" : 5,
    "clusterId" : ObjectId("539838845bc6bf5ee52a56ea")
}
  shards:
    {  "_id" : "rep0",  "host" : "rs0/host.example.com:27017,host.example.com:27018" }
  databases:
    {  "_id" : "admin",  "partitioned" : false,  "primary" : "config" }

Note that all that has changed is the _id for the shard, the "host" value remains the same, because rs0 is the name of the replica set - if you try to use rep0 there it will fail to add.  Hence, all that a remove and re-add will give you is a mismatch between the two names.
To change that host value, not only do you have to remove/re-add the shard, you also have to alter the replica set config before you re-add the shard.  In other words, the replSet parameter must be changed to be rep0 also, and that means re-initializing the set - not an easy task either.
Overall, it is possible to get to where you want, but there will be a large amount of work and it will not be quick (drains, re-init of the set), especially if you have a lot of data.  For the sake of changing a couple of strings, I would generally recommend leaving them as-is.
Answer: This is probably not supported.  However, I have found a way to rename the shards.  Use at your own risk.
Basically, the shard name appears in the config servers in the following collections: config.databases, config.chunks, and config.shards.
Do a simple update to replace the fields that have the old shard name with the new shard name.  You'll have to repeat this on all config servers.  Shut down the shard servers and mongos clients first.  An example is below:
$ mongo <configserver>:<port>/config
configsvr> db.databases.update({primary:'old_shard_name'},{$set:{primary:'new_shard_name'}},{multi:true})
configsvr> db.chunks.update({shard:'old_shard_name'},{$set:{shard:'new_shard_name'}},{multi:true})
configsvr> var temp = db.shards.findOne({_id:'old_shard_name'})
configsvr> temp._id = 'new_shard_name'
configsvr> db.shards.remove({_id:'old_shard_name'})
configsvr> db.shards.insert(temp)

If you are changing the replica set name at the same time, you can modify the "hosts" field of the record in the config.shards collection at the same time.

Rename Mongo Shard


UITableViewCell subclass, drawn in code, animate Delete button in

Question: I'm working on a custom UITableViewCell subclass, where everything is drawn in code rather than using UILabels etc. (This is part learning exercise and partly because drawing in code is much faster. I know that for a couple of labels it wouldn't make a huge difference, but eventually I'll want to generalise this to more complex cells.)
Currently I'm struggling with the delete button animation: how to animate the cell shrinking as the delete button slides in.

Firstly, I am drawing in a custom subview of the cell's contentView. Everything is drawn in that one subview.
I am setting the subview's size by catching layoutSubviews on the cell itself, and doing:
- (void)layoutSubviews
{
    [super layoutSubviews];
    CGRect b = [self.contentView bounds];
    [subcontentView setFrame:b];
}

I'm doing this rather than just setting an autoresizing mask because it seemed more reliable in testing, but I can use the autoresizing mask approach in testing if needed.
Now, the default thing that happens when someone hits the minus is the view gets squished.

I can avoid that by, when setting up my cell, calling
subcontentView.contentMode = UIViewContentModeRedraw;

That gives me the correct end result (my custom view redraws with the new size, and is laid out properly, like the first image I posted), but the animation of the transition is unpleasant: it looks like the cell stretches and shrinks back to size.
I know why the animation is working like that: Core Animation doesn't ask your view to redraw for each frame, it gets it to redraw for the end position of the animation and then interpolates to find the middle bits.
Another solution is to do
subcontentView.contentMode = UIViewContentModeLeft;

That just draws the delete button over my cell, so it covers part of it.

If I also implement
- (void) didTransitionToState:(UITableViewCellStateMask)state
{
    [self setNeedsDisplay];
}

then once the delete button has slid in the cell 'jumps' to the correct size. That way there's no nice slidey animation, but at least I get the correct result at the end.
I guess I could run my own animation in parallel with the delete button appearing, temporarily creating another view with a copy of the image of my view in the old size, setting mine to the new size, and fading between them — that way there would be a nice cross fade instead of a sharp jump. Anyone use such a technique?
Now, you might ask why I can't use the contentStretch property and give it a region to resize. The problem with that is I'm making something to be reasonably generic, so it's not always going to be possible. In this particular example it'd work, but a more complex cell may not.
So, my question (after all of this background) is: what do you do in this situation? Does anyone have the animating delete button working for custom drawn cells? If not, what's the best compromise?
Comment: I got that working, although I don't have the code with me right now. Could you PM me, using my email, so I don't forget to help you out?
Answer: This worked for me finally. in subclass of UITableViewCell
subDrawContentView.contentMode = UIViewContentModeLeft;

overide layout subviews method
- (void)layoutSubviews {

    CGRect b = [subDrawContentView bounds];
    b.size.width = (!self.showingDeleteConfirmation) ? 320 : 300;
    [subDrawContentView setFrame:b];
    [subDrawContentView setNeedsDisplay];

    [super layoutSubviews];
}

Answer: So I will paste the code first and then I will explain:
-(void)startCancelAnimation{
    [cancelButton setAlpha:0.0f];
    [cancelButton setFrame:CGRectMake(320., cancelButton.frame.origin.y, cancelButton.frame.size.width, cancelButton.frame.size.height)];
    cancelButton.hidden=NO;

    [UIView animateWithDuration:0.4
                     animations:^(void){
                    [progressView setFrame:CGRectMake(progressView.frame.origin.x, progressView.frame.origin.y, 159.0, progressView.frame.size.height)];
                    [text setFrame:CGRectMake(text.frame.origin.x, text.frame.origin.y, 159.0, text.frame.size.height)];
                    [cancelButton setFrame:CGRectMake(244., cancelButton.frame.origin.y, cancelButton.frame.size.width, cancelButton.frame.size.height)];
                         [cancelButton setAlpha:1.0f];
                     }  ];
}

-(void)stopCancelAnimation{
    [UIView animateWithDuration:0.4
                     animations:^(void){
                        [cancelButton setFrame:CGRectMake(320., cancelButton.frame.origin.y, cancelButton.frame.size.width, cancelButton.frame.size.height)];
                         [cancelButton setAlpha:0.0f];
                     }completion:^(BOOL completion){
                         cancelButton.hidden=YES;
                         [cancelButton setAlpha:1.0f];
                         [progressView setFrame:CGRectMake(progressView.frame.origin.x, progressView.frame.origin.y, DEFAULT_WIDTH_PROGRESS, progressView.frame.size.height)];
                         [text setFrame:CGRectMake(text.frame.origin.x, text.frame.origin.y, DEFAULT_WIDTH_TEXT, text.frame.size.height)];
                        }
     ];

}

-(void)decideAnimation{
    if([cancelButton isHidden]){
        [self startCancelAnimation];
    }
    else{
        [self stopCancelAnimation];
    }
}

So what I have there is a button that looks like this:

I have an IBOutlet to it. And what I am doing is resizing a UIProgressView and a UITextField (you can resize whatever you want). As for the code is pretty simple, but if you need any help to understand what's going on, please ask. Also, don't forget to add the Swip Gesture to the UITableView... Like this:
    UISwipeGestureRecognizer *gesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipe:)];
    gesture.numberOfTouchesRequired=1;
    gesture.direction = UISwipeGestureRecognizerDirectionRight;
    [table addGestureRecognizer:gesture];
    [gesture release];

Finally the method that does it all:
-(void)didSwipe:(UIGestureRecognizer *)gestureRecognizer {

        if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
            //Get the cell of the swipe...
            CGPoint swipeLocation = [gestureRecognizer locationInView:self.table];
            NSIndexPath *swipedIndexPath = [self.table indexPathForRowAtPoint:swipeLocation];
            UITableViewCell* swipedCell = [self.table cellForRowAtIndexPath:swipedIndexPath];
            //Make sure its a cell with content and not an empty one.
            if([swipedCell isKindOfClass:[AMUploadsTableViewCell class]]){
                 // It will start the animation here
                [(AMUploadsTableViewCell*)swipedCell decideAnimation];
                // Do what you want :)
            }
        }
    }

So as you can see the whole animation is created manually, so you can control exactly what you want. :)


What happens when all the same color balls (solids or stripes) go in on the break?

Question: I played on a pool league (TAP league, 8-ball) a few years ago and some of us pondered what would happen according to the rules if a pool player made either all solids or stripes on the break (but not the 8 ball).
We figured (with our rules anyway), since any balls made on the break does not automatically determine which color you had to make for that game, then you would be forced to go for whatever the other color was still on the table, essentially putting your opponent on the 8-ball as soon as one was made.  I would figure that either player wouldn't want that situation so they would both most likely choose to stalemate (unless a player was confident they could run the table), but I was wondering if there was any precedent or rule for this situation.
Oh yea, and spare me any responses like "It's probably not possible so don't worry about it!".  Just asking out of fun curiosity.
Thoughts?  Stories?  Please share!
Answer: Looking at the rules page of the World Pool-Billiard Association, your understanding is right. For the break, Groups are not yet determined.

3.3 (b) No ball is called, and the cue ball is not required to hit any particular object ball first.

After the break, you can determine your group by calling a ball and pocketing it. But the rules explicitly say that you can't strike the eight-ball when the table is open.

3.4 Open Table / Choosing Groups
  Before groups are determined, the table is said to be "open," and before each shot, the shooter must call his intended ball. If the shooter legally pockets his called ball, the corresponding group becomes his, and his opponent is assigned the other group. If he fails to legally pocket his called ball, the table remains open and play passes to the other player. When the table is "open", any object ball may be struck first except the eight ball.

So your only option would be playing a safety (possibly resulting in a stalemate) or trying to run the table.
Comment: As an even more extreme hypothetical, what would happen if by some strange quirk of fate all seven solids *and* all seven stripes were pocketed on the break?  The table would be open, but neither player could ever have a legal shot.
Comment: Great answer... not just because I agree with it, but also you took the time to post the relevant information from the rule book that the OP was clearly too lazy to do ;)  I do wonder if that has ever happened during a tournament or anything, because I imagine with most of the good pool players I've met I would think they would actually go for the win instead of just going with the stalemate.


Inheriting private members in C++

Question: suppose a class has private data members but the setters and getters are in public scope. If you inherit from this class, you can still call those setters and getters -- enabling access to the private data members in the base class. How is this possible since it is mentioned that a derived class cannot inherit private data members
Comment: A derived class *does* inherit private data members.
Comment: What is even more confusing is that you can override private virtual functions of the base-class.
Comment: And always think a second time when you add getters and setters for attributes: Sometimes they're perfectly fine but other times the work should be done through another, more descriptive, interface.
Comment: @Space_C0wb0y: That's not confusing at all. It's called the Template Method Pattern (which unfortunately has nothing to do with C++ templates)
Answer: A derived class doesn't inherit access to private data members. However, it does inherit a full parent object, which contains any private members which that class declares.
Comment: @user265260: That might work on *your* platform, but it is never **required** to work. Ever.
Comment: Yes, you could manipulate the private data in a hackish, non-portable way using `this` and offsetting accordingly.
Comment: @user265260:  Probably, but why?  That strikes me as a problem just waiting to happen.  Members are private for a reason, and if you can play with their values you can mess up an object.  Moreover, if the layout changes (and it can change between different compiles; an object with a `size_t` member is likely to have a different layout with 32-bit and 64-bit compiles), you're stomping on entirely different data.
Comment: @user265260: For learning what happens "under the hood", the best way would be to fire up your debugger and look at the addresses of the object and its data members. You could also pull up the debugger's "memory" view and see where the data goes in memory. Keep in mind that the behavior you'll see is platform/compiler specific.
Comment: just to poke and hack around, i was just wondering how this is implemented
Answer: It depends on the inheritance type. If you inherit privately, then the derived class does NOT have access to the Base's private members.
Access                      public     protected    private
-----------------------------------------------------------
members of the same class      yes           yes        yes
members of derived classes     yes           yes         no
not members                    yes            no         no

Comment: I think this answer can be misleading or at least inaccurate. @JRL please try to make it more clear.
Comment: This does not answer the question asked.
Answer: Because the getters and setters are public -- they're callable by anyone, not just derived classes.
Comment: Adam wants to keep the keys to his car private, so only he can use them. Even his kids don't have access.

However, if he provides a public get method for his car keys, he's giving the whole town permission to drop by and take his car out for a spin. _Of course_ that includes his children.
Comment: @user235230: "clearly you cannot inherit them"  This is WRONG.
Comment: my doubt is how come you can manipulate the values of the private data members since clearly you cannot inherit them
Comment: and those getters and setters are members of the base class, so they have access to the private data.
Comment: thank you @David this is the thing i needed to convince myself
Answer: They are included, but not inherited. What this means is:

Any inheriting type (: public SomeClass, : protected SomeClass or even : SomeClass, equivalent to : private SomeClass) will not make them accessible from child class methods, or outside (this->a and someobject.a respectively);
They will still be there - take space in memory allocated for child class instance;
Inherited methods will be able to access that private field.

So, basically protected is not visible outside while visible inside and from derived classes (if : private Parent wasn't used), while private is not visible from neither derived classes nor outside of the parent class; it's only visible for parent class' methods, even if they are inherited (but not overrided).
Answer: you can access to them by set access to setters and getters public and  acces to them like that
*.h

class Mamifere
{
private:
    int a;
public:
    Mamifere();
    virtual ~Mamifere();
    int getA();
    // ~Mamifere(); //le delete dans le exp02() affiche seulement mamifere mort :( destructeur de la class mere
    void manger() ;
    virtual void avancer() const;
};

class Deufin:public Mamifere{
public:
    Deufin();
    void manger() const;
    void avancer() const;
    ~Deufin();
};

*.cpp

Mamifere::Mamifere(){
        printf("nouveau mamifere est nee\n");
        this->a=6;
    }

Mamifere::~Mamifere(){
        printf("mamifere Mort :(\n");
    }
void Mamifere::manger() {
    printf("hhhh   je mange maifere %d\n",Mamifere::getA());
    }
void Mamifere::avancer() const{
    printf("allez-y Mamifere\n");
}

Deufin::Deufin(){
    printf("nouveau Deufin  est nee\n");
}
int Mamifere::getA(){
    return this->a;
}
void Deufin::manger() const{
    printf("hhhh   je mange poisson\n");

}
void Deufin::avancer() const{

    printf("allez-y Deufin\n");
}

Deufin::~Deufin(){
    printf("Deufin Mort :(\n");
}

main.cpp

void exp031(){
    Mamifere f;//nouveau mamifere est nee   //   nouveau Deufin  est nee
    Deufin d;

    f.avancer();//allez-y Deufin (resolution dynamique des lien  la presence de mot cle virtual)
    f.manger();//hhhh   je mange maifere (resolution static des lien pas de mot cle virtual)
    printf("a=%d\n",d.getA());//Deufin Mort :(   mamifere Mort :( (resolution static des lien  la presence de mot cle virtual) distructeur de class fille appel auromatiquement le destructeur de la class mere

}

int main(){
    exp031();

    getchar();
    return 0;
}

Answer: Getters and setters do Not give you complete control over private data members. The control still lies with the base class.
Answer: Using the pattern
class MyClass {
  private: int a;
  public: void setA(int x) { a = x; }
  public: int getA() const { return a; }
};

seems object-orientated and has the sent of encapsulation.
However as you noticed, you can still directly access the private field and there is nothing gained over just making a public and accessing it directly.
Using getters and setters like this does not really make sense in C++.
Comment: This question is related to C++ not C#. And a lot of people think it is smart to provide generic getters and setters for integral types - but it is not.
Comment: "Using getters and setters like this does not really make sense in C++.". Allowing unfettered access to data members except through a well defined interface (e.g. getters and setters) makes tracking down errors a nightmare. You need to look at all places where that member is set to try to determine why it has an unexpected value. Restricting access to class members through that well defined interface makes debugging much easier, as you have the stack trace providing some useful insight.
Comment: Actually they do. In C# (for example), if you decided to cache access to `a` here (assuming it actually was a lot of work to calculate `a`), you could just make a a property and you'd be done. However, in C++ you'd have to go and replace all code that references `MyClass.a` with `MyClass.GetA();`
Comment: @andand: Or you could just learn to use your debugger better.
Comment: This doesn't answer the question.  It's just a rant about a personal opinion on programming style (and a factually incorrect conclusion, to boot).

Inheriting private members in C++


Specify the reason for the refusal of publication node

Question: Please tell me whether it is possible to realize the functional moderation node using the Rules and Rules Link modules.
When you click the "Decline", moderation offers fill in the "Cause"?
3 day looking for a solution, shoveled a lot of information already.
Now implemented regular rulesov link "Decline" for no reason.
Comment: It turned out to implement the desired functionality of the module: https://www.drupal.org/project/editablefields dev version.
Couple of scripts to attach a link and everything works like clockwork.
Answer: Looks like you were looking for the editablefields module (and some scripts to attache a link). Here is an excerpt from its project page:

... allows CCK fields to be edited on a node's display (e.g. at node/123), not just on the node edit pages (e.g. node/123/edit). It also works within views etc. Anywhere a 'formatter' can be selected, you can select editable (or click to edit).


What does $cov(x_1,x_2) \gg 0, cov(y_1, y_2) \gg 0$ and $cov(x_1+y_1, x_2+y_2) = 0$ tell us about $x_1, x_2, y_1, y_2$?

Question: I was posed this problem where we know:
$$
cov(x_1,x_2) \gg 0 \\
cov(y_1, y_2)\gg 0 \\
cov(x_1+y_1, x_2+y_2) = 0 \\
$$
What does this tell us about the structure of $x_1, x_2, y_1, y_2$?
Is there any significance to the $\gg$ here? I don't think $\gg$ tells us any additional detail than what $>$ would tell us since covariance isn't normalized. The magnitude of covariance depends on the domain of the random variables, so whether the covariance is much greater than zero or just slightly greater than zero doesn't give us any additional information. On the other hand, if it was instead said that correlation is much greater than zero, which means it's closer and closer to 1, then this could tell us that the 2 variables have a near-perfect linear relationship.
So the best that I think I can say about this is that $x_1$ and $x_2$ are positively correlated and have some degree of linearity, but the strength of their correlation isn't clear. Same can be said for $y_1$ and $y_2$.
$cov(x_1+y_1, x_2+y_2) = 0$ tells us that the newly formed random variables $x_1+y_1$ and $x_2+y_2$ are uncorrelated. They are linearly independent, but not necessarily independent. The way the problem was posed to me seems to be suggesting that $cov(x_1+y_1, x_2+y_2) = 0$ should tell us something about $x_1, x_2, y_1, y_2$, but I can't seem to think what it could be telling us. Any hints?
Comment: $cov(x_1+y_1, x_2+y_2) = cov(x_1,x_2) + cov(x_1,y_2)+cov(y_1,x_2)+cov(y_1,y_2)$. If $cov(x_1,x_2)>>0$ and $cov(y_1,y_2) >> 0$, then we have $cov(x_1,y_2)+cov(y_1,x_2)<<0$.
Comment: Can it have anything to do with highly correlated parameters with opposite signs? They may be correlated but their summation may cancel the relationship between pairs?
Comment: Hmmm I'm not sure, but let me think about that. Why do you say "high correlated?" I don't think we are given that information. I was verbally posed this problem, and I got the vibe that there's something to be said about the original variables $x_1, x_2, y_1, y_2$, when we know that $cov(x_1+y_1, x_2+y_2) = 0$.
Comment: @TimMak Oh I like the use of bilinearity. Although, I'm not sure what information $cov(x_1, y_2) + (y_2, x_2) << 0$ tells us about the 4 random vars.
Answer: $$
cov(x_1+y_1, x_2+y_2) = cov(x_1,x_2) + cov(x_1,y_2)+cov(y_1,x_2)+cov(y_1,y_2)
$$
If $cov(x_1, x_2) \gg 0$ and $cov(y_1, y_2) \gg 0$, then we have $cov(x_1,y_2)+cov(y_1,x_2) \ll 0$.
If $x_1,x_2,y_1,y_2$ are all standardized, however, then supposing both $corr(x_1, x_2)$ and $corr(y_1, y_2)$ are close to 1, then it follows that $corr(x_1,y_2)$ and $corr(y_1,x_2)$ are both close to -1. Moreover, to ensure that the correlation matrix of $(x_1,x_2,y_1,y_2)$ is semi-positive definite, then $corr(x_1,y_1)$ and $corr(x_2, y_2)$ must be close to -1 also. An example is the following,
$$
Corr \begin{pmatrix}
x_1\\ x_2\\ y_1\\ y_2
\end{pmatrix} =
\begin{pmatrix}
1 & 0.99 & -0.99 & -0.99 \\
0.99 & 1 & -0.99 & -0.99 \\
-0.99 & -0.99 & 1 & 0.99 \\
-0.99 & -0.99 & 0.99 & 1
\end{pmatrix}
$$
Answer: One thing we learn is that the $y$-variables cannot be deterministic linear functions of their respective $x$- variables (and vice versa).
Assume, towards a contradiction that $y_1 = ax_1$, $y_2 = bx_2$ with $a\neq -1, b\neq -1$ (to avoid trivialities). To satisfy the second pair-wise positive covariance assumption we have also to assume that $a,b$ have the same sign (both positive or both negative), to obtain ${\rm Cov}(y_1, y_2) > 0$.
But then
$$0= {\rm Cov}(x_1+ y_1,\, x_2+y_2) = (1+a)(1+b){\rm Cov}(x_1,\, x_2) \neq0\;: {\rm contradiction}$$
Realistically I would extend this negative result (as "in general we cannot say that...") to stochastic linear functions (i.e. $y_1 = ax_1 + v$, $y_2 = bx_2 + u$) because then, in order to obtain the zero-covariance premise we would have to assume special structure for the newly arrived variables.


Ordinal Regression: Python vs. SPSS

Question: I need some help understanding the coefficients produced by Python (Statsmodels) for Ordinal Regression vs. SPSS.  I ran the same exact data set in both SPSS and Python, but received different output for the coefficients.  The coefficients for each ordinal level are shown below.  I'd like to reproduce exactly what SPSS generated with Python, but I cannot understand what Python is doing differently.  FYI - there is only 1, continuous IV in the model. The DV is an ordinal variable with 6 levels.
SPSS:
0: .541
1: 2.644
2: 3.442
3: 4.117
4: 4.912
ind_var: .467
Python:
0: .541
1: .743291
2: -.2248
3: -.39435
4: -.22837
ind_var: .467
*Notice how the coefficient for the first level is the same for both Python and SPSS (.541), which leads me to believe that I should be able to "convert" these coefficients to be the same values as SPSS.
Here is the Python code, just in case anyone wants to try.
from statsmodels.miscmodels.ordinal_model import OrderedModel
import pandas as pd
from pandas.api.types import CategoricalDtype
import numpy as np

df = pd.read_csv("raw_data.csv")

cat_type = [0, 1, 2, 3, 4, 5]
df['dv_cat'] = pd.Categorical(df['dv'], categories=cat_type, ordered=True)

def or_regress(data):
     or_model = OrderedModel.from_formula("dv_cat ~ iv_variable", data, distr='logit').fit(method='bfgs', disp=0)
     print(model.summary())
     return or_model

model_result = or_regress(df)
model_result.params

here is the same for SPSS:
PLUM dv WITH iv_variable
/CRITERIA=CIN(95) DELTA(0) LCONVERGE(0) MXITER(100) MXSTEP(5) PCONVERGE(1.0E-6) SINGULAR(1.0E-8)
/LINK=LOGIT
/PRINT=FIT PARAMETER SUMMARY.
Answer: The Python coefficients are the logarithms of the differences in the SPSS coefficients, so
0.541+exp(0.743291) is 2.643
0.541+exp(0.743291)+exp(-0.2248) is 3.442
and so on. This parametrisation ensures the thresholds are increasing.
Comment: Thank you, Thomas!  Very much appreciate the fast response!

Ordinal Regression: Python vs. SPSS


Does the audio an instrument emits above 20 KHz affect how the instrument sounds?

Question: It's commonly held that humans can hear sounds in the range 20 Hz - 20 KHz.
But most acoustic instruments will emit sounds outside that range, for instance breath sounds from flutes and recorders, bow noise on bowed string instruments, plucking noise on plucked string instruments, and so on.
One strand of reasoning says that if an instrument produces sounds with components above 20 KHz then they're inaudible and so don't really matter.
But is that true? Does the ultrasonic part of an acoustic instrument's spectrum affect its perceived sound?
I'm specifically asking about acoustic instruments and what it's like to be in the same room as that instrument as it's performed. I'm specifically not asking about audio recording/storage/replay, as that's a whole subject on its own.
This question was prompted after hearing a program
Costing the Earth
on BBC Radio 4 last night which reported that in the rainforest there's significant ultrasonic sound and that's why we feel better there than in the urban environment.
Subsidiary Question
Seems no-one has the answer at their fingertips. I've been wondering what experiment would answer this question?
Comment: Do bats flying by outside keep you awake? I'm sure this could descend rapidly into a deep philosophical discussion ;)
Comment: @Tetsujin - not often, but bats *inside*...
Comment: For a single instrument, the constructive interference would already have happened and the audible frequency would be there. I'm a bit skeptical about the idea that the ultrasounds from several different acoustic instruments would interfere to produce audible sounds or that those sounds would be musically significant.
Comment: What about constructive interference? Could two ultrasonic frequencies combine to generate a sonic one? Maybe? Though, as noted in some other answers, this gets messy because you're asking about actual acoustic instruments. Their waveform is so complex, and there are so many individual sound sources going on (as you noted—breath, string sounds), that's it's very hard to parse which frequencies are "affecting" which others.
Comment: @ojs well, the interference and distortion may occur inside the ear... also _some_ young people do hear above 20 kHz.
Comment: @ojs I'm referring to intermodulation distortion. _If_ there is some distortion occurring between the speaker and the hair cells, it may result in production of frequencies in the audible range from ultrasonic sounds. The comment about young people hearing range was unrelated, directed to Brian. Sorry for the confusion. Anyway, I'm not making any claims it's a good reason to work with higher bandwidth, otherwise I'd write an answer.
Comment: @user1079505 did I write something about distortion or some young people? It would also be interesting to hear what you think interference means.
Comment: "*humans can hear sounds in the range 20 Hz - 20 KHz.*" They *can*. It doesn't mean that they do and in my experience most do not, especially once you get past the teen years. You're lucky if you can hear up to 15kHz. But I think your question might have too many confounding factors to be answered. For example, if you restrict things to only live performances, how do you make a comparison? With a identical version of the instrument that is only different by being magically band-limited?
Comment: It'd be a whole lot easier and more consistent to take people with limited range of hearing and play the same recording with different equalizer settings to them. I've done this and can hear no difference.
Comment: First thing that comes to mind would be potential sympathetic resonance.
Comment: Audible / inaudible to whom (and what)?  At one company, someone shorted out a laptop switching supply they were working on.  About 10% of us were walking around with hands clamped to our heads to stop the piercing, painfully LOUD, icepicks-in-the-ears sound, while everyone else worked on, oblivious.  He decided he believed us after it swung the needle on a sound meter he had.
Comment: Brian, this is a controversial issue that nobody knows the answer to, and is debated.  It would be like asking "what is dark matter" on the physics site .. you know what I mean?
Answer: As far as I know up to this point there is exactly 0 scientific indication that any human will perceive music differently due to ultrasonic sound content, no matter what turntable producers want to make you believe.
High frequencies of certain parts of instruments might affect the sound due to non linearity. E.g. an Aetherophone uses a very high frequency oscillator mixed with a second high frequency oscillator, which produced the difference frequency which might then be audible.
But generally this will rather affect low frequencies than high ones, as high frequencies experience more dampening, and less effects will actually result in an audible distortion.
But the high frequencies actually emitted by the instrument – most likely no.
Comment: @ojs The benefit of slightly higher sampling rate than necessary is to give more head space for the necessary low pass filter, required to avoid quantization noise. Having a few KHz more space for your low pass filter to operate may in fact make an audible difference. But this question is *not* about digital audio.
Comment: I agree that ultrasonic content in the air has no affect when it's heard by a human. It's possible that ultrasonic signal levels in audio electronics could contribute to intermodulation distortion and generate new non-ultrasonic artifacts. But I wouldn't expect that to be a factor 99% of the time and only a very minor factor that other 1% of the time.
Comment: The more technically minded audio marketing people usually claim that the benefit of higher sample rates is that filtering artifacts are shifted outside the hearing range.
Comment: @ojs Bit depth is a result of quantization along the elongation dimension, sample rate a result of quantization along the time dimension. The first leads to noise in the sense of rounding error, the second leads to noise in the sense of nonuniqueness of representation for not rate/2 bandwidth limited signals.
Comment: @Lazy I agree that the question is not about digital audio but the subject often comes up with these unusually high sample rates, and usually it's not about few KHz but twice or four times the usual rate. Quantization noise however is related to bit depth, not sample rate. Steep lowpass filters have different problems.
Comment: @Lazy "quantization along the time dimension" is usually called just sampling, and the "the nonuniqueness of representation" is known as warping effect. If you use the standard terminology you'll find a lot of information and might learn how the filtering is involved.
Comment: @ojs Call it what you will, but what makes you believe I'm looking for information here? It is you who brought up this topic under my answer.
Comment: @Lazy well, you brought up the subject of turntables and it seems that you're a bit confused about digital audio so it might be a good time to learn.
Comment: @ojs Why should I be confused about digital audio? Because I do not use the terminology you prefer? Turntables have nothing to do with digital audio, it's just that the supposed benefits of ultrahigh frequency range are usually advocated by either turntable fanatics or people selling suff for turntable fanatics (of course completely ignoring that anything from a PVC disc above 14KHz is simply distortion).
Comment: **Comments have been [moved to chat](https://chat.stackexchange.com/rooms/145001/discussion-on-answer-by-lazy-does-the-audio-an-instrument-emits-above-20-khz-aff); please do not continue the discussion here.** Before posting a comment below this one, please review the [purposes of comments](/help/privileges/comment). Comments that do not request clarification or suggest improvements usually belong as an [answer](/help/how-to-answer), on [meta], or in [chat]. Comments continuing discussion may be removed.
Answer: As most of what we hear of other people's instruments is from a recording, most of this becomes moot anyway.
If you're in the room listening, you're still not hearing what the mic hears. Just try standing near a drum kit in a recording studio, then comparing it with what the control room hears for an extreme example.
Don't try this at home - by putting your ear 1" from the snare head, you'd get what the mic gets… except the mic won't even blink at those SPL levels [120 - 140 dBSPL potentially]. You, on the other hand, will suffer at least some temporary, it not permanent, hearing loss & will have experienced more pain than 'hearing'.
If you've got a violin on your chin, then half of what you hear is distortion in the nearest ear - you don't notice it because you're used to it. If you're trapped in a small room with one, it makes your teeth squeak.
So… where do we measure this possible high frequency 'interference' that we may or may not be able to perceive? Inside the instrument, 1/2" from it, far enough away that we're getting a good amount of room reflection in it, outdoors, in an anechoic chamber? Take your pick.
My best, flattest mic [so good they took one to Mars in 2020 to capture sound, I kid you not] is only good from 20 - 20kHz. You can get mics that go higher, but they tend to be for specialist use, not for music.
Comment: @Clockwork - the numbers will likely be skewed from regular extrapolation by the fact that the ears can 'relax' to protect themselves, up to a point. I honestly don't know any exact figures for anything like that. I do know every time I hit the snare in a rehearsal room, everybody but me blinks. That continues until everybody else is playing, by which time, they all 'got used to it'.
Comment: You mention a lot about mics, recording, which OP states isn't part of the equation here.
Comment: @Clockwork - you're just replacing one bit of hand-waving with another. It makes no difference whatsoever what the sound is, your ears just naturally compress the sound & de-sensitise after a while. If I were a doctor, I'd know what it's called. I'm not… & I don't ;)
Comment: My entire answer questions the circumstance under which this may be perceived, quite specifically. The OP's question is so general as to be almost unanswerable - as we see from the myriad attempts to answer small sub-sets of the overall theme. The entire second half of the question was added after many of these answers were written - moves the goalposts entirely. My personal take on all this is highly dubious, involving psychoacoustics.
Comment: Without detail of their experimental method, I would question anything that just bluntly claims, rainforest makes you feel good because of the ultrasound. Without significant double-blind tests, removing other senses, then it's no better than the simple statement 'people feel better in the woods than they do in an urban jungle surrounded by noisy people & lots of traffic.'… which I'd easily accept as true, though you'd probably still feel that way with your fingers in your ears; so long as it wasn't pi**ing down with sideways rain & 6°C.
Comment: I remember reading somewhere that the human ears can withstand continued noise at 85 dBA for 8 hours straight before suffering hearing loss (which may or may not be perceptible). Then they went on to add that the duration decreases by half that value by increasing the noise by 3 dBA (aka. a twice louder noise). Since I was bored, I came up with a graph which says: at the range of  120-140 dBA,  you have between 7 and 0.1 second before suffering permanent hearing loss; although some said that beyond 130, it doesn't matter how long you are exposed anymore. Sorry, spent too much time at the range
Comment: @Tetsujin I believe you but also wanted to add that, in some case, when you feel like your ears are "getting used to it", it's actually just suppressing the pain to make it more bearable (at least when it's way too loud). In your case though, I believe it was probably fine since it's "just" musical instruments.
Answer: Simple answer, most likely not - to humans.
There must be many, many sounds out there that are sounds, but are inaudible to humans. Most, it figures, we are unaware of, for obvious reasons. Dog whistles, for example. We know they work, as they have an effect on dogs, but we're blissfully unaware of the racket they make to dogs!
As we know, most instruments will not only produce the fundamental sound of a note, but varying degrees of its harmonics. An interesting point would be how that sound (due to its harmonics) would be 'heard' by different individuals. Some time ago, I built a speaker cab with an 18" speaker and a horn tweeter. The band members could hear the white noise emanating from the tweeter - I was blissfully unaware! So we heard the sound even when notes were played, in different ways.
So, basically, no, and speakers, headphones, et al, which are said to reproduce sounds outside the human hearing range may well do so, but they're as much use as the anti-elephant paint on my chimney pot...
Answer: There's some evidence that ultrasonic frequencies are in fact audible!
https://en.wikipedia.org/wiki/Ultrasonic_hearing
But I think most arguments for reproducing frequencies above 20Kz come from the fantasy world of Russ Andrews.
https://www.russandrews.com/
There's also the issue of what happens when you sample with a Nyquist frequency TOO close to the top of audible range. There's no true 'brick wall'   filtration.
Comment: @PhilFreedenberg - Russ Andrews sells snake oil to gullible 'audiophools'. I didn't find these jet engine examples, but a) do you know what they were recorded with & the audio spec right through, & b) were you listening on monitors capable of better than 20kHz at the top, from an appropriately high-rate source? A late c) have you ever had your hearing tested to know what range they currently have? btw, you can fake this stuff for the gullible in several ways -  by squeezing cut off filters really, really close to nyquist or vice versa, so there's aliasing right at the very top of the range.
Comment: @PhilFreedenberg Was this a blind test?
Comment: I once listened to a simulation of the sound of a jet engine with and without its ultrasonic frequencies, and could clearly hear the difference. Ultrasonic frequencies made the sound more realistic.
Answer: One can start with the fact that the nominal 20kHz limit is somewhat different between individuals and some (esp. younger ones) are sensitive to a kHz or two above 20.
Could this make difference exactly in regard to music is an open question.
I personally can hear up to e.g. 15kHz, but cannot really distinguish the pitch of a single tone between 7kHz and anything above. It may be generally impossible or a matter of training, I don't know. Even if it is a matter of training, probably few people will have it.
On the other hand, human ears (and the processing circuity between them) are known to be non-linear in a number of ways.
Loud sounds (and even not so loud ones) are known to alter the sensitivity of the ear outside of the sound's own spectrum, so e.g. an ultrasonic beat could leave auditory artifacts over the usual, audible sound.
Again from personal experience, the ultrasonic rat repellents (be damned whoever invented them) make me almost deaf even if set at frequencies that I am unable to hear.
In short, one can hear artifacts of an ultrasound even if unable to hear the ultrasound itself. The effect is small and I think it will be cruel to the listeners to use it even if possible.
Comment: With such a 'precision' device as a rat scarer, it's quite likely the cheap circuitry or even the speaker itself is subject to modulation dropping into human-audible territory.
Comment: Hell yeah, some of them do, but my comment is about the non-audible frequencies that still have audible (over some other sound) effect.
Comment: You're not hearing the 'well out of range' sound, what you're hearing is 'interference', lower frequencies caused by cross-modulation or resonance. You'd hear this even on a limited frequency recording.
Comment: Whatever the interference is, it happens in my ears - up to not understanding a normal speech - without hearing the ultrasound itself.
Comment: Have you tried recording it?
Comment: No. I try to avoid even staying there.
Comment: Then we'll never know…
Answer: It is possible to hear ultrasonic sound under the right circumstances, essentially if you have interfering ultrasound waves that generate beats at a lower frequency. This can be used to transmit audible sound directionally, some key words are "parametric speakers", "audio laser" and "beam forming".
As explained on directional-loudspeakers:

The speaker array actually produces a modulated wave made of two separate ultrasound waves. One of them is a steady, reference tone of a constant 200,000 hertz (Hz) frequency (the carrier wave) and the other is the signal that fluctuates between 200,200 Hz and 220,000Hz (the modulating wave). Although they're combined, it's easiest to think of them as two separate waves traveling out in parallel straight lines through a column of air without overlapping. If they meet an obstruction (such as your curious head), they suddenly slow down and mix together so they interfere constructively (by adding together) and destructively (by subtracting from one another). By the principle of wave superposition, two ultrasound waves of those frequencies can subtract from one another to produce a third wave with a much lower frequency in the range 200–20,000 Hz—and that's in the frequency range that your ears hear.

Could it be that interferences of ultrasound waves therefore effect how a music instrument sounds? I think so.
Can it be experimentally tested? It is tricky, as in the explanation above: As soon as these interfering ultrasound waves hit an obstacle (such as an eardrum or a microphone) they turn into regular sound waves, so even if you record a full audio spectrum from 16Hz to 200 kHz, these would be recorded at the lower interference frequency. Therefore filtering out the high frequencies would not change that. What should be possible, at least in theory: Record only the ultrasonic part of the spectrum (or record the full spectrum and filter out the audible frequencies) and play it back. Whatever is audible then would be the contribution of the ultrasound frequencies to the sound of the instrument. Whether or not that is technically feasible, I don't know.
Answer: I find the question VERY theoretical. The given frequency range is just the extension of the sequence of harmonics, which will surely be influenced by any constructional modifications you may attempt to strenghten or weaken the supersonic parts. But with  changes already in the easily hearable harmonics, how to decide (beyond recording/low-pass filtering which may have more impact than the effect you are searching for)?
Comment: Perhaps theoretical, but well-established theories based on a long history of experimental science.
Comment: When does supersonic regime come into effect? Honest question difficult to find answer.
Answer: Not in any direct sense, but there's an indirect sense where it might matter: all of the sound (audible and inaudible) is physical movement, and all of it is energy given up to the atmosphere by the instrument. So if you were to take an instrument and modify it to make more or less ultrasound, you might find that doing so alters the timbre of the instrument in ways that you wouldn't expect from a simple analysis.
The tension on a drum's head could evolve differently, giving it a different "note" and a faster or slower decay. The distinctive sound of bells and gongs is caused by the amplitudes of a large number of different resonances evolving over time (transferring energy between each other) after the instrument is struck, and any ultrasonic resonances would have an effect on that. A bowed instrument might exhibit a different amount of friction between the string and the bow. And so on: musical instruments are complex and nonlinear.
I'm not qualified to say whether any of these effects are significant — I'm not an expert in the field and I would love to hear from someone who is — but I would be very surprised if none of them were.
Answer: I would say yes and no. If there is an ultrasonic frequency or fundamental, it would have harmonics which you will hear because of the ultrasonic part. However that sound can be produced with out ultrasonic wavelengths. So it's still sub 20khz that you hear. But higher then 20 kHz still effects and resonates with lower frequencies and produces new sound you will hear but in the sub 20 kHz region and so these harmonics do not require super 20 kHz fundamentally but are naturally produced by them where there is harmonics.
So I think in working reality the simplest answer is yes. They can definetly effect the sounds you hear though you can not hear them alone.
Further if the given the ultrasonic frequency, frequencies which divide the ultrasonic frequency, will have a harmonic and the amplitudes will be effected at a given frequency which divides the ultrasonic frequency. You may hear this lower frequency that divides the ultrasonic frequency get changed. All the common divisors will be effected. But because the high frequency happens more times per second, it will have smaller and smaller effect as the area of the amplitude of the wave gets smaller and smaller. There is less power per amplitude.
So you would think that these ultrasonic waves probably in natural occurrence become less and less important in the sound we hear. But with digital audio or anything specifically designed to utilize these ultrasonic regions to hit harmonics, they certainly can have hearable effects.
It is also interesting that because you can not hear these frequencies on their own they can be used to construct harmonics, that can't be constructed and sound the same- as with waves using audible wave lengths.
Thus ultrasound is not totally insignificant, in sound and music.
Comment: I find it difficult to follow your argumentation. Much of what you're writing seems circular / begging the definition, or simply unsupported claims of dubious veracity.
Comment: Ultrasonic frequencies DO factually effect audible sounds via harmonics. That is fact. However when the wave as a total is broken down to its constituent frequencies, the ultrasonic part can be removed and no difference would be heard.
Comment: So in the non analog and digital world. Using various instruments or machines  say a violin and a dog whistle. You should be able to get harmonics which you hear, IN THEORY.
Comment: The issue is this is best to understand with science and Laplace transform however with out that music theory etc and natural music does not typically cover these areas. Science deals with waves and hence Laplace transform a lot. This question is precisely analogous to many physics and engineering concepts. Be it light waves, sound waves, it all is modeled by the same math and science. Which is quite common for physics etc. And this question quite easily decided with a YES.
Comment: Basically the laplace transform takes any crazy repeating wave like a real sound wave, and tells you the frequency spectrums which are present. The frequencies can all be added up or these many sound waves of different frequencies mix together and produce the original wave.
Comment: So superposition or adding and canceling of waves and the laplace transform are the key things which make this question easily answered.
Comment: This still doesn't make any sense. Laplace / Fourier transforms are used and useful of course, but they're only linear decompositions. I.e. phenomena where the constituents individually are inaudible but their sum is audible can _not_ be captured by them. It's true that such phenomena (intermodulation) nevertheless are possible, because no speaker or microphone or ear is perfectly linear, but Laplace transform is very badly suited for describing that. Generally speaking, the linear approximation works well at low volume and gets worse at very high SPL.
Comment: I think it is clear that ultra sound can produce audible effects. Ultimately because of the way waves add and subtract or superimpose. If an audible wave's frequency divides the ultrasound wave's frequency, it will have an audible frequency effect on the amplitude of the audible wave.
Comment: Perhaps you're referring to the fact that a signal with ultrasonic components can have a higher peak-to-peak amplitude than its bandlimited version. They'll still sound indistinguishable though. Peak amplitude is generally pretty irrelevant for audio, it can also vary simply based on phase shifts. It can even _increase_ when you remove frequency components. This only stops being true as you go to very high sound pressures, because then the linearity condition breaks down.


Connecting to server via VPN

Question: There is a server with connection via VPN to it (using GRE protocol). I have got a problem to connect to this VPN from home network, because GRE is not allowed by provider. But I have got another work server (with SSH connection to it from home) in other network from which I can connect to server in VPN. Is there any way to make tunnel to connect from home to VPN-server through work-server? SSH connection is anouth for me. Home computer and work-server have ubuntu operating system, vpn-server is under centos.
Answer: That is definitely possible. As you are telling that you need an SSH only, probably the most easy way would be to set up a GRE connection from your "another work server" (let's call it Server B) to your first server which accepts GRE (calling it Server A). Once you've done it and it can SSH from Server B to Server A you can just chain it from your home. I.e. first connection to Server B SSH and then just SSH to a Server A from there.
If you would like to have SSH connection without that chain, you have to set up some sort of routing and/or port forwarding (NAT) on the Server B. Exact configuration are greatly dependent on your configuration and would be out of scope of this question.
Answer: Once you can reach the work server you can easily do that.

Assumption for the example

source system (at home) : 10.0.0.1
work system (jump server) : 10.0.0.2 (ssh is running on standard port 22/TCP)
destination server : 10.0.0.3 (ssh is running on standard port 22/TCP)

port forward via server B

With opening the ssh tunnel you can set local port forward (-L [<local_addr>:]<local_port>:<remote_addr_to_forward_to>:<remote_port_to_forward_to> ). Then you can open another ssh connection pointing <local_addr> but with parameter -p <local_port> or the first tunnel. With this configuration:

the first tunnel have to be up to the rest is working
you can have more connection over the first tunnel (more ssh connections, scp connection,...)

(1) ssh -L 10022:10.0.0.3:22 10.0.0.2
(2) ssh -p 10022 127.0.0.1
(3) scp -P 10022 <local_file> 127.0.0.1:<destination_file>

+-----+        +-----+        +-----+
|  A  |=== 1 ==|  B  |        |  C  |
|     | -- 2 - | -2- | - 2 -> |     |
|     | -- 3 - | -3- | - 3 -> |     |
|     |========|     |        |     |
+-----+        +-----+        +-----+
10.0.0.1       10.0.0.2       10.0.0.3

native ssh connection using "native" jump host

ssh offer "native" support for this kind of connection using -J <destination> parameter. For the specification of destination is recommended to use config (~./ssh/config) file.
The example of the code would be (the outer connection is "transparent")
(1) ssh -J 10.0.0.2 10.0.0.3

+-----+        +-----+        +-----+
|  A  |========|  B  |        |  C  |
|     | -- 1 - | -1- | - 1 -> |     |
|     |========|     |        |     |
+-----+        +-----+        +-----+
10.0.0.1       10.0.0.2       10.0.0.3

Connecting to server via VPN


PHP http handling

Question: Is there a way to prevent a php script from sending a http response when the script is finished executing? If not in php is it possible in any-other common web scripting langues?
Comment: ...just don't echo/return anything?
Comment: could you give more details of what you're trying to achieve?
Comment: What would you want to happen instead? Let the browser hang there wasting one of its TCP/IP threads waiting for a response until the connection times out?
Answer: I believe that would be something controlled by the web server, not the scripting language.
Comment: Agreed. PHP just terminate the script. Then Apache replies back to the client to send "no data" in addition to a header 200 OK.
Answer: assuming no headers have been sent, just
die();
Answer: No, but you can send a http 204 (No Content).

PHP http handling


Visual Studio 2012 becomes corrupt when installing WiX 3.8.

Question: Visual Studio 2012 becomes corrupt when I tried to install WiX 3.8. This is what happens...
Following a successful WiX install I try to run VS2012 and get the splash screen followed by this error "Exception has been thrown by the target of an invocation". Clicking on ok simply places me on the desktop. The only solution is to re-install VS2012. I tried un-installing everything and starting over several times but no luck. I cannot find any information on this exact topic anywhere online including WiX forums. Does anyone have ideas on what I should try next?
Rudy
Comment: I've been running 3.8 with VS2012 for a while without trouble. I haven't heard of this problem before, so here are just a few things to consider/verify if you haven't already. (1) Make sure you are using the latest stable vesion of 3.8. (2) What other plugins are installed in Visual Studio? (I use Productivity Power Tools, Style Cop, and Resharper without any problems.) (3) Perhaps try a Repair on Visual Studio after the WIX 3.8 install? (4) Does anything show up in your Event Log when Visual Studio crashes? (5) Which VS2012 - Professional, Express, etc?
Answer: I just had the same problem after installing WiX 3.8. Basically even more problems as Explorer and other system application could not be started anymore.
The root cause was a change in the PATH environment variable which ended up to be more than 2048 chars and therefore the %windir% var was not accessible anymore.
Try to remove some unnecessary paths in PATH environment variable as described here:
https://superuser.com/questions/355594/windows-7s-path-and-environment-variables-are-corrupted
At least for me, it worked afterwards again.
Cheers and good luck


How to Reset Unifi APs over SSH?

Question: I want to Reset APs or switches over the Build-in SSH. I do no find a working anser since this is just turning the APs of.
Answer: After searching for some time i found this article which had an expanded command on doing it.
For those who don´t need the whole explanation, the Command is as follows:
<code>syswrapper.sh restore-default & set-default &
</code>

How to Reset Unifi APs over SSH?


Not able to "Run As" any application on a server in the TRUSTING domain using an account from the TRUSTED domain

Question: There are two domains: "dom1" and "dom2".

"dom1" is the trusting domain.
"dom2" is the trusted domain.

I.e. there is a one way trust where domain "dom1" trusts domain "dom2".
Servers joined to domain "dom2" and logged in with an account in the "dom2" domain, can access file shares on servers joined to the "dom1" domain. No issue here.
However, on a server joined to the "dom1" domain (server name: myserver.dom1.com) and logged in with an account in the "dom1" domain (logged into the server using dom1\myuserondom1, it is not possible to run an application using "Run as different user" and using a user account on the "dom2" domain (example: using an account such as dom2\myuserondom2)
When attempting to do this, the error below is shown:
There are currently no logon servers available to service the logon request

On myserver.dom1.com, if I do nslookup dom2.com it returns the name servers correctly.
On myserver.dom1.com, we are not able to add dom2\myuserondom2 to any local groups.
Comment: From myserver.dom1.com run: `nltest /dsgetdc:dom2.com`
Comment: @GregAskew This returns the following message: `Getting DC name failed: Status = 1355 0x54b ERROR_NO_SUCH_DOMAIN`. The domain name was entered correctly and I did use the FQDN to test this as well.
Comment: Run PortQueryUI from myserver.dom1.com against dom2.com.
Comment: @GregAskew Should I do `Service to Query` = `Domains and Trusts`?
Comment: Yes, domains and trusts.
Answer: Unless I'm thinking about this wrong I don't think this particular scenario should work to begin with. DOM1 trusts DOM2 but DOM2 doesn't trust DOM1. You're trying to use runas as a DOM2 user from a DOM1 computer. That should mean that in order to authenticate the DOM2 user the authentication request has to flow from DOM1 to DOM2, and since DOM2 doesn't trust DOM1 it fails. No?
A DOM2 user can't be authenticated by a DOM1 Domain Controller. A DOM2 user has to be authenticated by a DOM2 Domain Controller. The authentications flow tells me that this shouldn't work.


Cisco unity call manager -- personal greeting error enabled

Question: In Unity CM 8.6.1, one user's personal greeting settings show the Error greeting is enabled. I cannot disable it. I also cannot enable the standard greeting. Calls for this one user do not go to voice mail. The phone just keeps ringing.
I enabled the Alternate greeting to see if this would allow me to clear out the error but it did not work. How can I fix this?
Note, I am unable to enable the standard greeting. The error greeting is not the issue.
Answer: DISCLAIMER: I'm quite new to CUCM/CUC
I don't think you can disable/enable either the standard or error greetings...they are part of the system.  You can modify the standard greeting with whatever personal message you want though.
That said, if the calls aren't going to voicemail at all, then I believe CUCM isn't handing them off to Unity.
Look in the line properties of the user's phone as shown below:

Make sure the appropriate choices for that user are checked.
Comment: Facepalm. All those settings were unchecked. Thank you.
Comment: Nice! (not for you...just happy I actually knew the answer since I'm learning it as I go)


Is $f(z)=z^n$ holomorphic?

Question: Is $f(z)=z^n$ holomorphic?
I have tested a number of other functions using the Cauchy Riemann equations $u_x=v_y$, $v_x=-u_y$. However in the case of $f(z)=z^n$ I cannot think of a way to find the functions $u(x,y)$ and $v(x,y)$ without using a binomial expansion of $(x+iy)^n$.
Any help or pointers is appreciated.
edit - the problem requires the use of the Cauchy - Riemann equations and not the formal definition of complex differentiation.
Comment: What's wrong with using the binomial theorem?
Comment: The exercises the problems are from requires the use of Cauchy Riemann equations, so I have been staying away from the formal definition for now
Comment: What definition of holomorphic function do you know?
Comment: If you want to avoid using the Binomial Theorem, then you can use the Product Rule. Start with $ f: z \mapsto z $, which is holomorphic. Then $ g: z \mapsto z^{2} $ is the product of two holomorphic functions, and so by the Product Rule, it is holomorphic. This is essentially the start of an induction argument.
Comment: @BerrickFillmore see also my answer below.
Comment: Please define $n$.
Answer: The easiest way is just the definition
$$\lim_{z\to a}{z^n-a^n\over z-a}=\lim_{z\to a}(z^{n-1}+az^{n-2}+\ldots +a^{n-2}z+a^{n-1})=na^{n-1}$$
by definition, since $a$ was arbitrary, the derivative exists at all points, $a\in\Bbb C$.
Comment: Are you assuming that n>1?   If, for example, $n = -1$, then, the limit does not exit at the origin. So is $z^{-1}$ holomorphic?
Answer: HINT: Show that if $f=u+iv$ and $g=\hat{u}+i\hat{v}$ satisfy the Cauchy-Riemann equations, then so does $fg$. Use this together with the fact that $z^n$ is a finite product of holomorphic functions (since $z$ is holomorphic).
Comment: Yep! I endorse this.
Answer: Consider the function $f(x,y)=(x+iy)^n$. Then the real and imaginary parts of this function are
$$
u(x,y)=\frac{1}{2}((x+iy)^n+(x-iy)^n)\\
v(x,y)=\frac{1}{2i}((x+iy)^n-(x-iy)^n)$$
so
$$
\frac{\partial u}{\partial x}=\frac{n}{2}((x+iy)^{n-1}+(x-iy)^{n-1})
$$
whereas
$$
\frac{\partial v}{\partial y}=
\frac{n}{2i}(i(x+iy)^{n-1}+i(x-iy)^{n-1})
$$
Verify also the other Cauchy-Riemann equation.
Is this legitimate? Yes, of course. We're just considering functions $\mathbb{R}\to\mathbb{C}$ and derivatives are perfectly defined as usual, with the usual properties.

If you don't trust this (but you should), you can do a proof by induction. Denote by $u_n(x,y)$ and $v_n(x,y)$ the real and imaginary parts of $f(x,y)=(x+iy)^n$. Then
\begin{align}
u_n(x,y)+iv_n(x,y)&=(u_{n-1}(x,y)+iv_{n-1}(x,y))(x+iy)\\
&=
(xu_{n-1}(x,y)-yv_{n-1}(x,y))+i(xv_{n-1}(x,y)+yu_{n-1}(x,y))
\end{align}
So
\begin{align}
u_n(x,y)&=xu_{n-1}(x,y)-yv_{n-1}(x,y)\\
v_n(x,y)&=xv_{n-1}(x,y)+yu_{n-1}(x,y)
\end{align}
Compute the partial derivatives and apply the induction hypothesis.

Is $f(z)=z^n$ holomorphic?


Is learning Drupal 7 a bad option now after release of Drupal 8

Question: Hi I am WeB developer and have recently started  learning drupal 7.
I have finished learning basics of PHP and have started learning drupal along with learning how to program the individual elements. Thankfully i have also got no. of materials ranging from books and video tutorials but what i also find is Drupal 8 has now also been released though i think it will take a lot of lot of time for people to build learning materials for that.
But i also think that it will take atleast 1.5 years to learn entire aspect of drupal and by that time Drupal 8 will be the worldwide adopted version.So do you guys think that learning Drupal 7 will be a waste as ppl will sign it off by then due to advent of Drupal 8.
Please guide me on the same
Comment: Drupal 8 will still use the hook system and views so its still a good idea to use them.
Comment: Not at all. Drupal 8 need a long time to be fully practical. Lots of modules need to be compatible with the Drupal 8.
Answer: Well, firstly learning never gets wasted. Whatever you learn will some day in some moment help you.
Yes, Drupal 8 is going to be released and not yet released. No one knows when it gets released and even people are skeptic about the features that vary with Drupal 7. Definitely, Drupal 8 is going to set a new standard in development and usage. But, till then we shouldn't avoid Drupal 7.
Previously, we developed a website in Drupal 6 as soon as we deployed the site Drupal 7 was released. Then the features provided by Drupal 7 attracted us and we started migrating to 7 and it took most of our time in migrating. But our knowledge and work in drupal 6 didn't go into vain. Infact, we just learnt the new features added/upgraded. It took us only 1-2 days to know about Drupal 7, as we know the core concepts.
So, I suggest you to start learning drupal 7 don't bother about the things that are yet to come. You can easily manage things even drupal 8 gets released.
Answer: learning never gets wasted, most of the major principle remains same for Drupal 8. you will get more exposure learning many things and learn how to things different ways.
Yes, Drupal 8 is releasing soon, you can take all the benefits of core modules, but if you want more features and extended functionality you have to use contributed modules and not much contributed modules are there for Drupal8, developer needs time to write those modules for drupal8, you have to wait for that as well.
Decision is yours. I suggest you to go with Drupal7 and keep learning drupal8 as well.


Mysql e python erro ao inserir dados

Question: Tenho o seguinte código:
#encoding: utf-8
from django.utils.encoding import smart_str
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="[--CENSURADO--]",
  passwd="[--CENSURADO--]",
  database="Planilhas"
)
mycursor = mydb.cursor()

clientes = []

print "Loading table..."
f = open("Completo.csv", "r")
for x in f:
  clientes.append(x)

temp = []
for x in clientes:
        temp.append(x.split(';'))
clientes = temp

for c in clientes:
        sql = """INSERT INTO 'Completa'('id', 'cpf', 'nome', 'ordem', 'tipo', 'posto', 'sub on', 'upag', 'valor$
"""
        values = ()
        for data in c:
                sql = sql.replace("%s", data, 1)

        print sql
        mycursor.execute(sql)
        mydb.commit()

Ele basicamente, lê um arquivo .csv com 25 colunas e pega os dados em cada linha e substitui na query na referência %s e teoricamente a insere no banco, mas retorna o seguinte erro:
Traceback (most recent call last):
  File "model_for_completa.py", line 33, in <module>
    mycursor.execute(sql)
  File "/usr/local/lib/python2.7/dist-packages/mysql/connector/cursor.py", line 559, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "/usr/local/lib/python2.7/dist-packages/mysql/connector/connection.py", line 494, in cmd_query
    result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
  File "/usr/local/lib/python2.7/dist-packages/mysql/connector/connection.py", line 396, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Completa'('id', 'cpf', 'nome', 'ordem', 'tipo', 'posto', 'sub on', 'upag', 'val' at line 1

Saída do código:
Loading table... INSERT INTO 'Completa'('id', 'cpf', 'nome', 'ordem', 'tipo', 'posto', 'sub on', 'upag', 'valor', 'prazo', 'banco', 'nascimento', 'endereco', 'numero', 'complemento', 'bairro', 'cidade', 'uf', 'cep', 'tel_fixo_1', 'tel_fixo_2', 'tel_fixo_3', 'tel_cel_1', 'tel_cel_2', 'tel_cel_3') VALUES ('','CPF','NOME','ORDEM','TIPO','POSTO','SUB_OM','UPAG','VALOR','PRAZO','BANCO','Data Nasc','ENDERECO','NUMERO','COMPLEMENTO','BAIRRO','CIDADE','UF','CEP','FIXO1_TEL','FIXO2_TEL','FIXO3_TEL','CEL1_TEL','CEL2_TEL','CEL3_TEL ')

Comment: sql = """INSERT INTO Completa('id', 'cpf', 'nome', 'ordem', 'tipo', 'posto', 'sub on', 'upag', 'valor', 'prazo', 'banco', 'nascimento', 'endereco', 'numero', 'complemento', 'bairro', 'cidade', 'uf', 'cep', 'tel_fixo_1', 'tel_fixo_2', 'tel_fixo_3', 'tel_cel_1', 'tel_cel_2', 'tel_cel_3') VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s') """
Answer: Uma dica, para ler arquivos csv use o módulo csv, ao invés de dividir os dados você mesmo, é bem mais fácil.
Agora, respondendo a sua pergunta para inserir dados no mysql usando o mysql connector, você não deve substituir o %s pelo valor - ao invés disso, passe os valores separadamente para o método .execute(), e o mysql cuidará de inserí-los corretamente na query.
import csv

sql = """INSERT INTO Completa(id, cpf, nome, ordem, tipo, posto, `sub on`, upag, valor, prazo, banco, nascimento, endereco, numero, complemento, bairro, cidade, uf, cep, tel_fixo_1, tel_fixo_2, tel_fixo_3, tel_cel_1, tel_cel_2, tel_cel_3)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""

with open("Completo.csv", newline='') as f:
     cf = csv.reader(f, delimiter=';')
     for c in cf:
        mycursor.execute(sql, c)

Como você pode ver, c é uma sequência de valores que está sendo passada separadamente para o método execute() contendo os dados que serão inseridos. A query segue sem alterações, com os %s mesmo como estão.
Dessa forma, você também não precisa se preocupar com aspas uma vez que o mysql vai cuidar do tipo de dados automaticamente, e também não é preciso se preocupar com injeção de sql nas variáveis pois elas nunca serão parte da query.
Uma outra opção ainda mais rápida é usar o executemany(); Assim a operação é preparada uma vez só para todos os dados. Pode fazer muita diferença se forem muitos registros:
with open("Completo.csv", newline='') as f:
    cf = csv.reader(f, delimiter=';')
    mycursor.executemany(sql, cf)

Comment: Legal, para reduzir a quantidade de 's' poderia ser realizado algo como `"""... (""" + "%s, " * 9 + "%s)"`, com `''.join([])` sintaticamente possibilita uma melhor leitura.
Comment: mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'on, upag, valor, prazo, banco, nascimento, endereco, numero, complemento, bairro' at line 1
Comment: Ele me retornou este erro seguindo o primeiro método
Comment: @LinhadeCódigo parece que você tem um espaço no nome de campo `sub on`... Então nesse campo é preciso usar o *backtick* ou "crase" (`) para o mysql reconhecer. Editei a resposta, veja se é isso
Comment: Deu certo! muito obrigado.

Mysql e python erro ao inserir dados


Query to show result in the charts

Question: I have to implement charts in my application. Suppose i have a table structure
 DECLARE @SONGS TABLE
 (
    [ID] INT IDENTITY,
    [SONGNAME] VARCHAR(20),
    [CREATEDDATE] DATETIME
 )

 INSERT INTO @SONGS
 SELECT 'SONG1','20091102' UNION ALL
 SELECT 'SONG2','20091103' UNION ALL
 SELECT 'SONG3','20091107' UNION ALL
 SELECT 'SONG4','20091107' UNION ALL
 SELECT 'SONG5','20091107' UNION ALL
 SELECT 'SONG6','20091109'

Now user will pass start date and end date from outside as parameters like below
DECLARE @STARTDATE DATETIME
DECLARE @ENDDATE DATETIME

SET @STARTDATE='20091101'
SET @ENDDATE='20091111'

Now user has further one more option(SAY @OPTION VARCHAR(20) ) whether he wants the results with dates split into individual dates between the start date and end date, second option he can choose to have the results with dates into the months between the start date and end date, similarly for year.
--OUTPUT I NEED IS when @OPTION IS DATE

DATE        [SONGCOUNT]
------------------------------------------
20091101       0
20091102       1
20091103       1
20091104       0
20091105       0
20091106       0
20091107       3
20091108       0
20091109       1
20091110       0
20091111       0

Similarly i want the results with dates splitted according the option(day,week,month,year) having count next to it.
My goal is to display date on xaxis and count on y axis, can you suggest me a way to implement the same.
Answer: DECLARE @dimDate TABLE (
 myDate datetime
,dt int
,yr int
,ym int
)

DECLARE  @dte datetime

SET @dte = @STARTDATE
WHILE @dte <= @ENDDATE
    BEGIN
       INSERT INTO @dimDate (myDate, dt, yr, ym)
         VALUES(
             @dte
            ,datepart(yy,@dte)*10000+ datepart(mm,@dte)*100 + datepart(dd,@dte)
            ,datepart(yy,@dte)
            ,datepart(yy,@dte)*100+ datepart(mm,@dte)
            )
        SET @dte = dateadd(dd,1,@dte)
    END

.
DECLARE @option varchar(2)
SET @option ='dt'

.
-- per day
IF @option ='dt'
BEGIN
SELECT d.dt, COUNT(s.ID) AS "song_count"
  FROM @dimDate AS d
    LEFT JOIN @SONGS AS s ON d.myDate = s.CREATEDDATE
  GROUP BY d.dt
END

.
-- per year
IF @option ='yr'
BEGIN
SELECT d.yr, COUNT(s.ID) AS "song_count"
  FROM @dimDate AS d
    LEFT JOIN @SONGS AS s ON d.myDate = s.CREATEDDATE
  GROUP BY d.yr
END

.
-- per year-month
IF @option ='ym'
BEGIN
SELECT d.ym, COUNT(s.ID) AS "song_count"
  FROM @dimDate AS d
    LEFT JOIN @SONGS AS s ON d.myDate = s.CREATEDDATE
  GROUP BY d.ym
END

Answer: For making the results in x & y axis, use PIVOT(SQL server 2005+).
This kind of queries are called CROSS TAB QUERIES
For your reference
SQL Server PIVOT examples

Query to show result in the charts


pre_match problems and won't match the value being sought

Question: I'm trying to get a pre_match to work right to pull in the results of a value as seen below:
readonly="readonly" value="email@example.com">

I'd like to snag what's inside the value field only and go based on that and not worry about the readonly or the
Here's what I have tried to no avail:
preg_match("value=\"([\w-]+[0-9]+@\w*\.?craigslist.org)\"/i", $compiled_results, $matches2);

What am I doing wrong?
Answer: The main problem seen is that you're missing the beginning delimiter /. You can also use ' to quote your regular expression and avoid escaping here and replace the part before @ with [\w-]+
What about simply the following?
preg_match('/value="([\w-]+@\w*\.?craigslist\.org)"/i', $compiled_results, $match);
echo $match[1];

See Live demo
Depending on whether or not you are looking for that specific match or just wanting to match and capture everything between the quotation's of the value field, you could simply use.
preg_match('/value="([^"]*)"/i', $compiled_results, $match);

Comment: That seems to have done it! Thanks for your help. And I thought for white spaces it was +s? Am I wrong?
Answer: Missing starting /
preg_match("/value=\"([\w-]+[0-9]+@\w*\.?craigslist.org)\"/i", $compiled_results, $matches2);

Comment: Doesn't seem to catch it still.
Comment: @MrTechie: Can you provide an example value for `xxxx-xxxxxx`?
Answer: Try the following:
preg_match("/value=\"(\w+-\d+@\w+\.?craigslist.org)\"/i", $compiled_results, $matches2);

Demo.


Predicting data in many dimensions

Question: I have two matrices deriving from one matrix of the original data. One is the training, the other is the validation set. Each matrix has rows= examples, columns = featuers. The proportions are 65% vs 35% respectively.
Given that the data is in many dimensions and it is not possible to visualize it, what would you suggest to use to make predictions ?
I was initially thinking about a polynomial fit, but how does one know which of the 65 features to square, cube, etc?
Answer: You are describing the very complex problem of feature selection (as it is known in the machine learning and statistics community).
http://en.wikipedia.org/wiki/Feature_selection
What do you want to predict, anyway?  Do you have a classification for each example (each row) or a numerical outcome?
Comment: The first X features are results at a given time, the other Y a different type of result, and the last W dimensions are a binary indicator of on which day of the week, and which hour of the day the results were obtained. I would like to predict the number of the result X given some other features. I am totally new to the area and not really sure how to approach it. I would imagine that having the training set, I can create a multi-dimensional function describing it(regression) and later supply some arguments to it to obtain the result, the prediction.
Comment: You didn't state the data type of X, so I can't say which link function to use, but the most straightforward thing you could do is linear regression.  I recommend using R.  http://en.wikipedia.org/wiki/Linear_regression#Simple_and_multiple_regression
Comment: Ah, they are all numerical. Both X and Y is a number, at a given time. I so happen to be using R :-). I have been able to make linear regression using gradient descent for smaller data, 2D. But I suspect that linear will not be good enought for this type of problem, and think therefore that I would have to use a more complex model. Could you give me some advice on how to approach this, and what functions in R can prove to be helpful? :)
Comment: lm() function -- include covariates you would believe if they came back significant, include interaction terms, prune the model by taking away non-significant terms

Predicting data in many dimensions


getting autocomplete working

Question: I honestly did, what this and this tutorial told me, but somehow my autocomplete textfields still fire an ajax error. but to be more specific: the ajax error gives a 200 http response and a status OK, but no answer-text.
my setup is:
$form['field_new_verein_location_'.$i] = array(
    '#type' => 'textfield',
    '#title' => t('Neuer Verein Ort'),
    '#default_value' => '',
    '#size' => 60,
    '#maxlength' => 128,
    '#required' => TRUE,
    '#description' => t('description'),
    '#autocomplete_path' => 'dsregion/autocomplete'
);

function ds_regions_menu(){
    $items['dsregion/autocomplete']=array(
      'title' => 'location auto complete',
      'page callback' => '_dsregion/autocomplete',
      'access arguments' => array('access region autocomplete'),
      'type' => MENU_CALLBACK
    );
    return $items;
}

function _dsregion_autocomplete($string) {
    $matches = array();
    $result = db_select('ds_plz_ort','o')
      ->fields('o',array('ort'))
      ->condition('ort','%'.db_like($string).'%','LIKE')
      ->range(0,10)
      ->execute()
      ->fetchAllKeyed();

    foreach($result as $row){
      $matches[$row->ort]=check_plain($row->ort);
    }
  drupal_json_output($matches);
}

Answer: You have a slight error in your page callback property for the menu item. You've got a string resembling a path in there instead of the name of the callback function.
Just change
'page callback' => '_dsregion/autocomplete'

to
'page callback' => '_dsregion_autocomplete'

Then clear Drupal's caches and you should be good to go.
Comment: I love you guys. I was already comparing my code with the ones from the tutorials twice, but I didn't see this. Thanks a lot!

getting autocomplete working


Finding the dimensions of a rectangle in a photo, given knowledge of one side (perspective)

Question: Consider a photograph of a table like this:

Assuming the table is truly rectangular, and that the photograph was taken straight-on (that is, the near and far edges of the table are totally horizontal in the photo), and that I know the true length of one of the sides, how can I find the length of the other?
I can measure the pixels of each side, but how do I correct for perspective?
Comment: Just checking - you're looking for the true width/length from the true length/width?
Comment: The "vertical sides" meet at "visual infinity", so you have similar triangles.
Answer: You need some other information, because the ratio between front and rear apparent widths depends only on the distance of the camera, while the ratio between real and apparent depth depends on the camera focal length and on its height with respect to rectangle plane.


Giving full access to IIS to non-admin users using command line

Question: How can I give a user full access to IIS without being Local Administrator, using command line?
I would like to have a BAT-script on a machine, which asks for "DOMAIN\username" as input, then gives that user all necessary access to IIS (locally only).
The script itself will be executed by an domain admin using "Run As" from the context menu.
I have read around a bit, and so far it seems appcmd.exe can not be run unless you are a member of the administrators group, but I hope there is a way around.
Answer: You can't.  Users need the correct privileges to perform tasks if they are to perform them; the way in which this is implemented is groups.  To administer IIS, you need to have administrator privileges on the IIS server.  The process of granting this access is adding a user to the administrators group, as this is how windows manages access rights.
That said, typically the domain admins group is a member of the local administrators group on all domain-joined workstations, so it's not clear why there would be much need to do anything here.


How do I modify data to test retest measure as more normal?

Question: I am working with a psychometric test of future orientation/prospection and looking at repeat measures within-subject, tested twice across 3-4 years.
I've read that Pearson's r would be suitable if the data are normal, though my Wilks Shapiro stats strongly suggest non-normality.
Do you have any advice for test-retest with non-normal data?  Would a log transform be appropriate (and rechecking normality first)?
Answer: Pearson's $r$, as well as other correlation coefficients, are popular choices for assessing retest reliability, but they aren't very good ones. The problem is that correlation coefficients, by design, adjust for differences between the variables such as additive bias and rescaling. When you're looking at retest reliability, on the other hand, you want to check to what extent the test gives the same scores between administrations, as opposed to merely correlated scores. So you're best off with something like root mean squared error or mean absolute error. Having data that isn't normally distributed, by the way, isn't an issue for either of these.


tooltip cortada pela div

Question: Bom dia pessoal. Estou tentando criar um tooltip somente com css num painel lateral à direita da pagina. Nesse painel aparece uma lista de usuários e cada tooltip apresenta um breve perfil, bastante semelhante à lista de usuário do facebook em que aparece uma tooltip com foto e informações do usuário com o mouseover. Já consegui fazer o tooltip e tudo mais, no entanto, quando uso a propriedade overflow o tooltip acaba cortado pela div parent; o fato é que a lista de usuários é grande e precisa de um scroll. Já pesquisei em todo lugar e não encontrei uma solução. Alguém poderia me ajudar como resolver esse problema?

*{padding:0px;margin:0px;}
html, body{background:#000;overflow:hidden;}
.painel
{
    width:15%;
    position:absolute;
    right:0px;
    top:80px;
    bottom:0px;
    overflow: auto; /*só funciona com hidden */
    min-width:200px;
    background: blue;
}

#users_online ul{list-style-type:none;}
#users_online
{
    padding-left:5px;
    background: red;
}
#users_online ul li
{
    float:left;
    width:100%;
    border:1px solid transparent;
    padding:0px;
    margin-left:-1px;
    border-right:0;
    position:relative;
    white-space: nowrap;
}
#users_online ul li:hover{border-color:#999; background:linear-gradient(to right, #FFF, #000 160%);}
#users_online ul li a{text-decoration:none; float:left; width:70%; margin-left:10px;font-size:14px;color:#999;line-height:40px;}
#users_online ul li a .nome_titulo{line-height:20px;}
#users_online ul li a .nome_dados{font-size:12px;line-height:20px;}
#users_online ul li a p span.tipo_usuario{font-size:12px;text-transform:capitalize;font-weight:bold;}
#users_online ul li a:hover{color:#000;}

.imgSmall
{
    float:left;
    width:40px;
    height:40px;
    overflow:hidden;
    border-radius:50%;
}
.imgSmall img{width:100%; height:100%;}

.tooltip_usuario
{
    position:absolute;
}
a.tooltip_usuario span.toolinfo:hover{text-decoration:none;color:rgb(139,29,30);}
a.tooltip_usuario span.toolinfo{font-size:14px;display:none;padding:10px 10px;margin-top:-40px;margin-left:-350px;width:310px;line-height:15px;}
a.tooltip_usuario:hover span.toolinfo{display:inline;position:absolute;border:1px solid #000;background:#CCC;color:#000;z-index:1;}

            <?php for($i=1; $i<=20; $i++): ?>
            <li id="<?php echo $i ?>">

Nome Teste

Usuario/Adminitração

Nome Teste

Usuario

Administração

firstname.lastname@example.com

Ultima vez online as 12:12 de 12/12/2012

            <?php endfor; ?>

Answer: Boa tarde Larissa,
Você não chegou a comentar seu código e não sei se você está utilizando (quase com certeza, sim) o framework Bootstrap.
No bootstrap há dois componentes parecidos com o que você quer fazer.

Popover
Tooltip

Tenho a impressão de que o que você realmente precisa é do Popover.
Para utilizá-los, você pode executar o seguinte código:
<button type="button" class="btn btn-default" data-container="body" data-toggle="popover" data-placement="left" data-content="Aqui vai o conteudo do seu popover">
  Popover à esquerda
</button>

O código acima, é a maneira mais simples de executar um popover.
Caso você queira mais controle, é possível abri-los manualmente com JQuery:
$('#element').popover('show')

Enfim, são várias possibilidades para você conseguir construir um popover muito legal. E o mais interessante de tudo, seu popover já é responsivo.
Espero que tenha ajudado, caso contrário, você sempre pode comentar a resposta com suas dúvidas.
Comment: Muito obrigada pela dica Andrew, mas eu não estou usando Bootstrap por algumas incompatibilidades pois eu acabei optando pelo JqueryUI. mas valeu pela dica. Vou postar meu código mais abaixo para algum esclarecimento

tooltip cortada pela div


Solving the matrix equation: $e^{\frac{1}{\ln(A)}}=A$

Question: Looking to solve the matrix equation:
$$ e^{\frac{1}{\ln(A)}}=A $$
where $A$ is a matrix with a logarithm.
I am interested if this equation has a solution. I read about the logarithm of a matrix and the square root of a matrix. Still having trouble solving it though.
Comment: If $X^2=I$, then you can take $A=e^X$, assuming that the $\ln$ is defined such that $\ln(e^X)=X$ for that $X$.
Answer: This equation does indeed have a solution:
Let's define $1=Id$ as the identity matrix.
First, take the natural logarithm of both sides to get $\frac{Id}{\log(A)}=\log(A).$
Next, multiply both sides by $\log(A).$ So, $Id=\log^2(A).$
$\log(A)=\begin{bmatrix}
    -1      & 0  \\
    0 &-1
\end{bmatrix}$
for $A=\begin{bmatrix}
    1/e      & 0  \\
    0 &1/e
\end{bmatrix}.$ So it follows that $\log^2(A)=Id.$
$\square$


Can I use the cloudsql-proxy to connect to a custom VM running postgres?

Question: I have a custom Postgres instance running on a GCE VM. I am not using CloudSQL. I'd like to use the functionality provided by the cloudsql-proxy, but when I specify my custom instance the proxy fails.
<code>googleapi: Error 404: The Cloud SQL instance does not exist., instanceDoesNotExist
</code>
It appears that only CloudSQL instances work and I don't understand the limitation. It seems like the proxy should work on any VM with port 5432 open.
Answer: Cloud SQL Proxy can only be used with Cloud SQL instances.
In the documentation About the Cloud SQL Proxy there is no mention about using it for custom databases inside GCE.
As it is stated in the documentation:

The Cloud SQL Proxy provides secure access to your Cloud SQL Second
  Generation instances without having to whitelist IP addresses or
  configure SSL.

However, I found some documentation about Access control overview where you can find an alternative to it.


Gerar uma lista de frases ordenada pelo arraySort() em js

Question: Estou tentando criar uma lista de frases ordenada alfabeticamente utilizando o arraySort() em JS, porém utilizando o código abaixo, retorna uma frase duplicada. Alguma ideia de como fazer diferente?
//Cria lista de textos

var lista = [];

lista.push( "Amanhã vou comprar um carro." );
lista.push( "Está nevando no Canadá." );
lista.push( "Quem fez o tema?" );
lista.push( "Antes tarde do que nunca." );
lista.push( "Você não pode fazer isso." );
lista.push( "Perdi minha carteira ontem." );

function arraySort( a, b ){
    lista.sort( );
}
var retorno = lista.sort( arraySort );
console.log( retorno );

/*
**Retorno:**
[ 'Amanhã vou comprar um carro.',
  'Está nevando no Canadá.',
  'Está nevando no Canadá.',
  'Perdi minha carteira ontem.',
  'Quem fez o tema?',
  'Você não pode fazer isso.' ]
*/

Se eu utilizar sem o function, retorna correto:
var retorno = lista.sort( );
console.log( retorno );

Comment: O problema começa no sortCeption. Você está a fazer um `sort` dentro de outro `sort`
Comment: Como eu poderia fazer?
Answer: Você está a fazer um sort dentro de outro sort:
function arraySort( a, b ){
    lista.sort( );
//         ^---- e dentro da função de ordenação chama sort de novo
}

var retorno = lista.sort( arraySort );
//                   ^--- começa por chamar o ordenar aqui

Se pretende fazer uma ordenação normal basta chamar o sort normalmente, como indicou na própria pergunta:
lista.sort( );

É relevante também mencionar que o sort altera a lista diretamente, e por isso o retorno é a própria lista que foi ordenada. Ou seja, não retorna uma nova copia ordenada e sim altera a original.
A função serve para poder definir formas diferentes de comparar. Pode por exemplo ordenar os textos de forma inversa com a função de comparação utilizando localeCompare para comparar as strings:
function arraySort( a, b ){
    return b.localeCompare(a);
}

Ao passo que se fosse a.localeCompare(b) ja daria a ordenação a-z.
Veja o resultado dessa função de comparação no seu código:

//Cria lista de textos
 var lista = [];

lista.push( "Amanhã vou comprar um carro." );
lista.push( "Está nevando no Canadá." );
lista.push( "Quem fez o tema?" );
lista.push( "Antes tarde do que nunca." );
lista.push( "Você não pode fazer isso." );
lista.push( "Perdi minha carteira ontem." );

function arraySort( a, b ){
    return b.localeCompare(a);
}

var retorno = lista.sort( arraySort );
console.log( retorno );


How to pass variables without giving people the chance to see their value

Question: I'm programming a quiz and I've got a (hopefully) small problem:
I get the questions and their answers from a database and then I display it using a html form. By clicking on an answer the page gets reloaded, the chosen answer gets saved in the database and the form with the same question and answers gets displayed again - but with the difference, that the correct answer is highlighted in green and the buttons are disabled (in order to prevent users from clicking another time).
All this happens with all questions.
What I now want is to do exactly the same but without having to reload the page that often. I'd like to mark (highlight in green) the correct answer as soon as the user has chosen an answer by having clicked on a button or as soon as 10 seconds have passed.
I think of using Ajax in order to manage this but I have to pass the variables to the php script and therefore it would be easy for users to just look at the source code and get the correct answer, wouldn't it be?
Is there another opportunity of doing so, which is also secure (so that cheating isn't that easy)?
Comment: You only need to send the `question id` and the selected `answer id` to verify wether an user chose the correct answer
Comment: To ensure a request is sent from your form you could do these steps 1) Generate a random hashed string and store this in a session variable 2) Place this token in a hidden field 3) Sent the token with other data via ajax to your server and verify if it matches the session one, if so process the request, otherwise ignore the request
Comment: Well, yes, then the user can't see the correct answer in the source code but he's still able to imitate my request and with this he gets the correct answer, because I have to pass back from php to js which answer is correct.
Comment: If you are worried about brute force attacks then you should implement some security. You could limit the requests by logging the IP address and allowing only answering a specific question once every 10minutes, you could use a token in the mainform to be sure the request is sent from your domain only, ...
Comment: Well, I'm not worried about brute force attacks... But the thing with the token sounds interesting - could you explain that a bit more precise, please?
Comment: Generating a hashed string and store it in a session var sounds unnecessary because the user could run his script after having logged in and therefore the session var will always be correct if he runs the script. Am I wrong? Well, you can see the value of a hidden input field in the source code, can't you? Same for ajax request - you can see it in the source code.
Answer: You can reload certain parts of your form using AJAX, as for security, you can just send the users input to the server and do all your processing in php file, so there is no way to see which answer is correct in case if anyone would attemt to cheat.
Comment: I thought about doing this, but I would also have to pass the question id to the script. And a user could prepare a script that does the same as my script -> so he sends the question id and answer1 for instance to my script using a post param and gets as a result whether this answer is true or not. Do you know what i mean and can you see my problem? Or should I explain it more?
Comment: If it is a test, can you have it disabled and only enable it at the time of the test? I will be honest I haven't come across such a problem yet so I would be very interested in seeing other views.
Comment: In fact, it's not a test but a real quiz which will be played in our school (class vs class). Everyone plays several rounds and after the first round the user has enough time to evaluate how I pass the data and to create a script that imitates that. During the time to answer the question, he could get the question id, run his script and then click the correct button. I feel forced to add any security machanism or to solve it differently...
Answer: Thank you for your answers, @K.I and @DarkBee, I think I've got a solution - I'll realize it using AJAX. The script with which ajax is communicating increases a session var. If the session var doesn't fit to another session var which gets increased by reloading the question page, I'll disqualify the user. I think that should do, anyway, I'll give it a try ;)


Similarity of two matrices with the same characteristic polynomial and minimial polynomial

Question: Suppose $A,B\in \mathbb{M_n}$ where $n\in \mathbb{Z_{n>0}}$. If A and B both have i) same characteristic polynomial, ii) same minimal polynomial and iii) multiplicity of each eigenvalue in the characteristic polynomial not greater than 3, prove that they are similar.
Comment: It's a nice problem.  The crux of the solution is the restriction on the algebraic multiplicity to at most $3$.  Have you given it some thought?
Answer: HINT:
Considering the sizes of Jordan cells associated to a given eigenvalue, you are reduced to showing:
Let $1\le a_1 \le \ldots \le a_k$, $1\le b_1 \ldots \le b_l$ be integers such that
$$\sum a_i = \sum b_j\le 3\\
\max a_i = \max b_j $$
Then $k=l$ and $a_i = b_i$ for all $i$. There are but three cases to consider, according to what that $\max \in \{1,2,3\}$ is.


"Oracle initialization or shut down in progress" problem

Question: I installed oracle 9i before 20 days, it was working fine till now but now when i try to login from scott user with correct password it is giving oracle initialization or shut down in progress error and not letting me login.
Any solution please?
Comment: What is the platform and how do you connect (locally from the dbserver of via the network)?
Answer: Look for the alert.log file, and then the last entries in that file.
My guess would be that it has been generating archive log files and has filled up the location where they go.


Is baking the skates equivalent of quicker breaking them in?

Question: Will baking give me something that (after some time) breaking in will give me as well? Or will it be completely "new quality" not reachable by simply skating (even for long period)?
If the latter, is baking a must just right after shopping, or one can skate, say, for a week and then bake the skate. This is safer for potential selling skates.
I have Bauer Supreme One.7 and Vapor X.70 in mind.
Answer: Baking skates essentially gives you a step ahead in the skate breaking in status. If you don't bake them, your skates will still form to your foot, however it will take longer.
Baking can be done at any time, and can also be done multiple times. It can be good to bake the skates before your first skate, and again after 2-3 skates.