Is IP address retrieval authorized in terms of users' privacy?

Question: I'm currently new developping large scale webservices and I'd like to retrieve IP addresses from visitors to make some stats about the country/state of origin.
Is it allowed to take IP addresses from clients for internal use?
As this is a kind of personal information, I wonder if it is legal or not retrieving it.
Comment: ...why would it _not_ be legal? It's part of the conversation your server has with the users' browsers. And it's not really "personal". In any case, this is off-topic here. If you're really concerned about this you should speak with a legal representative in whatever jurisdiction you operate.
Answer: It's not possible for you not to know the client IP (because your site couldn't work without it), but you don't have to keep it. From a GDPR perspective, data is only "personal data" if it can be linked to an individual (even indirectly), so for example you could take the client IP, do some kind of GeoIP lookup on it (preferably local), and then increment a country counter. Then you can simply discard the IP, and the aggregate data you retain has no way of being connected back to an individual, so it's not personal data.
A very simple approach would be a table like this:

Country
Count

France
2

Germany
4

USA
10

So you would just bump the count for the country each time. This gives you the data you're after, but without any privacy impact for your users, and no GDPR exposure.


Solution of first order integro-differential equation

Question: Consider
$$ \frac{dy}{dx} + p(x)y = \int_{0}^{\infty} y(x)dx = R~~(say) $$
$$ y(0) = \int_{0}^{\infty} f(x)y(x)dx.$$
I want to solve above differential equation.
Here is my try:
$$ y(x) = y(0) e^{-\int_{0}^{x}p(\tau)d \tau} + R \int_{0}^{x} e^{-\int_{s}^{x} p(\tau) d \tau} ds. $$
where $$ R = \int_{0}^{\infty} y(0) e^{-\int_{0}^{x}p(\tau)d \tau} dx + R \int_{0}^{\infty} \int_{0}^{x} e^{-\int_{s}^{x} p(\tau) d \tau} ds dx $$
$$ y(0) = \int_{0}^{\infty} f(x)y(0) e^{-\int_{0}^{x}p(\tau)d \tau} dx + R \int_{0}^{\infty}f(x)\int_{0}^{x} e^{-\int_{s}^{x} p(\tau) d \tau} ds dx. $$
Now, I am not able to find $R$ which is independent of $y(0)$ and $y(0)$ which is independent of $R$. Please let me know if it is possible to find solution of this integro-differential equation.
Comment: Are $p$ and $f$ arbitrary functions? You have not specified what they are, so it is unclear what exactly you are doing.
Comment: $p$ and $f$ are continuous functions. Here, I am trying to find solution to given integro-differential equation with initial data in the form of integral involving solution of given differential equations.
Comment: I understand now. In that case, it appear you have two linear equations in two unknown to answer.
Answer: Given $$R=y(0)\int_0^{\infty}e^{-\int_0^xp(\tau)\,\mathrm{d}\tau}\,\mathrm{d}x+R\int_0^{\infty}\int_0^xe^{-\int_s^xp(\tau)\,\mathrm{d}\tau}\,\mathrm{d}s\,\mathrm{d}x$$ $$y(0)=y(0)\int_0^{\infty}f(x)e^{-\int_0^xp(\tau)\,\mathrm{d}\tau}\,\mathrm{d}x+R\int_0^{\infty}f(x)\int_0^xe^{-\int_s^xp(\tau)\,\mathrm{d}\tau}\,\mathrm{d}s\,\mathrm{d}x$$ you can rearrange to obtain two linear equations with two unknowns. The former equation is equivalent to $$0=y(0)\int_0^{\infty}e^{-\int_0^xp(\tau)\,\mathrm{d}\tau}\,\mathrm{d}x+R\left[\int_0^{\infty}\int_0^xe^{-\int_s^xp(\tau)\,\mathrm{d}\tau}\,\mathrm{d}s\,\mathrm{d}x-1\right]$$ while the latter is equivalent to $$0=y(0)\left[\int_0^{\infty}f(x)e^{-\int_0^xp(\tau)\,\mathrm{d}\tau}\,\mathrm{d}x-1\right]+R\int_0^{\infty}f(x)\int_0^xe^{-\int_s^xp(\tau)\,\mathrm{d}\tau}\,\mathrm{d}s\,\mathrm{d}x$$ This can be solved with just elementary algebra, or using matrix algebra. You will get $y(0)$ and $R$ exclusively in terms of $f$ and $p,$ provided suitable integrability conditions for these functions. It depends on the determinant of the corresponding matrix. If the matrix is invertible, then $y(0)$ and $R$ are unique.


iOS Container View in UITableViewCell

Question: I'm trying to add another view controller inside a UITableView cell. The idea is that you tap the cell, and it expands to show more content--a messaging interface. It's important (I think) that this is controlled by a separate Messaging ViewController.
Expanding the cell and having views inside the cell expand with the proper constraints is actually very straightforward in Storyboards, so I tried to keep everything in storyboards by adding my new VC to the TableViewCell via a Container. That way I'd be able to add constraints on the container view, and pipe the content in from my Messaging VC.
Here's the error:

Illegal Configuration: Container Views cannot be placed in elements that are repeated at runtime.

Any way to get around this issue, or is there a way I can pipe the view from my viewcontroller into this tableviewcell and have it constrain to a configuration that I set in Storyboards? Thank you!
Comment: Looks like this is possible, but not via a storyboard. http://stackoverflow.com/questions/14741951/using-a-uicollectionview-from-a-uicollectionviewcell
Answer: I had the same task and decided it this way:
Step 1. Create subclass MyCell: UITableViewCell.
Step 2. If you use Self-Sizing Cells, in InterfaceBuilder add UIView to MyCell, then add height constraint and constraints to all sides. This view needed for set height of cell.
If not, skip this step and use heightForRowAtIndexPath.

Step 3. In MyCell.h add outlet from view height constraint and controller property:
@interface MyCell: UITableViewCell

@property (weak, nonatomic) MessagingVC *controller;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *viewHeight;

@end

Step 4. In cellForRowAtIndexPath add code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    MyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell" forIndexPath:indexPath];

    // adjust this for your structure
    cell.controller = [[UIStoryboard storyboardWithName:@"MessagingVC" bundle:nil] instantiateInitialViewController];

    [self addChildViewController:cell.controller];
    [cell.contentView addSubview:cell.controller.view];
    [cell.controller didMoveToParentViewController:self];

    //  if you use Self-Sizing Cells
    cell.viewHeight.constant = 200; // set your constant or calculate it

    return cell;
}

Step 5. Add didEndDisplayingCell method:
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell isKindOfClass:[MessagingVC class]])
         [((MyCell*)cell).controller removeFromParentViewController];
}

Comment: When using this, the tableview is not removed for some reason. You can see this in the Debug View Hierarchy, scroll up and down, and you will see an increasing number of tableviews including the containing cells. In order to fix this I had to remove the tableView of the controller in Step 5 first and then remove the controller from its parent view controller.
Comment: Works! Thank you!
Answer: Make your UITableViewController content as Static.
Answer: You can just drag Container View into UITableVeiw in the storyboard. For example, you can drag it before prototype cell, and you will see your container's view controller before your prototype cells. By the way you can drag any UI element to table view. I'm not sure, how to deal with autolayout in the combination table view + container view, maybe you need to manually calculate / set constraints at the runtime. Will update my answer when I'll find the right solution about autolayout.
Comment: It's true you can add a container view into UITableView, it just won't compile.
Comment: @Joe you definitely could do this in the time when the original question was asked. I had released app that used this approach... Can't tell you about now, probably you're right. Not sure about downvote for an outdated answer, though.
Comment: The error of the original poster is the same as today - so no, the error was the same back then as today. They weren't asking if the container view *could* be put into a table view cell, they were asking how to get around the error. Granted, the title question is pretty weak. If you update your answer like you indicated in 2015, I'd be glad to remove the downvote and upvote it. I believe the answer is that you can put the container in the cell, but the error doesn't allow compilation for unknown reasons, like greg says in the original comment.
Answer: Putting container views in table view cells is way too heavy. Table view cells should be lightweight so the user can scroll through them quickly. It's not necessary to put the entire view controller in each cell. The cell should just represent some of the data for that row.
When the user touches the cell you just use a normal segue to the messaging view controller. Its presentation will be automatic. Then create and specify an animationController to handle the transition to make it appear as though the message composition view was contained within the table view cell.
Comment: I believe the OP wants to present certain data in the table view cell to the user. So while you are correct, limiting the developer to only being able to implement tapping on the cell to reveal data isn't the solution. The solution is to use something more lightweight than a page view controller (i.e., collection view controller, perhaps?). Many apps embed collections of data in other collection objects.

iOS Container View in UITableViewCell


When writing the integral sign $\int$, how does one know what integral is being discussed?

Question: We have the Lebesgue integral and the Riemann Integral. Generally, must the integral sign $\int$ refer to one or the other exclusively or does it depend on the integrand? Can someone provide intuition to this concept?
For example, in college-level Calculus courses, what integral is actually being used here?
Comment: It really depends on the context.
Comment: Some people use $\int_{L}$ and $\int_{R}$ to represent these integrals, but I'm not a fan of that convention at all... I have also seen $\int_{D}$ to represent the Darboux integral. I would imagine that the integral sign has to be defined in context, or it would be ambiguous. :/
Comment: @Cameron. For example, what about in college-level Calculus?
Comment: @Clarinetist Except in formulating the foundations, there is no distinction between the Riemann and Darboux integrals. We only distinguish between them temporarily in order to prove that they are equivalent. Except when talking about this equivalence, both are just called Riemann integrals.
Comment: In introductory calculus, the Riemann integral is most definitely what is meant.
Answer: If a function is continuous on some closed interval then the two integrals will agree, hence a distinction is not necessary. Otherwise I believe the context should be enough.
Answer: There are only two situations where it could be unclear:

The integral is on a compact interval, $f$ is not Riemann integrable and is Lebesgue integrable;
The integral is not on a compact interval, $f$ is improperly Riemann integrable and not Lebesgue integrable.

(Note that e.g. $\int_0^1 \ln(x) dx$ is "not on a compact interval" in this sense.)
The first situation is really not a problem, because either:

the discontinuities of $f$ have positive measure, in which case you're dealing with a Lebesgue integral;
or it doesn't matter, because both exist and are the same.

The second situation requires careful attention to context. For instance, one should pay careful attention to properly understand what "$\int_1^\infty \frac{\sin(x)}{x} dx$ exists" means.
Answer: It is possible that some courses may differ, but Riemann integration seems to be
fairly standard in your basic first textbook of integral calculus.
The standard curriculum for real analysis as I recall it was you get one year
of single-variable differential and integral calculus,
then a year of multivariate calculus, and if you continue on from that
(which you will almost certainly not do unless you are majoring in math)
you get Lebesgue integration.
I think the reason may be it's relatively easy to explain Riemann integration;
to motivate Lebesgue integration you'd have to understand things like the reason
the set of rationals has measure zero and the set of irrationals does not.
The online course description for
Calculus I at the University of Houston,
for example, mentions Riemann sums immediately under the heading of integration.
MIT's open courseware Calculus lecture notes
pretty clearly are using Riemann integration for the definite integral.
Comment: @Ian I _did_ misunderstand. I thought you meant you took a graduate-level course in your second or third year of college. Such things do happen occasionally (though never to me). I suppose I should have said in my answer that some courses _will_ differ (though mainly in how long it takes to get to Lebesgue, rather than in what you start with).
Comment: My experience with real analysis was a semester of single variable, a semester of "mostly multivariable" with some extra stuff added in, and then Lebesgue integration at the graduate level. All of this is after three semesters of calculus.
Comment: @Ian Sounds like a fast-track program compared to most. As I recall I may have gotten to Lebesgue integration in the first semester of college, but this was in a course that was supposed to combine second and third year analysis for math majors, and I only got into it by placing out of first year calculus completely (having taken AP calculus, which as I recall relied on Riemann integration).
Comment: I think you misunderstand. Having taken AP calculus, I came in taking calc III. Then I had some other courses (linear algebra, for example) before taking the intro to proof class in my second spring. Then I had analysis in both semesters of my junior year, which did *not* cover Lebesgue integration. (It stopped at some function space topics including the implicit function theorem.) I did Lebesgue integration in my first semester in graduate school.


How to scale a drawable to center crop in a custom view programmatically

Question: I have a custom view that I am using as an imageview. Its parent is a constraint layout but I have to extend that layout(parent) to get some other implementation.
I want to Center-crop the drawable in the custom view just like in the normal ImageView
I have only been able to achieve the fitXY, how can I make the drawable Center-Crop in the custom view?
class CustomImageView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : CustomShimmerView(context, attrs, defStyleAttr) {

    var mDrawable:Drawable?=null

    @RequiresApi(Build.VERSION_CODES.O)
    override fun dispatchDraw(canvas: Canvas?) {
        if (isLoading && mDrawable == null) {
            background = ContextCompat.getDrawable(context, android.R.color.black)
            super.dispatchDraw(canvas)
        }

    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        mDrawable?.setBounds(0, 0, width, height)
    }
    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        if (mDrawable == null) return

        if (mDrawable!!.intrinsicWidth == 0 || mDrawable!!.intrinsicHeight == 0) return

        if (canvas != null) {
            canvas.save()
            canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
            mDrawable!!.draw(canvas)
            background = null
            canvas.restore()
        }
    }
    fun setImage(bitmap: Bitmap){
        mDrawable = BitmapDrawable(resources, bitmap)
        invalidate()
    }

}

Answer: Translate the canvas before you draw the drawable
override fun onDraw(canvas: Canvas?) {
    ...
        if (canvas != null) {
            canvas.save()
            ...
            canvas.translate(-mDrawable.width/4f,-mDrawable.height/4f)
            mDrawable!!.draw(canvas)
            ...
            canvas.restore()
        }
    }

Comment: Thanks for your suggestion. Translate moves the origin on the canvas. Combined with the scale method I was able to achieve what I wanted. I will post the answer.
Answer: I was able to achieve the center crop method with the code below. Though, I tried to use matrix as seen on the imageview source code it did not work but the one below works well as center crop.
class CustomImageView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : CustomShimmerView(context, attrs, defStyleAttr) {

    var mDrawable:Drawable?=null

    @RequiresApi(Build.VERSION_CODES.O)
    override fun dispatchDraw(canvas: Canvas?) {
        if (isLoading && mDrawable == null) {
            background = ContextCompat.getDrawable(context, android.R.color.black)
            super.dispatchDraw(canvas)
        }

    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        if (mDrawable?.intrinsicWidth == 0 || mDrawable?.intrinsicHeight == 0) return
        mDrawable?.setBounds(0, 0, mDrawable!!.intrinsicWidth, mDrawable!!.intrinsicHeight )
    }
    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        if (mDrawable == null) return

        if (mDrawable!!.intrinsicWidth == 0 || mDrawable!!.intrinsicHeight == 0) return

        val dWidth = mDrawable!!.intrinsicWidth
        val dHeight = mDrawable!!.intrinsicHeight
        val scale:Float = if (dWidth * height > width * dHeight){
            (height.toFloat()/dHeight)
        } else{
            (width.toFloat()/dWidth)
        }

        val dx = (width-dWidth * scale) * 0.5f

        if (canvas != null) {
            canvas.save()
            canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
            canvas.concat(matrix)
            canvas.translate(dx, 0f)
            canvas.scale(scale, scale)
            mDrawable!!.draw(canvas)
            background = null
            canvas.restore()

            requestLayout()
        }
    }
    fun setImage(bitmap: Bitmap){
        mDrawable = BitmapDrawable(resources, bitmap)
        invalidate()
    }
}


React native app crashes on receiving notification with error message "There is no completion handler with completionHandlerId:"

Question: I am trying to integrate react-native-firebase to a simple App. I followed the steps mentioned here http://invertase.io/react-native-firebase/#/installation-ios?id=_11-initialisation. I configured everything and run the app, but when I get notification from fcm app crashes with above-mentioned error message and it happens in RNFirebaseMessaging.m line number 406,
the code looks like this
RCT_EXPORT_METHOD(finishRemoteNotification: (NSString *)completionHandlerId fetchResult:(UIBackgroundFetchResult)result) {
    RCTRemoteNotificationCallback completionHandler = self.notificationCallbacks[completionHandlerId];
    if (!completionHandler) {
        RCTLogError(@"There is no completion handler with completionHandlerId: %@", completionHandlerId);
        return;
    }
    completionHandler(result);
    [self.notificationCallbacks removeObjectForKey:completionHandlerId];
}

I did print completionHandler dictionary before this method is called and it has data but when this method is called completionHandler is nil.
Has anyone come across the same issue?
I am using react native version 0.47.0 and react-native-firebase 2.0.5
PS: App crashes every time it receives remote notification.
Comment: May I recommend making an issue on the github repo for RNFirebase, happy to take a look at it over there.
Answer: As written here
The problem is that you are probably subscribing to 2 (or more) onMessage listeners.
When you call onMessage it will return unsubscribe method which you can call later if you need to and then subscribe again afterword.
Also, they are currently working on Messaging / FCM overhaul

// subscribe
const unsubscribe = firebase.messaging().onMessage((url) => {
  // ...
});

// unsubscribe
unsubscribe();


A error creating filter - filter tips

Question: I want to create a filter text module for drupal 8.
emtfilter/src/Plugin/Filter/emtfilter.php

/**
 * @file
 * Contains \Drupal\emtfilter\Plugin\Filter\emtfilter.
 */

namespace Drupal\emtfilter\Plugin\Filter;

use Drupal\Core\Form\FormStateInterface;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;

/**
 * Text filter for highlighting PHP source code.
 *
 * @Filter(
 *   id = "emtfilter",
 *   module = "emtfilter",
 *   title = @Translation("Tipograf"),
 *   description = @Translation("Tipograf"),
 *   type = Drupal\filter\Plugin\FilterInterface::TYPE_HTML_RESTRICTOR,
 * )
 */
class emtfilter extends FilterBase {

  /**
   * {@inheritdoc}
   */
  public function tips($long = FALSE) {
    if ($long) {
      return t('text1r-');
    }
    else {
      return t('text2r-');
    }
  }

  /**
   * {@inheritdoc}
   */
  public function process($text, $langcode) {
        return new FilterProcessResult($text);
  }
}

After clearing cashe everything is ok. But when I visit some forms with textfields second time, Drupal generates this error:

Notice: _filter_tips(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "Drupal\emtfilter\Plugin\Filter\emtfilter" of the object you are trying to operate on was loaded before unserialize() gets called or provide a __autoload() function to load the class definition in _filter_tips() (line 350 of core/modules/filter/filter.module).
_filter_tips('full_html', ) (Line: 378)
template_preprocess_filter_guidelines(Array, 'filter_guidelines', Array) (Line: 293)

And my tips disappear. What am I do wrong?
Comment: It's probably the use of `t()`. Can you change to `$this->t`?
Comment: I tried - all the same. This is a problem with cashe, as I think. In the first launch it works properly, including translation.
Answer: I made a mistake in the letter case in the class file (emtFilter.php -> emtfilter.php)

A error creating filter - filter tips


how do I use hook_services_request_postprocess_alter() to wrap field with CDATA?

Question: May i know how to use "hook_services_request_postprocess_alter" .I have field called 'body' in $result ,I want to wrap it with CDATA.Any idea how to do it? &$result[0]->body is my variable.
function hook_services_request_postprocess_alter($controller, $args, &$result) {

watchdog("custom_forms", '
' . print_r(&$result[0]->body, true) . '
');
}

I created a view of service display and body is one of the field,which i want to wrap it with cdata,in order to avoid encoding problem,can anybody help me in this? OR Which other hook function I need to use in order to avoid encoding problem with body field,when i view page source of service url? In view page source of service url &lt &gt are coming instead of >< for body field.
Answer: This code work for you to over right body result.
function hook_services_request_postprocess_alter($controller, $args, &$result) {
  if (is_object($result)){
    //Single value
    $tmpSArray = (array) $result;
    if (!empty($tmpSArray)){
      foreach ($tmpSArray as $skey => $sval){
        $result->body = t('<![CDATA['.$result->body.']]>');
      }
    }
  }

Comment: thank you so much for your answer. I updated my code, but if i hit service url and view page source, i cannot see 'cdata' and body html field is not encoded, it has <,> etc instead of  > <
Comment: use t() instead of it.
Comment: i can see body content wrapped with CDATA now, but encoding problem is not solved. Do u know which hook function i need to use in order to avoid encoding problem in view page source?


How do you play this notation

Question: I am studying to play a piece and it has this:

How do I play the eighth notes with the whole numbers? What does that mean?
Comment: (I'm assuming that "whole numbers" means "whole note," maybe a keyboard autocompletion mistake. If you mean something else, please edit to explain more.)
Answer: I'm assuming that this is a piano piece, the staff is for the left hand, and that you don't have freakishly large hands.
In that case the answer is simple. The notes don't add up to a whole bar because there are two simultaneous voices notated, and the only way you can keep the organ point sounding while executing the upper voice is to use the pedal.
Comment: yes. this is a piano piece and thats for the left hand

How do you play this notation


Nettoshpere and javax.servlet.Filter support

Question: I'm using Nettosphere into a simple chat application. What I want to do is to take an already implemented Filter and integrate it to Nettosphere prior each call to atmoshpere etc.
If I'm not mistaken, the Netty way to interfere into the flow is by implementing a ChannelUpstreamHandler. Is it possible, and how, to integrate a javax.servlet.Filter implementation with Nettosphere?
Comment: there is a similar discussion here: http://stackoverflow.com/questions/7439955/servlet-api-implementation-using-netty but has anyone sorted this  out in a solid way?
Answer: Filter aren't supported directly, but if you defined them in atmosphere.xml they will be installed. Or you can create a ReflectorServletProcessor and add your Filter to it.


Apache/PHP Configuration question - Where else can info.php be disabled besides php.ini?

Question: Sorry for the bone head Q. but I rarely need to reinstall my server :)
I wish to enable phpinfo() function. My php.ini config file has the disable_functions directive blank--which I understand is the way to turn this feature off.
Except this directive in my php.ini config is blank. Other php files are being served properly. What gives?
Answer: Are you using proper tags (<?php instead of <?)?
What happens if you put display_errors(E_ALL); in the beginning of the file?
Comment: I'm stupid. The first one... I never use this shortened syntax; however, I also super-rarely edit the config file. Thus the same file worked for the last install, but not the new.


Group Policy Printers only deployes at first login on RDP

Question: I'm struggling to get Group Policy Printers to deploy on our RDP server 2008 r2.
They all deploy fine the first time users logon, but hereafter no printers deploy.
If I make changes to the GPO, the printers will deploy again at next logon, but after that they will disappear again. What am I doing wrong??
Any help greatly appreciated!!
Best regards,
Steffen.
Comment: How do you deploy this? Are you using GPP? Please add some screenshots from the policy.
Comment: Welcome to Server Fault! Please read [How do I ask a good question](//$SITEURL/help/how-to-answer) and try to rewrite your question so that it matches the site quidelines. Include the following: What have you tried? What did you expect to happen? What happened instead? What does your config look like? Do you have any log entries from the times it didn't work as expected?
Comment: Yes, I am using GPP - screenshots coming up...
Comment: https://s20.postimg.org/5gihr85rh/Capture.png
Comment: [GPO Settings](https://s20.postimg.org/azq4t3lm5/Capture.png)
Comment: the setting seem ok, please select ´run in user context', double click the printer and check second tab for the settings. let me know if it help
Answer: Ok, I managed to solve this problem by adding the following option to our terminal server GPO:
COMPUTER POLICY\ADMINISTRATIVE TEMPLATES\SYSTEM\GROUP POLICY\Printers preference extension policy processing: Process even if the Group Policy objects have not changed.
Not sure if that is the best solution, but it works for now. :)


No variance in binomial glmer yields problematic CI

Question: I have a glmer with a binomial response variable and two binary predictor variables, where there are no observations for one of the four groups. I used emmeans to calculate confidence intervals, and for this group obviously the mean and variance are zero. The model predicts a CI from 0 to 1, and my question is whether the confidence interval and contrasts are calculated correctly when all observations and thus variance of a group are zero. Please see details below. I have a total of 804 observations, so a bit much to include here. Should someone want to reproduce my models, I can share the data somehow.
The data concern observations of two female sharks in an aquarium. The response variable is presence/absence in a shipwreck (in_wrak_inc). Presence was recorded by multiple people (nearly twenty observers) every five minutes between 9:00 and 17:00 for many days (a few in early January 2021, and then intermettently from 2021-12-14 to 2022-01-19). As random effects, the model includes observer and date. As fixed effects, the model includes individual (either the first or second female shark, jv or ov), presence/absence of a male shark (locatie_jm, where Kleine Oceaan == absence) and there interaction.
  individu locatie_jm    in_wrak_inc     n
1 jv       Kleine Oceaan nee            52
2 jv       Kleine Oceaan ja             27
3 jv       Oceaan        nee           213
4 ov       Kleine Oceaan nee            83
5 ov       Kleine Oceaan ja            165
6 ov       Oceaan        nee           177
7 ov       Oceaan        ja             87

As you can see there are no observations for jv when locatie_jm == Oceaan + in_wrak_inc == ja. My code is below.
model_wrak1 <- lme4::glmer(in_wrak_inc ~ locatie_jm * individu + (1|datum) + (1|observant),
                           data = scans_vrouwtjes_wrak,
                           family = binomial)

summary(model_wrak1)

# Generalized linear mixed model fit by maximum likelihood (Laplace Approximation) ['glmerMod']
# Family: binomial  ( logit )
# Formula: in_wrak_inc ~ locatie_jm * individu + (1 | datum) + (1 | observant)
# Data: scans_vrouwtjes_wrak
#
# AIC      BIC   logLik deviance df.resid
# 406.6    434.7   -197.3    394.6      798
#
# Scaled residuals:
#   Min      1Q  Median      3Q     Max
# -1.7776 -0.0625  0.0000  0.0980  8.6087
#
# Random effects:
#   Groups    Name        Variance Std.Dev.
# datum     (Intercept) 26.32    5.130
# observant (Intercept) 32.81    5.728
# Number of obs: 804, groups:  datum, 27; observant, 16
#
# Fixed effects:
#   Estimate Std. Error z value Pr(>|z|)
# (Intercept)                   1.9335     2.7759   0.697 0.486091
# locatie_jmOceaan            -31.3131    66.9586  -0.468 0.640036
# individuov                    1.1188     0.3358   3.331 0.000864 ***
#   locatie_jmOceaan:individuov  25.2350    66.9589   0.377 0.706268
# ---
#   Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#
# Correlation of Fixed Effects:
#   (Intr) lct_jO indvdv
# locat_jmOcn -0.013
# individuov  -0.115  0.000
# lct_jmOcn:n -0.012 -0.999  0.000

model_wrak_emm_loc_ind <- emmeans::emmeans(model_wrak1,
                                           specs = pairwise ~ locatie_jm | individu,
                                           type = "response")

model_wrak_emm_loc_ind$emmeans

# individu = jv:
# locatie_jm      prob    SE  df asymp.LCL asymp.UCL
# Kleine Oceaan 0.8736 0.306 Inf  0.029111     0.999
# Oceaan        0.0000 0.000 Inf  0.000000     1.000
#
# individu = ov:
# locatie_jm      prob    SE  df asymp.LCL asymp.UCL
# Kleine Oceaan 0.9549 0.119 Inf  0.086899     1.000
# Oceaan        0.0463 0.123 Inf  0.000208     0.919
#
# Confidence level used: 0.95
# Intervals are back-transformed from the logit scale

model_wrak_emm_loc_ind$contrasts |> confint()

# individu = jv:
#   contrast               odds.ratio       SE  df asymp.LCL asymp.UCL
# Kleine Oceaan / Oceaan   3.97e+13 2.66e+15 Inf      0.00  3.93e+70
#
# individu = ov:
#   contrast               odds.ratio       SE  df asymp.LCL asymp.UCL
# Kleine Oceaan / Oceaan   4.36e+02 1.34e+03 Inf      1.05  1.82e+05
#
# Confidence level used: 0.95
# Intervals are back-transformed from the log odds ratio scale

Comment: I don't really understand why you consider the CI (0, 1), problematic. It is the most conservative CI possible (with guaranteed coverage), which seems appropriate if there is no information to derive a more narrow CI.
Comment: If there are many observations and all are negative, surely that is an indication it is somewhat likely the CI should be closer to zero than to one? In this case, the probability of the other group is 0.87, and I expect a difference in the contrasts.
Comment: Sure, but you would need to quantify "somewhat likely" to derive a more narrow CI. And you can't do that just based on the model.
Comment: I understand the model cannot do that (because there is no variance?). Can it be done based on the number of observations? I have 213 observations where `in_wrak_inc == 0`. Surely the likelihood of `in_wrak_inc == 1` is therefore lower than when I would have, say, only 15 observations.
Answer: You may find this paper helpful.
This problem, sparse data in one or more cells of the cross-tabulation of your predictor and outcome variables (as you present above) which causes extreme parameter estimates, is referred to as separation. The solution is usually one or another form of regularization
(Alternatively, you can omit the covariate(s), which cause the separation, but I'll ignore that here).
There are several such options discussed in the linked paper. Potentially the easiest to implement would be data augmentation. Another option would be to estimate the model in the Bayesian framework. Using even modestly informative priors on the log odds ratios would provide the regularization needed to get  sane results (and narrower intervals).
You could try estimating the model with R package brms. It uses the same syntax as lme4 so you wouldn't really need modify your model specification, you'd just need to add priors for the model parameters.
Comment: Thanks. That paper, and looking at separation in logistic regression generally, seems very useful. I'll check it out.
Answer: Trying to answer my own question. The lme4 package cannot deal with complete separation, but info how to fix it can be found here and here (based on a question posted here). Running a mixed model with priors with blme::bglmer() did the trick. The priors I chose (10 for the intercept and 2.5 for the various slopes) are default.
model_wrak1_bayes <- blme::bglmer(in_wrak_inc ~ locatie_jm * individu + (1|datum) + (1|observant),
                           data = scans_vrouwtjes_wrak,
                           family = binomial,
                           fixef.prior = normal(sd = c(10, 2.5)))

This gives the following emmeans, which I find very reasonable:
individu = jv:
 locatie_jm        prob       SE  df asymp.LCL asymp.UCL
 Kleine Oceaan 0.092783 0.216260 Inf  6.65e-04    0.9402
 Oceaan        0.000234 0.000542 Inf  2.49e-06    0.0215

individu = ov:
 locatie_jm        prob       SE  df asymp.LCL asymp.UCL
 Kleine Oceaan 0.269436 0.505533 Inf  2.40e-03    0.9826
 Oceaan        0.093029 0.198690 Inf  1.01e-03    0.9120

Confidence level used: 0.95
Intervals are back-transformed from the logit scale


how to set switch for ON and OFF iphone sound in setting page

Question: I have setting page in this page Uiswitch as sound toggle button for ON and OFF. Implemeted UIswitch with on and off control and working fine with out audio. Now i need control iPhone sound through UISwitch  for ON and OFF , Same how to set default setting .any one provide me some tutorial.
Answer: there is no way to switch on/off sound global iPhone sound without using private API


Implementing the 'kernel trick' for a support vector machine in R

Question: I've heard a bit about the 'kernel trick' for support vector machines, and I was wondering:

How do you identify problems that might benefit from the kernel trick?
How to implement it in R?

Thank you
Answer:
Basically anything what is not separable with a line (ok, hyperplane), for instance 2D data like this:

kernel trick will effectively project this situation into a (higher-dim) space in which linear separation is possible; see this movie for an effect of a gaussian kernel on similar data.
Look for a kernel argument in your svm function ;-) Note that using a kernel usually introduces new parameters to the outer optimization.
Comment: Would a radial kernel also work on this kind of data?
Comment: @Zach I think so; also polynomial one should be OK
Answer: you should take a look at kernlab R package. They even have a very nice vignette.


How to alter single custom field value in views?

Question: I have a view with field Global: Custom Text, which is modified as a link.
I want to change replacement tokens for generating this link, dependent on a value of other field.
Tried to modify this in hook_views_pre_render but I can't find a way to do this.
In hook_views_post_render there are two arrays:
$view->style_plugin->render_tokens
$view->style_plugin->row_tokens

which contains generated links for every row, but they are not present in pre_render, and changing them in post_render doesn't work.
I've also tried to do that in template_preprocess_views_view_fields but for that specific view this function does not firing (for other views it does), and I don't know why.
Answer: function hook_views_pre_render(&$view) {

  switch ($view->name) {
    case 'YOUR_VIEW_NAME':
      //  override the global custom text field value
      $view->field['nothing']->options['alter']['text'] = 'My custom text';
    break;
  }
}

Check the link for more details
How to insert values into Global custom text field of views programmatically?
add nid as field in view and use that field for condition
you can add condition as follows: if ($nid == '124') {  $view->field['nothing']->options['alter']['text'] = $nid}
Simple way is to create a new field field_waga which will have field_waga_1 as new name if you check in the view and then you can change the label and override that field with your custom value
if($view->result[0]->field_waga[0]['raw']['value'] == '10') {
//here you can create the field to act as custom text field and enter the custom //value
$view->result[0]->field_waga_1[0]['#markup'] = 'alter';
}

Comment: No just add a field_waga which you already have again using the add field and then use that field as custom field to input your custom values
Comment: This solution changes every field to 'My custom text', I cannot see an option to alter only chosen fields, and to alter a link (if field is modified to display as a link) this way.

Unfortunately I can't use a preprocess_views_view_fields() function, which is mentioned in link you provided, because for unknown (for me ;) ) reason this function is not fired for this specific view.
Comment: you can add condition as follows: if ($nid == '124') {  $view->field['nothing']->options['alter']['text'] = $nid}
Comment: check updated answer
Comment: Added condition in this way:
    if($view->result[0]->field_waga[0]['raw']['value'] == '10') {
        $view->field['nothing']->options['alter']['text'] = 'ALTER';
}

If a have a value '10' in first row than all fields 'nothing' has value 'ALTER'.
Not only first, but all rows, unfortunately.

I think it is a global alter and it cannot be used to chosen rows.
Comment: pls check the updated answer
Comment: If I understand correctly, I should remove field "Global: custom text" from views UI, and instead provide programatically created field_waga_1, right?

OK, so this way I have a value but how can I display it in a view?
Comment: Haha, great idea! Starting from that I achieve exactly what I wanted. Thanks a lot!
Answer: As an update to the above answer, I had to set 'alter_text' to TRUE in order for this to work, e.g.:
function hook_views_pre_render(&$view) {

  switch ($view->name) {
    case 'YOUR_VIEW_NAME':
    //  override the global custom text field value
    $view->field['nothing']->options['alter']['text'] = 'My custom text';
    $view->field['nothing']->options['alter']['alter_text'] = TRUE;

    break;
  }
}


Save LINQ Query As Variable To Call Another LINQ Query

Question: I have a var type storing the result of a LINQ query that I would like to use as a parameter for another LINQ query.
I am using for Controller:
  public async Task<ActionResult> Index(String aContainer)
    {
        var partsLocations = db.PartsLocations.Include(p => p.LocationType).Include(p => p.ManufacturingPlant);
        var empty = from y in db.PartsLocations select y;

                    if (!String.IsNullOrEmpty(aContainer))
                    {
                      var parentLoc = from a in db.PartsLocations
                                    where a.LocationName.Contains(aContainer)
                                    select a.ParentLocation;
                      var location = (from b in db.PartsLocations.Where(b => parentLoc.Equals(b.LocationID))
                                    select b).ToList();

                        return View( location.ToList());
                     }
        empty = empty.Where(r => r.LocationName.Contains(null));
        return View(await empty.ToListAsync());
    }

My View is:
@model IEnumerable<Parts.PartsLocation>

@{
    ViewBag.Title = "Index";
 }

Model:
 public int LocationID { get; set; }
    public int TypeID { get; set; }
    public string LocationName { get; set; }
    public string Description { get; set; }
    public int PlantID { get; set; }
    public Nullable<int> BayID { get; set; }
    public Nullable<int> SecurityGroupID { get; set; }
    public Nullable<int> ParentLocation { get; set; }
    public Nullable<System.DateTime> LastMoved { get; set; }
    public string Notes { get; set; }

But I am getting error: "Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types."
In SQL I do something like:
SELECT ParentLocation FROM PartsLocations where LocationName = 'aContainer';
SELECT * FROM PartsLocations where LocationID = ParentLocation;
How can I use the result of a LINQ query as a parameter for a separate query?
Thanks in advance!
Answer: This
              var parentLoc = from a in db.PartsLocations
                            where a.LocationName.Contains(aContainer)
                            select a.ParentLocation;

is not a result.  It is a query.
If you want a result, run the query:
var location = parentLoc.Single();

Try, something like:
              var parentLoc = (from a in db.PartsLocations
                               where a.LocationName == aContainer
                               select a.ParentLocation).Single();

              var locations = (from b in db.PartsLocations
                               where b.LocationID == parentLoc
                               select b).ToList();

Comment: Still, using navigation properties is much more succinct and it takes only one database roundtrip.
Comment: I replaced the second query with 'var location = parentLoc.Single();' as you suggested but now I get error: 'The model item passed into the dictionary is of type 'System.Int32', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Parts.PartsLocation]'.
Comment: @ David Browne- I am actually needing a record set returned for my second LINQ query, with parentLoc as a parameter.
Answer: If I understand you correctly, you are looking for locations having parentloc as parent locations. You can easily do that by using a navigation property PartsLocation.ParentLocation that refers to the parent location. You should be able to add that property and rename the current ParentLocation property to ParentLocationId:
var location = (from b in db.PartsLocations
                where b.ParentLocation.LocationName.Contains(aContainer)
                select b).ToList();


how to draw path or line two pushpins in bing map?

Question: Hi I want draw line or paths between two pushpins in bing map using Javascript SDK.
This is a google map example I want similar like this.
Comment: ya i can do this using google map api but i want do this in bing map api
Answer: Here you go, you need to have your bing map credentials.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

      <title></title>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">


Why does exactness of Cech complex not make Cech cohomology trivial?

Question: In my class notes we proved that the (Cech?; I'm not sure what it's usually called) complex $\underline{C}^\bullet((U_i), \mathcal{F})$ (Hartshorne Section III.4) is an exact cochain complex, where $(U_i)$ is an open cover of $X$. Hartshorne (in the first definition of Section III.4) defines the $p$th Cech cohomology group of $\mathcal{F}$ with respect to the covering $(U_i)$ to be
$$ \check{H}^p((U_i), \mathcal{F}) = h^p(\underline{C}^\bullet((U_i), \mathcal{F})).  $$
But wouldn't this lead to the Cech cohomology always being trivial? Having done examples in this area before, I've always ended up taking global sections of $\underline{C}^\bullet((U_i), \mathcal{F})$ and then taking the cohomology of the resulting complex. So from the examples I've done/what I've just said, I'd expect the Cech cohomology groups to be defined something like $h^p(\Gamma (X , \underline{C}^\bullet((U_i), \mathcal{F}))$, but they're not.
I think I'm missing something really obvious here. Thanks for any answers.
Edit: red_trumpet has answered my original question in the comments, though I'm still interested in Q1 and Q2 which I've written in the comments.
To expand on Q2, I now understand that in my class notes I have the sheafified Cech complex $\mathscr{C}^\bullet((U_i), \mathcal{F})$ which satisfies
$$ \Gamma(X, \mathscr{C}^\bullet((U_i), \mathcal{F})) = C^\bullet((U_i), \mathcal{F}) $$
where $C^\bullet((U_i), \mathcal{F})$ is the global Cech complex (I've switched to Harthsorne's notation for this edit).
If $X$ is affine, then $\Gamma(X, -)$ is an exact functor. I presume in class that we proved $\mathscr{C}^\bullet((U_i), \mathcal{F})$ is exact, so by the identification above, $C^\bullet((U_i), \mathcal{F})$ too would be exact. Then putting extra conditions on $X$ such that Cech cohomology and normal sheaf cohomology agree, we get that $H^p(X, \mathcal{F})$ vanishes for $p>0$. Have we recovered a frequently stated "affine $\implies$ vanishing cohomology" result here?
Comment: The Cech complex is not exact in general. Are you missing some assumptions ? (For instance $\mathcal{F}$ flasque ?)
Comment: There are two versions of the Chech complex: A global one, $C^p(\mathfrak{U}, \mathscr{F})$ (p. 218), and a *sheafified* on, $\mathscr{C}^p(\mathfrak{U}, \mathscr{F})$ (p. 220). Taking global sections of the sheafified version yields the global Chech complex. The sheafified one is in fact exact save for the beginning (Hartshorne proves this in Lemma 4.2), but taking global sections destroys this property.
Comment: $U_i$ are open affines but apart from that I don't think so; perhaps I'm thinking about the definition of the Cech complex the wrong way.
Comment: Even with $U_i$ affines this is not true. Do you have a specific lemma in mind in Hartshorne Section III.4 or is  this from your class notes ?
Comment: @red_trumpet Yes, this makes sense, thank you. I suspect the one in my class notes is the sheafified version (the definitions actually match). I have two more quick questions (I've split them into two comments): **Q1:** firstly, the sheafified version (p. 220) is therefore the one that is an exact complex as I proved in class, correct?
Comment: **Q2:** Now suppose $X$ is affine. Then the global sections functor $\Gamma(X, -)$ is exact. So then the global Cech complex will be exact and the Cech cohomology will indeed be trivial. Given conditions that Cech and normal sheaf cohomology agree, would this be a way to prove an "affine $\implies$ vanishing cohomology"-type theorem? Thank you.
Answer: I'll attempt to answer my own Q2. Let $X$ be a noetherian scheme with a finite open affine covering $(U_i)$ such that any finite intersection of the $U_i$ is affine $(*)$, and let $\mathcal{F} \in \mathsf{QCoh}(X)$. Then using the Leray spectral sequence and the fact that for an affine morphism of schemes $f: X \rightarrow Y$ and for $\mathcal{F} \in \mathsf{QCoh}(X)$ we have $R^pf_* \mathcal{F} = 0$ for all $p>0$, it can be shown that we have the canonical isomorphism
$$\Gamma(X, \mathscr{C}^\bullet((U_i), \mathcal{F})) = C^\bullet((U_i), \mathcal{F}) \cong H^p(X, \mathcal{F}).$$
But then by what I've said at the end of my edit in the question, we indeed have for $X$ affine + noetherian + $\mathcal{F} \in \mathsf{QCoh}(X)$ + condition $(*)$ that $H^p(X, \mathcal{F})=0$ for all $p >0$, which is the result claimed at the beginning of section III.3, Hartshone p. 213, though actually Hartshorne does not state condition $(*)$; perhaps there's more work to be done if we drop it?


Securing VPN access from users machines (home office)

Question: We already have a couple of people working from home, accessing some internal servers via VPN. They're all using company provided laptops or PCs which we have complete control over. Now we're faced with more people wanting to do home office but using their own machines. They need access to at least our internal IM and fileserver.
Giving them VPN access to our internal network from their own machines seems to pose a potential security risk. I'm mostly concerned about giving them access to our samba fileserver. What has been suggested is to simply rely on an on-access virus scanner protecting the fileserver, but I'm not completely convinced this is sufficient.
Is there some kind of access-proxy or something like that which we could put into an DMZ and only allow outside access to that server, do some kind of scanning/filtering and have them access our internal servers from there?
Preferably opensource/linux based as we're mostly using CentOS/RHEL for our servers and would like to keep it that way (opensource shouldn't imply we're not willing to pay for it, just need some ideas or products which we could look at).
Answer: I'd be loathe to give VPN clients in such a scenario unfettered layer 3 (and up) access to my network. Aside from whatever application-layer tools you're going to use I'd be very draconian, at layer 3, about what the remote VPN clients can "talk to".
If you're worried about protocol-level attacks against your file server you might think about exposing the file server via a WebDAV over SSL gateway. WebDAV is arguable a more "auditable" protocol than SMB and most versions of Windows and many Linux distros handle accessing files via WebDAV very well.
In terms of the classic "confidentiality, availability, integrity" attacks against your file server by these VPN clients I think you're going to have trouble finding a "magic bullet" solution. Assuming these machines are "owned" by third parties (malware, etc), you have to assume that keyloggers could be present (thus implying the need for one-time-password functionality in a trusted device). Anything the user will have rights to access (modify, etc) will be available to the malware on these machines as well.
Given how little I'd trust personally-owned computers I'd lobby hard for giving the VPN users access to compute resources hosted on trusted computers via a "thin client" protocol-- X Windows, RDP, PCoIP, etc, and require them to use a hardware token for one-time-password sign-on. It's still not perfect (since data could be injected into or pulled out of the thin client protocol stream by a malicious third party) but it keeps direct access to the data away from the remote client computers.
Comment: +1 for the thin client suggestion
Comment: The thin client/terminal server idea absolutely hasn't been considered so far, but I like really really like it, as I'm with you not trusting personally-owned machines at all.
Answer: Something like a Juniper SSL VPN comes with a Windows component called Windows Secure Access Manager  that isn't quite a proxy or firewall, but it lets you specify applications (and MD5 hashes to ensure it really is the app) and source destinations and ports.
That may be an option for the IM stuff.
File shares is a tricky one as even using that sort of component you still have drive or UNC access in Windows, least I don't know of a way to restrict it to read-only at the VPN level.
Depending how much access they need, one option would be to use the web file access component of the VPN, that way they have access to the files but using a web interface, no SMB access.
Also with a commercial VPN you get host checkers so you can mandate that machines must have AV and it must be up to date, and if it isn't, come back and try again when you meet the rules.
Comment: "Network Access Protection" and the like (mentioned in your last paragraph) is all a big farce unless it's running on cryptographically trusted hardware (think machine w/ TPM and trusted boot environment). You can ask my computer "Are you good?" all you want and, unless there's a root of trust in my computer that you trust, my computer can just lie and say "Oh, yeah-- we're all good here." All types of NAP / NAC schemes suffer from this fault-- the machines being tested must be "trusted" to begin with or it's all a meaningless farce.
Comment: Of course, but how far do you take it in a typical business environment before you let a machine get to the logon screen?  You're right it's not perfect, but I suspect few SMB's can afford to truly enforce "trust".
Comment: That's why I'd suggest treating the clients as untrusted and using a "thin client" method of access rather than using something that lulls you into a false sense of security re: the state of the clients.
Answer: We have numerous folks connecting remotely from their own PCs.  We use Winfrasoft enterprise edition (http://www.winfrasoft.com/vpnq.htm) which checks the client for requisite security patches, anti-virus software current, connection sharing disabled, etc.


Sort/Order string output Apache Impala SQL query

Question: Hello I have a string output in my query and I want to sort by this column. The Column contains only strings but two of them are date strings and one is characters only.
I want to sort/order by the date strings first and the character string should be at last position.
SELECT column1, column2, column3 FROM table1 ORDER BY column1;

column1 contains following data as string:
ROW1: Older
ROW2: 19.03.2023
ROW3: 20.03.2023

I want the output as follows:
Column1        column2        column3
20.03.2023     some value     some value
19.03.2023     some value     some value
Older          some value     some value

How to do that, a simple ORDER BY is not working correctly.
Thanks
Comment: what kind of sorting you want - ascending? descending ? alphabetical ?date sort ?
Comment: @KoushikRoy I have written the output that I want to have. Today should be first row, yesterday should be second row and Older should be last. I edit the output in my question
Comment: If you want a string to be ordered by date, you need it to be `YYYY-MM-DD`. Otherwise, `01-02-2023` is naturally going to come before `02-01-2023`
Comment: Are there any other strings that can appear, such as `'Newer'`? Or is `'Older'` the ***only*** non-date string?
Answer: You can split the data into yyyy,mm,dd, actual value, it should work. Pls check it out.
order by split_part(column1,'.',3),  split_part(column1,'.',2),  split_part(column1,'.',1), column1

Comment: What about the `'Older'` row?
Comment: thank you this is working perfectly for me if I add DESC to each split_part.
Comment: `older` will go to bottom because all split() will generate null.


Why do these chords use the first fret if there is a capo on the second fret?

Question: I'd like to play Eagles - Hotel California, so I looked into the sheet music, but there is something I don't understand:

It says: guitar 1 is a 12-string acoustic played with capo behind 2nd fret.
I don't understand how is it possible. If you look at the chords shown, there is an E7 which has to put a finger on fret 1 in G-String. How is it possible if there is a capo on 2nd fret?
On the other hand, if the chords are shown from 2nd fret, E7 chord is no longer an E7. It'd be a F#7, right?
Answer: The chords shown for guitar1 become relative to the capo. So you´d place the capo behind fret 2 and play for example the E7 as shown, first finger, first fret on the third G string, just behind the capo. So in fact your capo becomes fret 0, the start of your fret board.
By placing the capo on the second fret, the tuning of youre guitar is raised by a whole tone, which results in Am becoming a Bm, G  with A in the bass becoming A with a B bass etc.
Comment: A guitar with a capo is notated like a transposing instrument, which means that the pitches and chords as written are not the same as the ones we hear. To notate it any other way would make it much harder for a performer to follow the score in a timely fashion.
Comment: Your´e correct. The reason, and i can only guess, is probably most beginning players are more used to the `open` chord names or ´shapes´
Comment: If I understand you correctly, E7 it's really a F#7 (one tone), right? So, why they don't put F#7 instead?
Comment: Ok, thanks. I don't usually play guitar with capo, so it confused me. In fact, it made me crazy and that's why I asked, because I knew the chord played was actually a F#7. From now I'll know whenever I have to read a sheet music with capo on any fret.
Answer: The chord shapes are shown as if the capo is at the nut of the guitar. This way, it's easier for a beginner. So, the 'E7' is what is actually played, as if the guitar starts at fret 2, but the sound will be F#7.If they called it 'F#7', the player would (over) compensate, and play it two (more) frets higher. It's done this way to get the voicing of the chords to sound as they do.


How to interpret the capped binomial deviance as rating model fit in two player games?

Question: In two player games using rating algorithms like Glicko, the capped binomial deviance is being regarded as a measure of the model data fit.
Does anyone know how to interpret this measure? What measure height is regarded as a 'good fit'? Is there any research about this subject that I should read?

This will be of a great help for interpretation of the capped binomial deviance: http://www.englishchess.org.uk/wp-content/uploads/2012/04/ratings.pdf
Comment: Actually, user1983395, that document appears to mention, just in passing, the term 'binomial deviance' (without 'capped')... and it doesn't seem to define it. What is the capped binomial deviance?
Answer: Your linked article says " Smaller values on all metrics correspond to more accurate predictions," (bottom of p.3) so presumably good fits will have values near 0. A better question might be, "What is the cutoff threshhold for a bad fit?"
Regarding the "binomial deviance" metric, the Chess Ratings kaggle contest used it as their evaluation metric and provided the following definition:

$-[Y\log_{10}(E) + (1-Y)\log_{10}(1-E)]$
where Y is the game outcome (0.0 for a black win, 0.5 for a draw, or 1.0 for a white win) and E is the expected/predicted score for White

The metric is undefined for 0 and 100, but values near 0 are good fits and values near 100 are bad fits.
The Kaggle site references Mark Glickman, the current chairman of the US Chess Federation and inventor of the Glicko rating system. Unfortunately they do not provide a specific citation and he has quite a few publications, but if you are interested in learning more about this metric you should dig through his work. http://www.glicko.net/
I can't access the article from my current workstation, but I believe this is the citation:

Glickman, Mark E. "Parameter estimation in large dynamic paired comparison experiments." Journal of the Royal Statistical Society: Series C (Applied Statistics) 48.3 (1999): 377-394.
Comment: thanks for your answer. I wil dig into it. I found the article here: http://wilson.engr.wisc.edu/rsfc/oth_sites/rate/papers/glickman99parameter.pdf


ssh_exchange_identification: Connection closed by remote host remote desktop

Question: I'm trying to connect to my work server using my macbook. in the morning it was working and now its not.
This is what im doing
ssh -vv email@example.com -L 1024:bolton:3389

This is the verbose
OpenSSH_5.9p1, OpenSSL 0.9.8r 8 Feb 2011
debug1: Reading configuration data /etc/ssh_config
debug1: /etc/ssh_config line 20: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to man.softwarehouse.com [18.104.22.168] port 22.
debug1: Connection established.
debug1: identity file /Users/muhammadnadat/.ssh/id_rsa type -1
debug1: identity file /Users/muhammadnadat/.ssh/id_rsa-cert type -1
debug1: identity file /Users/muhammadnadat/.ssh/id_dsa type -1
debug1: identity file /Users/muhammadnadat/.ssh/id_dsa-cert type -1
ssh_exchange_identification: Connection closed by remote host

Also when I can connect when im using my friends wifi !
Comment: Check the verbose logs on the ssh _server_. They will tell you what has gone wrong.
Comment: If it works in your friends network and doesn't in yours, is most likely an problem of your network. Do you have any barriers (firewall/proxies) in your network? or in the host configuration?
Answer: Using TCP Wrappers for access control can cause the vague message above.
Check the contents of your /etc/hosts.allow and /etc/hosts.deny to ensure you are not blocking SSH.


Is there a name for each of the two chords that form a cadence?

Question: Let's say we're in the key of C major (for simplicity). A typical cadence would be V-I, which is G major to C major. Is there are name given for the role each chord play within a cadence?
The reason for this question is that I'm trying to develop some rules for my students when it comes to building phrases in various modes and I'm trying to find a name for the cadential chords at the end of a phrase.
Comment: Sure...when I say "rules" that's what I'm saying. In any complicated musical topic, for every "rule" there are always some ways to negate those rules.
Comment: Consider introducing them as guidelines (or similar), not rules. I find calling this sort of thing a 'rule' can confuse students, because they'll be more exceptions than you can poke a stick at.
Answer: Well, yes:

V-I: Dominant - tonic: authentic or perfect cadence.
IV-V-I: Subdominant (or predominant) - dominant - tonic: another (fuller) authentic cadence.
ii-V-I: Supertonic (or predominant) - dominant - tonic: yet another authentic cadence.
II (V/V)-V-I: Dominant of the dominant - dominant - tonic: (you guessed it) yet another authentic cadence.
IV-V: Subdominant (predominant) - dominant: half or imperfect cadence.
ii-V: Supertonic (predominant) - dominant: another half cadence.
V-vi: Dominant - submediant (tonic substitute): deceptive or interrupted cadence.
IV-I: Subdominant - tonic: plagal cadence.
iv6-V (- I): Subdominant minor (predominant) - dominant (- tonic): Phrygian half cadence (authentic cadence).
It+6/Fr+6/Gr+6 - V (- I): Augmented sixth (predominant) - dominant (- tonic): Half cadence (authentic cadence).

You can substitute iv for IV, i for I and VI for vi, depending on mode, for most of these cases. I didn't list II-V as a half cadence, although it can make a perfectly valid one, because there is a fair potential for ambiguity: is it II-V in the tonic key or V-I in the key of the dominant? This will be context-dependent, and you will find that you will need to refer to the context when teaching.
This list is by no means exhaustive (it misses the Neapolitan sixth as a predominant, for instance), but it does give some insight into how function factors into cadences: cadences tend to fall into some variety of half, authentic, deceptive or plagal, and the functions of the chords involved tend to be some variety of subdominant (or substitute), dominant (or substitute, e.g., vii°) or tonic (or substitute).
It is sometimes simpler to refer to a chord that leads into the dominant as a predominant, because they will sometimes partake of mixed function. V of V, for instance, is almost a "super-dominant", and the French sixth combines a gapped dominant seventh of the dominant over a descending leading tone bass (♭6 moving to 5), so works both as a dominant and a subdominant. (Augmented sixths can act as dominant substitutes as well as predominants. I would contend that jazz tritone dominant substitutions are really just mixed function augmented sixths.)
In a modal context, using v as a dominant is a bit rare (due to the fact that, without the leading tone, v doesn't much sound like a dominant). Plagal (iv-i, Iv-i, iv-I and IV-I) and plagal-like cadences involving ♭VII6 or ♭vii6 are going to be common in modes lacking V. In Pop music, where parallels are not necessarily a consideration, you may find ♭II or ♭ii used in plagal-style cadences as well. Half cadences in very minor modes like the Phrygian will tend to move to the subdominant as well (e.g., i-iv).
Comment: There is a scheme for naming the chords depending on their context - just as I have listed above. The name of the cadence itself tells you the role of the two or three chords taken as an ensemble.
Comment: Thanks for the answer. After reading it, I don't think it answers what I'm asking. I understand how cadences are created, but I want to know if there is some sort of scheme for naming the role of the two (or three) chords in a cadence.
Comment: @Patrx2 the way I interpreted the OP's question was to paraphrase it as something like "if the basic idea of a any type of cadence is a progression of two chords X and Y, is there a generally accepted name for 'chord X' and 'chord Y'?". (And I suspect the answer is "no, because this isn't a very useful way to characterize cadences").
Comment: @alephzero, which leaves us with subdominants (predominants in a more general sense), dominants and tonics, and chords that _act_ like these. I quite agree that adding a level of indirection (which is what I suspect OP is doing) isn't very useful: so much of common practice harmony depends on the asymmetry of effect of dominant regions versus subdominant regions relative to a tonic (on the level of tonal regions as well as at the chord and phrase level) that trying to abstract this away, even in the early stages of instruction, is not doing the students any favours.
Answer: The perfect (authentic) cadence - V>I, is dominant > tonic, or root. [G>C]
The imperfect (half)cadence is the opposite - I>V, tonic to dominant. [C>G], leaving us dangling, as we were going home, but now...
The plagal cadence ends on tonic, Amen. sub-dominant>tonic. [F>C]
The interrupted (deceptive) cadence is usually dominant to submediant. V>vi [G>Am], nearly home, but home's changed subtley.
Comment: Most of us like to put labels on whatever we can, but there's already labels on the cadences, and after all, there's only two chords involved in each, and the penultimate is the same in different cadences. So, I don't think there's any point in pinpointing it any more than it is.
Comment: I know about the types of cadences (perfect, imperfect, plagal and deceptive). That wasn't exactly what I was asking, but thanks for the quick reply anyways. Let me give you an example: in the V-I perfect cadence, perhaps the V is called the "preparer" chord and the I is called "the finisher". I'm just making stuff up here of course. Are there any proper terms for their roles. By my. Among scheme, the IV in the plagal cadence would also be the "preparer".


Difference between perfect 4th and perfect 5th

Question: I've recently been learning about interval ratios and about why some intervals are more consonant or dissonant than others.
I was trying to find out about the order of intervals by consonance/dissonance. While there's discrepancies later in the list, I kept reading that it in order of consonant to dissonant, it goes: Unison, Octave, Perfect 5th, Perfect 4th... and so on.
What I'm confused about is that if you consider an interval, it depends which note you consider the root note. So a P5 can be considered a P4 if you switch the root note, and vice versa. Their frequency ratios even have a close relationship.
So why then is a P5 always considered "more consonant" than a P4 when they can be kind of considered having the same sound. Am I the only one who thinks they sound the same?
Any answers are greatly appreciated, thank you :)
Edit: Here's a little bit of context if anyone cares to read further.
I'm actually writing a program to try and demonstrate visually all the not relationships between notes in a chord and I was looking for a visual way to show which relationships are more dissonant than others (probably by color: blue = consonant, red = dissonant).
The only thing is, the program represents the notes in the chord using a graph, but each note in the graph is irrespective of its octave position. That is, each node on the graph only shows the note letter, for example. If a user selects C4 and C5, the graph will display a single node "C".
This is why it's important to me to figure out how to work out how dissonant intervals are when they can be considered differently by switching which note is the root.
Images below (I find these 2 to sound pretty much the same so that's why I'm unsure about why one should be more consonant than the other):
Comment: Part of the problem with this area of discussion is that there are at a least two kinds of dissonance/consonance.  One is acoustic, and has to do with frequency ratios, which is often discussed (but also waveform, which is rarely discussed).  The other is musical, or perhaps better, functional, having to do with instability and stability, and that is cultural, so it varies.  For example, 20th century music, especially jazz, treats chords that were formerly dissonant as consonant.
Comment: @MichaelCurtis I think it comes up a lot because even though it's Music Practice & Theory, it's still StackExchange and therefore draws a lot of people in computer science and related fields.
Comment: I wonder what the musical application of this dissonance thingy really is. :) Many people seem to be interested in it. I like "dissonant" intervals, and a lot of the time, adding a third note makes the harshness go away. C-B is "dissonant", but E-C-B is not. C-D is "dissonant", but C-D-B is a bit less so. Anyway, an interval of a fourth points to the higher pitch as a root candidate. An interval of a fifth points to the lower pitch as a root candidate. In C-F, F is root'ish, and in F-C, F is root'ish. This can be seen in chord inversions. G-C-E is a C major, and E-C-G is a C major too.
Comment: Why write a harmony program before understanding basic harmony concepts? This comes up a lot on this forum and I don't know why.
Comment: If by dissonance you mean "roughness" like Plomp & Levelt, and if you're trying to create some kind of a magic formula for making nice chords based on the assumption that "roughness = bad", there is quite a lot of discussion on it on this site. Read these questions and answers, and the source material referenced in them https://music.stackexchange.com/questions/4439/is-there-a-way-to-measure-the-consonance-or-dissonance-of-a-chord/6556#6556

https://music.stackexchange.com/questions/88564/i-want-to-create-chords-from-solely-interval-structure-as-opposed-to-building-up/89684#89684
Comment: @MichaelCurtis Could you direct me to some 'basic' harmony concepts I should learn before looking into this? Theodore is also correct, I do play piano, but I am a mathematician at heart, so this sort of thing gets me excited.
Comment: Well known books I've recommended are Kostka/Payne, Harmony; Piston, Harmony (1st ed.); Mann/Fux, Study of Counterpoint, or another counterpoint book like Piston's. Intervals and counterpoint are the principle study areas. In super-broad terms, the issue isn't about acoustics and ratios, but about the aesthetic consonance of a root position major triad, and instability and dissonance being - on the whole - anything else.
Answer: It doesn't matter which tone is the "root" or the lower of the two.
An interval is just a measure of distance.
Using octave numbers with letters makes it a bit easier to talk about without staff notation.
C4 to G4 is a perfect fifth whether you measure from C4 up to G4 or G4 down to C4. It spans 5 letters CDEFG and so is a fifth of some kind. It is 7 half steps and so a perfect fifth.
G3 to C4 is a perfect fourth whether you measure up from G3 to C4 or C4 down to G3. It spans 4 letters GABC and so is a fourth of some kind. It is 5 half steps and so a perfect fourth.

I was trying to find out about the order of intervals by consonance/dissonance.

For some reason this is a fairly common interest with people learning about intervals. There are two main ways to consider it.
First, intervals expressed as ratios are considered more consonant for simpler, smaller number ratios with 1:1 - the unison - being most consonant, 2:1 - the octave - next most consonant, 3:2 - the perfect fifth next, etc. etc. You might call that the mathematical or acoustical approach.
The second approach is the stylistic approach that depends on aesthetics and the system of harmony used. In common practice era harmony you really have only two categories: consonant for major/minor thirds, sixths, and perfect unisons, fifths, and octaves, and dissonant for all other intervals. Beyond that you can distinguish perfect and imperfect intervals, or relative stability for things like chord inversions, but those get into the details of counterpoint, chord balance, etc. and strictly speaking those elements are not about consonance/dissonance.
This may seem contradictory, for example, if dissonance is unstable, isn't consonance stable? To some degree "yes", but there isn't a clear link. Consider that while an inverted major chord is less stable than a root position major chord, both are considered consonant. Could you place those two chords on a spectrum of consonance? Not really. There is no measure to do so. The distinction between the two chords would not be expressed in terms of consonance/dissonance, but in terms of stability.
From that perspective, in common practice style, you can't really says something objective like a sixth is less consonant than a third. Somethings like a minor second being more dissonant than a major second seem fairly obvious, but a lot has to do with context - a chromatic minor second will sound more "jarring" than a diatonic minor second - and contrapuntal treatment would not be different in terms or preparing/resolving a dissonance.
In the second, stylistic approach there isn't a gradation of dissonance, but two categories - consonance and dissonance - with certain part writing conventions associated with various aspects of the two categories.
Comment: _"Could you place those two chords on a spectrum of consonance? Not really. There is no measure to do so."_ According to this accepted answer that currently has a whopping 79 upvotes, there indeed is a measure for placing any combination of pitches somewhere on a dissonance spectrum https://music.stackexchange.com/questions/4439/is-there-a-way-to-measure-the-consonance-or-dissonance-of-a-chord/6556#6556  :) For at least some meaning of "dissonance". I'm inclined to somewhat disagree on the usefulness of that "measure", but it's a measure and there's even published "science" or something on it.
Comment: @piiperiReinstateMonica, are you talking about the answer regarding "roughness?" The article that says in its opening that dissonance is "hard to measure quantitatively?" There is good reason to distinguish between acoustical dissonance and musical dissonance. There are _acoustical_ rankings, but they don't match up to common practice treatment. P4 versus M3/m3 is the obvious disparity. The point of my answer is to explain that disparity... and how to measure an interval.
Answer: The fourth and fifth are not the same interval; they are inversions of each other. Intervals are always computed from the lowest note.
A perfect fifth has a ratio of 3/2.
A perfect fourth has a ratio of 4/3.
(I'm not sure why "perfect" but it's probably because the F-C and C-F intervals are bordered by half steps.) Perfect intervals have only perfect, augmented, and diminished forms.
The whole thing of consonance and dissonance is a bit complicated; it's not entirely related to ratios. The fourth is treated as a dissonance against a bass note but a consonance against an upper voice.
Comment: Hey thanks for responding, I'm not sure I fully understand, but I need to read this again when my brain isn't so tired. Do you reckon I might be able to ask you further questions about it, maybe by email or discord or something? I saw you are a retired math professor, and I thought I could show you my program and you might be able to help me with it. Otherwise no worries.
Comment: @JohnSmith If you're looking for a more open-ended discussion, please consider The Practice Room, the primary chat room connect to this site.
Answer: As suggested in a comment, there is an acoustic aspect to consonance and dissonance:
Harmonic partials
In (perhaps overly-) simple terms, the sound of a single note is composed of many individual frequencies.  Collectively, these are called "partials".  For most pitched musical instruments, the partials are (at least approximately) "harmonic", meaning they occur at frequencies that are whole-number multiples of the fundamental frequency.  (For example, an A2 contains 110 Hz, 220 Hz, 330 Hz, 440 Hz, etc.)  The partials generally decrease in amplitude with increasing frequency.†
Consonance
When two notes are played together, one aspect of the perceived consonance between them arises from the alignment of the partials in one note with those of the other.
Fewer partials align in a perfect fourth than in a perfect fifth.
Further details
The intervals analyzed for consonance below are based on just intonation (JI), which uses whole number ratios between pitches. The equal temperament (ET) system in wide use now is a compromise based on the uniform, irrational ratio of 21/12 between semitones.  The ET equivalents are close, but the JI ratios make for neater presentation of the numbers.‡
An octave corresponds to a frequency ratio of 2/1.  The perfect fourth corresponds to a ratio of 4/3 and a perfect fifth is 3/2.
Consider the fundamental of the root note to be 1.  (It doesn't make a difference which basis frequency we use, so this just makes the numbers easier to read.)
The root note contains partials at these relative frequencies:
1, 2, 3, 4, 5, 6, ...
A note one octave higher contains these relative frequencies (all partials of the root note, each multiplied by 2):
2, 4, 6, 8, 10, 12, ...
You can see from the above that every partial of the octave corresponds exactly with a partial of the root.
A note a perfect fifth above the root contains these (each multiplied by 3/2):
3/2, 3, 9/2, 6, 15/2, 9, ...
A note a perfect fourth above the root contains these (each multiplied by 4/3):
4/3, 8/3, 4, 16/3, 20/3, 8, ...
I've bolded the partials of the perfect fourth and fifth that align with partials of the root.
Every second partial of the perfect fifth aligns with a partial of the root, while  only every third partial of the perfect fourth aligns.  The perfect fifth has more partials that align and sounds more consonant as a result.
For comparison, let's also look at another consonant interval, the major third (with a ratio of 5/4) and its less-consonant inverse, the minor sixth (with a ratio of 8/5):
A major third contains these (multiplied by 5/4):
5/4, 5/2, 15/2, 5, 25/4, 15/2, 35/4, 10, ...  (Every fourth partial aligns.)
A minor sixth contains these (multiplied by 8/5):
8/5, 16/5, 24/5, 32/5, 8, ... (Every fifth partial aligns.)
In addition to the quantity of partials in alignment, consider that the higher-order partials are generally weaker in amplitude and contribute less to the perception of consonance or dissonance.  The more-consonant intervals contain alignments of lower-order partials.
Notes
† Some instruments (e.g. pitched percussion) may have significant partials that are substantially inharmonic.  Some instruments (e.g. piano) have partials that are slightly inharmonic.  The relative amplitude of the partials varies over time and some may be entirely absent.  The composition is a large part of the specific timbre of each instrument
‡ An ET perfect fourth has a ratio of about 1.3348, a bit sharp of JI.  An ET perfect fifth has a ratio of about 1.4983, a bit flat of JI.  The third and sixth are further out-of-tune in ET.
Answer: I have some bad news for your app project: It's impossible to rank intervals as being more or less dissonant than others. "Consonant" and "dissonant" are subjective words,* equivalent simply to "sounds good" or "sounds bad." And people in different places and times in history haven't even agreed about what sounds good. And even within a single genre or practice, a given interval might sound "better" or "worse" depending on the chord it's used in and what's going on around it. So whatever source has been telling you that they can be ranked is perhaps something you shouldn't continue paying attention to.
As to why you hear a similarity between P4 and P5: First of all, you've discovered complementation! They are related, just as 2nds are to 7ths and 3rds are to 6ths. And as for why this pair seem even more closely related than others, they're the "most similar." If you split an octave exactly in half, you get a "tritone," which you can spell either as an augmented 4th or a diminished fifth; for instance, a C up to an F#. If you go up from the F# to the next C, you still have a tritone. You have a dim. 5th rather than an aug. 4th, but you have the same number of half steps. Well, aside from this "identical" inversion, the next step away from the "exact middle" of the octave gives you the P4/P5 pair. The "difference" between the two is the least of any pair, without being (enharmonically) identical.
P4 and P5 also have a relationship in triadic harmony. A simply triad, like C major, contains C, E, and G: a fifth, with a third in between it. If you move the C to the top, you have a P4 on top, but the E still helps you identify it as a C major chord.

Meanwhile, the C minor triad has the same fifth but a different third. Its E flat identifies it as minor no matter the inversion.

But if we delete the third from the chord entirely...

... then we can't say whether these are major or minor chords. We have "modal ambiguity." These "open chords" feature in a lot of contexts like various folk musics, or rock power chords. Judith Kuhn uses the term "fourthy-fifthiness" to describe Shostakovich's second string quartet and its "power chords" as three instruments play either fourths or fifths in the opening:

(Embedding a video with score, though I prefer the St. Petersburg Qt. performance.)

* At least the way we're using them here; see phoog's comment about a more scientific usage.
Answer: Intervals are named from what 'space' there is between the lower and higher notes, along with the note names, which gives the number of those intervals. So C>G is P5, while G>C is P4.
The difference, though, is C>G is deemed consonant as G is a harmonic of C,(the 2nd, and audible when C is played on many instruments) whereas G>C is dissonant as C is not a harmonic of G. At least not a particularly close one to note G - inaudible on most instruments.
So, on the face of it, while they both sound the same two notes, C>G is P5 and consonant, G>C is P4  and dissonant.
Comment: I don't think this holds up, since whether P4 is consonant or dissonant depends on context. Also, thirds were considered dissonant for a few centuries, and major thirds, at least, are fairly nearby in the harmonic series. Also, the question doesn't claim that P4 is dissonant — only that it less consonant than P5.
Comment: @Aaron - the two terms seem to have been bandied about for a long time, and probably these days don't really have the same meaning as original. In fact, they're, to me, meaningless. But I just thought this may be a non-scientific way to explain the difference the OP searches for.
Answer: Sometimes in music theory we can deal exclusively with pitch classes, a C is a C irrespective of octave.  A perfect 4th and its inversion a perfect 5th are completely equivalent.
Sometimes we can't. It matters which note is on the bottom.   C - G sounds like ^1 - ^5, the most stable interval there is, bar a unison or octave.   G - C sounds like ^1 - ^4 or ^5 - ^1.   Not a chord you'd choose as the final one of a piece.
Comment: Yup!  And now I have...
Answer: I agree with Theodore's answer  that we need to consider the harmonic series aspect of the 2 intervals.  As you can see in this graph showing harmonic amplitudes of a flue organ pipe, we can see the decreasing amplitudes as the harmonic numbers become higher.
Here's a comparison between the first 6 harmonics of perfect 5th (root=C1) and perfect 4th (root=G1).

Perfect 5th (root = C1): c1 c2 g2 c3 e3 g3 and g1 g2 d3 g4 b4 d5The sorted harmonics we hear: c1 g1 c2 g2 g2 c3 d3 e3 g3 g4 b4 d5

Perfect 4th (root = G1): g1 g2 d3 g4 b4 d5 and c2 c3 g3 c4 e4 g4The sorted harmonics we hear: g1 c2 g2 c3 d3 g3 c4 e4 g4 g4 b4 d5

Notice how within the first 2 octaves of the harmonics:

in the perfect 5th (root = C1) all 6 notes are C's and G's, even with a doubling of g2.
in the perfect 4th (root = G1), only 5 notes are C's and G's, with a d3 interfering next to a c3!  The doubling of g4 is in the 3rd octave above the root, so it doesn't help much.

Therefore, the above acoustic analysis should show how (in theory) the perfect 5th is more consonant than the perfect 4th, especially when the sound is produced by a an instrument with a "natural" tonal characteristics such as wooden flue pipes in a pipe organ.


Scald : How to add several medias to a node using entity metadata wrapper?

Question: I'm looking for a solution to my problem that is pretty simple in fact.
I'm on an importing task in which I have to create programmatically a node and then populate all its fields.
As we're using the Scald module, we can add several medias to a node. But I can't figure out how to associate several medias to a node ?
I tried the following :
foreach ($file_atoms as $i => $atom) {
    $node_wrapper->field_atom[$i] = $atom->sid;
}

or :
foreach ($file_atoms as $i => $atom) {
    $node_wrapper->field_atom[$i]->set($atom->sid);
}

But I get the following error :

Error: Cannot use object of type EntityDrupalWrapper as array

I followed the doc on this page but it does not seems to work..
Can somebody help me ?
I'm encountering the same problem with taxonomies : I'm not able to set multiple values to the node wrapper.
Comment: Are you sure the `field_atom` field has the option of taking multiple medias?
Comment: Good question, the field is not configured for several medias... Thanks
Answer: Your issue is that your field_atom field is not configured as multiple.
When it's not, an EntityDrupalWrapper object will give you direct access to the field, instead of having to go through the 0 delta.
Just fix the field_atom options to accept multiple medias, and your code will work fine.


drush appears to not be respecting --no-backup

Question: My server has a great backup system in place.  I do not need additional backups dropped into my home directory.
Reading the drush docs gave me the impression that the <code>--no-backup</code> option, would instruct drush to not make a backup.
<code>$ drush --version
drush version 4.5
</code>
When I update a module with the --no-backup option it seems to be ignored.
<code>$ ls ~/
creds
$ drush dl drush --no-backup --yes
Would you like to back up your current drush version 4.5 to /home/username/drush-backups/unknown/20110823223228 and replace it with drush 4.5? (y/n): y
drush backed up to /home/username/drush-backups/unknown/20110823223228/drush  [ok]
Project drush (7.x-4.5) downloaded to                                [success]
/srv/www/_drupal_.example.org/drush.
Drush successfully updated to version 7.x-4.5.                       [success]
$ ls ~/
creds  drush-backups
</code>
Am I missing something obvious here?  I have tried changing the order of the parameters, but that doesn't seem to make any difference.
Comment: I'm voting to close this question as off-topic because it's a bug report for a contributed module, and needs to be dealt with in the module's issue queue
Answer: This is a Drush bug, and would best be raised in the issue queue.  By coincidence, someone recently posted this: http://drupal.org/node/1741108


How to handle findElements result?

Question: Code 1
resultsBoard.findElements(By.css(mySelector)).then(function(elements) {
  elements.forEach(function(val, idx) {
    elements[idx].getText().then(function(text) {
        console.log(text);
    });
  });
});

Code 2
resultsBoard.findElements(By.css('mySelector')).then(function(elements) {
  for (var idx = 0; idx < elements.length; idx++) {
    elements[idx].getText().then(printText(text));
  }
});

Code 1 works well and retrieves the text of all the elements that matched my selector.
Code 2 gives me a

ReferenceError: text is not defined

What is the difference? Why does this happen?
Answer: The 2nd snippet adds calling parenthesis that invoke the function (printText) immediately, expecting text to already be defined. These parenthesis aren't present in the 1st snippet.
elements[idx].getText().then(printText(text));

// is equivalent to...

var _result = printText(text);
elements[idx].getText().then(_result);

To provide a named function as an argument, you'll want to just use its name as a variable:
elements[idx].getText().then(printText);

Comment: It is perfectly clear now. My JSHint Gutter was telling me to create a function outside and i ignored that printText function. I was expecting the difference to come from the forEach. Thanks
Answer: In the first example:
elements[idx].getText().then(function(text) {
   console.log(text);
});

The .then(function(text)) part is actually giving a name (text) to the data that you get from getText(), so you can use it in the next line. You are not doing this in the second example.
So you should rewrite your second example to something like this to get it to work:
resultsBoard.findElements(By.css('mySelector')).then(function(elements) {
  for (var idx = 0; idx < elements.length; idx++) {
    elements[idx].getText().then(function(text) {
      printText(text);
    });
  }
});

How to handle findElements result?


get magento module config data in Observer

Question: I created a module with an observer for the sales module with event hook 'sales_order_shipment_save_after' ,
My module has the following files

Company/Modulename/etc/config.xml
Company/Modulename/etc/system.xml
Company/Modulename/Model/Observer.php

there are four fields in the modules admin configuration fields
I want to get those saved data in the Observer class.
using $this->getConfigData('password'); gives a

Call to undefined method

error
Any suggestions?
Answer: Magento uses a static method on the global Mage application object to get configuration values
$config = Mage::getStoreConfig('section_name/group/field'); //value
$config = Mage::getStoreConfig('section_name/group'); //array

Comment: The group feature is a huge bonus as you can Mage::log($config) and see what all the options are and if you have labelled them properly - thanks for that!
Comment: Your tutorials related to Magento are awesome. Helps a lot. Thanks.
Answer: An amendment to Alan's completely correct answer.
Along with path as first parameter, getStoreConfig also accepts storeid as second parameter(optional).
Well, this is useful when you want to retrieve store-wise values.
Alan has mentioned this point in his own tutorial. I guess, he has not mentioned here just because OP has not mentioned this requirement in his question.
Please refer this
Answer: In a shipment module I can use $this->getConfigData for fields in system.xml, but in another kind of modules sometimes not, e.g. extends Mage_Core_Model_Abstract, than I must use getStoreConfig. So the answer is you don't have to use always getStoreConfig. But I don't know why ...
Answer: getConfigData is just defined in a shipment class and uses getStoreConfig too. A little confusing that some functions are extra defined and unneeded in fact ...


Trying to find the longest string in an array in Ruby

Question: how do I find the longest name in an array in ruby.  here is what I tried:
people = ["john", "clark", "stan", "mike", "nick", "devon"]

def find_longest_name(people)
  longest_name = nil
  longest_name_length = -1
  people.each do |friend|
    if friend.length > longest_name_length
      longest_name = frined
      longest_name_length = friend.length
    end
  end
 return longest_name
end
puts "#{longest_name_length}"

I am getting an error that says I have an undefined variable.
Comment: `frined` != `friend`
Comment: *Which* error do you get? Please, read the *entire* error, it will *tell* you a) *exactly* where to find the undefined variable and b) what the *precise* name of the variable is. Look at the name. Are you 1000000% sure that that is the name of the variable?
Comment: In `puts "#{longest_name_length}"`, `longest_name_length` is defined inside method definition. Will not be accessible from outside.
Answer: Try this one
people.max_by(&:length)

You mispelled friend into frined at this line
longest_name = frined

Answer: For maximum
people.map(&:length).max

For minimum
people.map(&:length).min

If you want length for max string
h = {}
people.map{|a| h[a]= a.length}
h.key(h.values.max)