Layer 2/3 Switch recommendations

Question: Looking at setting up VLANs for a quickly-growing office (6 servers, 60 workstations, probably adding another 10 within the next month or so). I need to do inter-VLAN routing and ACLs (layer 3, packet filtering if possible); QoS would be beneficial, but not necessary.
Here's my (likely) impossible wish list:

GbE x 24 -- if I'm buying a new core switch, I want Gigabit.
Layer 3 routing (RIPv1/2) or "static routing" with a decent sized routing table limit (think the ProCurve 2610 was 8, which is too small)
Layer 3/4 ACLs (packet filtering): I don't want to do router-on-a-stick to achieve any sort of decent firewalling between the VLANS.
(the kicker) under $1500

Nice to have:
1. QoS
Any recommendations?  It seems like I need something between a 2600 series and a 2900 series, possibly from another manufacturer, but I'm really drawn to HP ProCurve's good reputation and lifetime warranty.  Will consider other vendors though.
Answer: No way you can get something that would satisfy all these requirements. Especially #4: a smart GigE switch will run in the neighborhood of $100/port. Of course, you always have the linksyses and netgears of this world, but I wouldn't trust them to run anything more complex than VLANs, some basic trunking and routing with no ACLs.
Among the more reputable vendors, ProCurve is the most budget friendly, and you seem to know enough about them to figure out what would fit (or rather that nothing would fit) on your own.
And one more thing: router on a stick is not such a bad idea, especially if you have robust virtual environment. Just last week I deployed a pair of pfSense virtual appliances, and I couldn't imagine an easier way to get a capable router in my environment at almost zero (CPU and memory consumption of that appliance are negligible) cost. With that requirement gone, you could get much simpler and cheaper switches.
Comment: I have deployed a few embedded installs of pfSense on ALIX hardware for edge firewall/routers, but with your virtual environment, are you doing any interVLAN routing between physical hardware?  With 60 odd workstations chatting across VLANs to the servers (and with the VM overhead), I can see that becoming the bottleneck (which essentially the router-on-a-stick model is).
Comment: I don't have my own numbers to show for it (the routers are not in a high traffic environment), but I would venture a guess that with six servers you should be fine with a pair of teamed pNICs dedicated to the router VMs. The only two scenarios where it won't be enough are high bandwidth data stream generation (multimedia), or very fast storage that the clients consume at max speeds. Regular small office stuff (low-end file servers, AD, mail) never needs full GigE bandwidth. Just capture your current traffic utilization, and you'll be able to say if my suggestion is crap.
Comment: I think I'm going to use Herculean strength to get the client to commit to the 2910AL over a 3-year lease if necessary (with a low buy-out after), as with the lifetime warranty, it'll service them for years.  I will play around with pfSense on a teamed NIC/VMWare setup though.

Layer 2/3 Switch recommendations


GAM with many binary factors

Question: I am trying to model the blood glucose response at 15-minute intervals after a meal. The meal event has many continuous variables (like time of day, body weight, etc) and many binary variables (like butter, bread, breakfast, etc).
I have tried several approaches. One is to use all of the factors as by-variables, like this:
glucose ~ gam(s(time, by=butter) + s(time, by=bread) + s(time, by=breakfast) + s(weight) + ...)
Another option is to multiply all of the binary variables by time, so that they become smooths of their own:
glucose ~ gam(s(butter*time) + s(bread*time) + s(breakfast*time) + s(weight)
Are either of these on the right track? Is there a better way to handle all these binary factors without losing the time dependency? (E.g. the effect of butter should be smooth between 15 minutes and 30 minutes).
Another option that I am considering is decomposing the glucose signal into ~3 principal components and then training seperate GAMs for these. Then the binary factors could be treated as simple linear predictors.
Thank you for your help!
Edited to include more details as requested.
Comment: Do you have non-categorical predictor variables?
Comment: Can you show or describe your data structure? If seems to me that you will have glucose measured repeatedly at 15 minute intervals after a meal with a series of constant values that pertain to the meal. So `glucose` measured every 15 mins for subject A after meal 1, and `bread`, `butter` etc are constant vectors of values for this subject and meal combination, with values `0` or `1`  depending on whether the indicated food stuff was consumed as part of the meal.
Comment: You need to give us some more context! Questions with some interesting context tends to generate ore interest ...
Comment: @Dave, yes, there are many continuous predictors as well.
Comment: @kjetilbhalvorsen I'm trying to predict the blood glucose response  to meals. There are continuous variables (e.g. time of day, body weight, etc) and binary variables (e.g. butter, bread, breakfast). Thank you in advance for any tips!
Comment: I'm now thinking of using PCA on the time-series targets to get rid of the time-dependency, and then using seperate GAMs to the target the different PCA components. Does that make any sense? It still has the binary variable problem though. I guess those should just be modeled as non-smooth (linear) contributors.
Comment: Please add this new info to the post as an edit:  Please do not give new information only in comments, edit
 your question to add the new information. We want posts to
 be self-contained, comments can be deleted, and anyhow,
 information in comments are not well organized. Also, many
 people do not read comments.
Comment: Thank you @kjetilbhalvorsen, it is edited with more details.
Answer: You're assuming that the audience here knows quite a lot about your particular subject area and specific task. I'm also going to assume your pseudocode was just a thinko as it is gam(y ~ s(x) ...) not y ~ gam(s(x) ...).
A first problem is that in any model with a by factor smooth you need to include the factor as a "fixed" effect to include the group means. So if one went for a by factor model you'd need something like
gam(glucose ~ bread + butter + breakfast +
      s(time) +
      s(time, by = bread) +
      s(time, by = butter) +
      s(time, by = breakfast),
    data = meals, method = "REML", family = Gamma(link = "log"))

where I would (instead of the standard factor by model, but note I don't think this is what you want - read on) code bread, butter, breakfast etc as ordered factors. That way we'll get the smooths set up as a smooth of time for the all zero combination (assuming you have those?) of the factor variables, and then the by factor smooths will be parameterised as deviations from this reference level "meal food stuff combo".
In other words your s(time) if you code the factors covariates as ordered factors will represent the reference way glucose varies over time post meal, and the other smooths will reflect smooth deviations from this reference time course.
I can think of other ways in which we might have a smoothly varying effect of the food stuffs. You could do the same model as above but with standard factors; though I don't think this will get you what you want as the smooth of each food stuff by time  will be some smushed up average of all the meals in which that particular food stuff was consumed.
The problem with both of these models is that we will get two smooths per food stuff, one for the not-consumed (0) case and one for the consumed case (1), and that is likely not what you want.
Another model might be to treat these food stuff variables as continuous variables and fit
gam(glucose ~ s(time, by = bread) +
      s(time, by = butter) +
      s(time, by = breakfast),
    data = meals, method = "REML", family = Gamma(link = "log"))

How this model differs is that here we are fitting
$$\text{glucose} = \beta_0 + f(\mathtt{time}) \mathtt{bread} + \cdots$$
compared with something like this for the factor by model
$$\text{glucose} = \beta_0 + \gamma_{\text{bread}} + f_{\text{no bread}}(\mathtt{time}) + f_{\text{bread}}(\mathtt{time}) + \cdots$$
It's kind of cheating, but in the first equation above, note that we are multiplying the smooth of time by the numeric value $\mathtt{bread}$
$$f(\mathtt{time}) \mathtt{bread}$$
and if $\mathtt{bread} = 0$ then we get no contribution at all from the bread, whereas in the second equation (the one for the by factor model) we will get a smooth of time base on all the meals in which which bread was not consumed and that doesn't sound useful to me.
You could create all possible combinations of food stuffs observed in the data set, create a factor from that variable and use that to fit a whole bunch of smooths, sort of like this (in pseudocode)
meals <- transform(meals,
                   food_stuff = interaction(bread, butter, breakfast,
                                            drop = TRUE))

gam(glucose ~ food_stuff + s(time, by = food_stuff), ....)

but that could end up creating a huge number of smooths (each using 9 parameters each by default) if you have even a modest number of food stuffs.
Whether the continuous version works will depend on whether you need some indication of how blood glucose changes over time post meal or not. For example, you might want:
$$\text{glucose} = \beta_0 + f(\mathtt{time}) + f(\mathtt{time}) \mathtt{bread} + \cdots$$
and set up the smooth for the by term to have a penalty on the first derivative so that it penalises deviations from the average glucose time course:
gam(glucose ~ s(time) + s(time, by = bread, m = 1) + ....)

where the m = 1 will set the penalty to be on the first derivative, (i.e. deviations from a constant function).
What you want will depend on how you understand glucose to vary over time with different combinations of food stuffs and that's not something we can help you with unless you actually spell this out in your question. Even then you're likely to want to seek local support as this seems like a relatively complicated modelling exercise requiring some detailed input from a statistician.
Comment: Thank you @GavinSimpson, this is really helpful! I will definitely take this as a jumping-off point and find someone locally to help further. Also, thank you for your website :)
Comment: @GavinSimpson Is `m=2` the default in `s()`? What is the reason that `m=1` in `s(time, by = bread, m = 1)` is preferred as opposed to `m=2`?
Answer: First of all you are not handling serial correlations in the data.  This will lead to suboptimal fits and lack of a proper basis for confidence intervals, etc.  To remedy that, think of a first-order Markov model or generalized least squares with an AR(1) correlation structure.
Depending on your effective sample size you may have included too many interactions in the model.
In terms of model specification I think it may be more logical to include both absolute time and time since the last meal in the model.  Absolute time can handle circadian and other rhythms, and for that purpose you might use a regression spline with 7-12 knots.  Time since the last meal will be a time-dependent covariate and can be modeled with fewer knots in a regression spline to allow for a smooth decay function.
Interactions is a tough one but you might think about quantifying the amount of carbohydrates in the last meal as an interacting factor (or just as a main effect) instead of looking at particular foods.  Some sort of dimension reduction such as that may be needed.

GAM with many binary factors


Getting a null when trying to query data from different models - Nodejs

Question: I have a model transaction and it has a column transaction_id. This transaction id can be connected to different other models using their respective _ids.
But how does it know this id is from transfer model or deposit model?. The transaction model has another column called type, which can either be transfer or deposit And this is how it'll know the model being referenced is either deposit or transfer or withdrawal.
So I have tried to create an api route to return the transaction details with the respective connected model details. The problem is, I am getting a null value on the transaction_id. Someone kindly help
router.get("/transactions", isAuth, async (req, res) => {
  try {
    const transactions = await Transaction.find({
      user_id: req.user.id,
    }).populate({
      path: "transaction_id",
      model: req.body.type == "transfer" ? Transfer : Deposit,
    });

    if (!transactions) {
      return res.status(400).send({ error: "Transactions not found" });
    }

    res.json({ success: true, transactions });
  } catch (error) {
    return res.status(500).json({ success: false, message: error.message });

  }
});

Answer: it looks like the problem is with the req.body.type in the model property of the populate function. To get the value from the request body, you should use req.query.type instead of req.body.type as the GET request does not have a request body. try this-
router.get("/transactions", isAuth, async (req, res) => {
  try {
    const transactions = await Transaction.find({
      user_id: req.user.id,
    }).populate({
      path: "transaction_id",
      model: req.query.type === "transfer" ? Transfer : Deposit,
    });

    if (!transactions) {
      return res.status(400).send({ error: "Transactions not found" });
    }

    res.json({ success: true, transactions });
  } catch (error) {
    return res.status(500).json({ success: false, message: error.message });

  }
});

Comment: Thanks for this but it still doesn't work


How to replicate this form with exposed filters

Question: I'm wondering how can I achieve something like that "Browse Listing" block (on the right) with exposed filters - http://demo.rlisting.com/rlisting/result
Should I create Content type for each Property type and add Listing type as a vocabulary or to use only one content type for all properties and then add property and listing types as vocabulary or as text fields with select list?
And more importantly how Min & Max range could be created?
using drupal 7.14, views 3.3
Answer: You should create a view, with display page and add some exposed filters.
Then you have to enable the function "Expose form in block", or something like this, that creates a block with your exposed filters.
Comment: I know the basics of exposed filters. I was looking for something advanced and therefore to answer my question - how the example I gave can be replicated and how Min and Max range works with exposed filters.


Use Win32API: unions within structures generate TypeLoadException

Question: I'd like to import an extern function of Win32API.
The Code from the API (in C) looks like this:
typedef struct _BLUETOOTH_ADDRESS {
  union {
    BTH_ADDR ullLong;
    BYTE     rgBytes[6];
  };
} BLUETOOTH_ADDRESS;

My C# implementation looks like this:
[StructLayout(LayoutKind.Explicit, Size = 8)]
public struct BLUETOOTH_ADDRESS
{
    [FieldOffset(0)]
    public ulong ullLong;

    [FieldOffset(2)]
    public byte[] rgBytes;
};

The problem is: As soon as I create the struct, it throws me a TypeLoadException, error Code:
System.TypeLoadException: "Could not load type 'BLUETOOTH_ADDRESS' from assembly 'BleLab, Version=184.108.40.206, Culture=neutral, PublicKeyToken=null' because it contains an object field at offset 2 that is incorrectly aligned or overlapped by a non-object field."
Do you have any idea to fix this or where the problem is?
Best regards
Edit:
Forgot to provide the way of calling:
var ba = new Win32API.BLUETOOTH_ADDRESS();
ba.rgBytes = new byte[6];

Comment: Are you aware what a C `union` is?
Comment: I tried to understand
Answer: There's really no point in trying to declare this as a union. It's an unsigned 64 bit type. Just use ulong instead of the struct.
If you never need to display the address, then you would need to pick out just the first 6 bytes of that ulong. A Bluetooth address is a 48 bit value, hence 6 bytes.
But for your purposes there's nothing to be gained by trying to express that nuance in the type used for interop. Which is why I would recommend working with ulong for the interop and picking out the meaningful bytes if necessary as a separate action.
Comment: Thank you! I did not know the possibility to only write `ulong` instead. It now works!
Answer: To help you understand the error, note the following:

All members of a C union type have overlapping storage that begins at offset 0, so the offset of member rgBytes in your C# struct should use [FieldOffset(0)], not [FieldOffset(2)].
The type of the rgBytes member in the C union is a fixed array of 6 bytes. In your C# struct it is a byte[] array type.  A (normal) array type in C# is a "reference type", which can be thought of as being like a C pointer.  That is, the object just holds a reference (pointer) to a value on the heap.
You can create a fixed array using the fixed keyword as follows:
fixed byte rgBytes[6];
Fixed arrays are unsafe code, so the above needs to be declared unsafe. It is also declared public in your struct, so the full declaration of the rgBytes member can be as follows:
public unsafe fixed byte rgBytes[6];

Putting it all together gives the following C# declaration for BLUETOOTH_ADDRESS:
[StructLayout(LayoutKind.Explicit, Size = 8)]
public struct BLUETOOTH_ADDRESS
{
    [FieldOffset(0)]
    public ulong ullLong;

    [FieldOffset(0)]
    public unsafe fixed byte rgBytes[6];
};

You can probably leave out the Size = 8 part.
As per David Heffernan's answer, you are probably better off just using a ulong, especially as that will avoid any "unsafe" code.
Comment: This is really the wrong way to solve the problem. If you want to enable the access of the meaningful 6 bytes, do that with access methods. Unsafe code, explicit layout, fixed, all needless complexity for no gain.
Comment: @DavidHeffernan True, as I mentioned in the answer, OP is probably better off avoiding the unsafe code, but it's still reasonable to make corrections to errors in the OP's original attempt to translate the C union members into a C# struct. There are also endianness issues with treating a bluetooth address as a `ulong` value when it is really a sequence of 6 bytes.


Overriding node output

Question: I'm currently creating a website on Drupal 8, even if it's still in RC3.
I've been swimming in the sauerkraut since few days now and I still cannot figure it out how to override node output as I could do in Drupal 7.
Because Drupal 8 is not as used as Drupal 7, it's tough to find answers on Google.
So, I'd like to do the following in my twig file(s):

    <?php if ($field_images) { ?>
    <?php
      $img_url = $field_images[0]['uri'];
      $img_alt = $field_images[0]['alt'];
      $img_title = $field_images[0]['title'];
    ?>

      <a data-lightbox="galleryWrapper" href="<?php print image_style_url('lightbox', $img_url); ?>">
        <img src="<?php print image_style_url('album_thumb', $img_url); ?>" alt="<?php echo $img_alt; ?>" title="<?php print $title; ?>" class="media" />

    <?php } ?>

I've seen that I could, as in Drupal 7, override a template file with a specific filename, such as: "field--node--field-images--gallery.html.twig".
The thing is that I don't know where to create my variables that will be available for my twig files (MYTHEME.theme?).
I've already tried this in "field--node--field-images--gallery.html.twig":
{% if multiple %}

    {% for item in items %}

        {#  Before was {{ item.content }} instead of the 5 following lines  #}
        {% if item.content.url %}
          {{ item.content.image }}
        {% else %}
          {{ item.content.image }}
        {% endif %}

    {% endfor %}

{% else %}
  {% for item in items %}

      {#  Before was {{ item.content }} instead of the 5 following lines  #}
      {% if item.content.url %}
        {{ item.content.image }}
      {% else %}
        {{ item.content.image }}
      {% endif %}

  {% endfor %}
{% endif %}

I've tried to access to "url" with {{ item.content.url }}, because {{ content }} seems to call "image-formatter.html.twig", which contains the following:
{% if url %}
  {{ image }}
{% else %}
  {{ image }}
{% endif %}

As you can imagine, it doesn't work.
And, that's another issue, but I've already tried to dump variables but I got this famous WSOD (White Screen Of Death). So, that's very difficult to know what this $variables contains.
Answer: The fields you are looking for are under '#item', for example:
 {{ item.content['#item'].title }}

To set variables for twig put a theme_preprocess_field() function in  MYTHEME.theme.
To examine variables use kint (this is in the devel module):
{{ kint() }}
{{ kint(items) }}

Comment: Thanks! I've tried with _['#item']_ and I have the _.alt_ or _.title_.
I Still didn't find the image url. Even with {{ item.content['#item'].src }}

Any idea?
Comment: And thanks for {{ kint() }}.
I'll try to install devel again. Last time, I had issues.
Answer: (Crosspost with 4k4, slightly different approach and some background info, so still posting)
Yes, preprocess still exists and yes, you can put it in your yourtheme.theme file just like in D7. See template_preprocess_field() in theme.inc for the default logic.
Also see FormatterBase::view() for all the data that is passed to the field template. You can see entity and items in there. Those are basically the raw data.
Accessing them directly in twig is a bit complicated due to the #, You'd need something like {{ elements['#items'].0 }}, you could use preprocess to make that available (note that top-level items is created in the preprocess and something else.
For the url, you should actually be able to access it through content with a similar syntax as above, {{ item.content['#url'] }}.
Comment: Sorry, I meant the image src tag: {{ item.content['#item'].src }}, which doesn't work.
I could retrieve the {{ item.content['#url'] }} and it works fine.

I'll have a look on FormatterBase::view() too.

Overriding node output


A non-normal linear operator can have eigenvalues and eigenvectors?

Question: May I say that only normal linear operators have eigenvalues and eigenvectors?
Comment: no.............
Comment: Why do you think that?
Comment: I was not sure if eigenvalues only ocurr in matrices diagonalized by unitary matrices (Spectral Decomposition Theorem).
Answer: No. The operator $T\colon\mathbb{R}^2\longrightarrow\mathbb{R}^2$ defined by $T(x,y)=(x+y,y)$ is not normal, but $(1,0)$ is an eigenvector and $1$ is an eigenvalue.
Answer: In finite dimension, finding the eigenvalues is equivalent to find the roots of the characteristic polynomial of the operator. So every operator on $\mathbb{C}^n$ and every operator on $\mathbb{R}^{2n+1}$ has at least one eigenvalue (and, consequently, at least one eigenvector).
Comment: In real spaces, why only in odd dimensions?
Comment: Every real polynomial of odd degree has at least one real root. This is not true in the case of even degree, where there are polynomials without real roots (for instance, $x^2+1$).
Comment: Indeed Francesco! Thanks.


Eclipse indents new line with tabs instead of spaces

Question: I've followed all the suggestions here.
When I press return, I get a new line that is indented with tabs instead of spaces.
If I backspace to clear the tabs, and then press TAB a series of times, it correctly indents with spaces.
I'm pretty sure I have all my settings set up correctly.  I created a new Code Style > Formatter policy for every language in the project, and specified to always use spaces.  It seems as though these settings are partially active (ex: when I press tab), but inactive when I use return.  I tried restarting Eclipse.  I'll try restarting the computer now...
I'm using Mac OS X 10.9.2 and a Liferay Developer Studio (1.6.3.v201312111844) version of Eclipse (not sure which Eclipse build its based on though).
Can anyone think of another setting/solution to ensure that newlines are created with spaces instead of tabs?  I recently saw http://editorconfig.org/, and I'm wondering if there's some interference.
Thanks for any suggestions
Answer: If the file has existing lines that are using tabs, then Enter will respect that and try to create new lines in a similar way (see this comment by topchef for a solution). Also, it could be something in Liferay Studio's proprietary settings is overriding Eclipse standard preferences (as suggested by user John).
Keep in mind that each type of editor in Eclipse can have its own preferences and perhaps that's what you're running into here. You can try to find them all by opening Preferences and searching for "indent" in the search field. That will show all the preferences pages where indentation can be configured.

Also note that the Formatter settings don't have any affect on as-you-type formatting; that's for when you select a file or group of files or part of a file and choose Source > Format from the menu.
Comment: Which settings control the 'as-you-type' settings?  I've changed everything I've found, maybe I missed something.

I did Source > Format the whole file, saved it, restarted, etc.  It's still not working..
Comment: Thanks for the screen.  I found those "Typing" settings, and they're set appropriately.  I reformatted my code and there are no tabs.  It still doesn't work - but I'll give up for now
Comment: Whew! Got it. Just as I was about to give up, here's a potential tip for anyone else who finds this:

Go to `General > Editors > File Associations` to figure out which editors are enabled for various file types.

I had an Aptana editor active, which had its own Tabs/Spaces setting.  I changed literally 5-6 different `Editor > Formatter` settings before I found the right one.
Comment: See the additions I made to my answer.
Comment: @E-Riz It looks like the **Formatter** settings do affects as-you-type formatting. Eclipse was auto indenting a new line when I hit _return_ using a four-space tab. Once I modified the settings in the **Formatter**, Eclipse started indenting by two spaces. This is on _Eclipse Neon_. This should be rechecked as I was messing with a number of settings.
Answer: I've been struggling with this with my editing.  I found out an interesting thing:
Eclipse editor is taking indentation character cues from the previous line!
If you go to the end of a line indented with the tab character and press enter to add code, it uses the tab to indent the new line.  If the existing line was indented with spaces, it uses spaces.  I have wasted man-hours of time every time I see times and check everywhere in IDE settings and preferences for a setting  that can change this behavior without luck.  I just happened to notice the behavior I described above.  So the trick is, make sure the line above is indented with spaces!
(Edit:)
Wow.  I just noticed @E-riz posted an answer here about 10 years ago that says the same thing I said here.  I'm going to go follow that link in his answer!


Responsive grid in view layout

Question: I think it's an easy question but I just can't solve it.
I use responsive grid type in view to show a content type named "clinic information",and it is.
I want a row only have two clinics and the five-stars are beside the information(picture,phone number...), not below, how can I make it?
(picture, name, address, phone number, five-stars are clinic information in one content in a grid)
Comment: First of all what module are you using to render the responsive grid layout? This also depends on the type of theme you are using, are you using any one of the responsive themes, e.g. bootstrap? The solution can very simple like overriding the output markup of the view with something to your liking. That is what I usually do. Provide the additional info and I will post a full answer for you.
Comment: Sorry for that I just use drupal for a week so many things I probably can't understand.

The theme I used is CorporateClean, and modules that I'm using are Views Responsive Grid(using CSS), Fivestar and Views only.
Answer: The important thing to make this work is the theme that your using; the Views Responsive Grid doesn't do much by itself with regards to styling but it allows you setup you view to apply the appropriate CSS class from your theme to make your display responsive.
You are using the Corporate Clean theme but it's not a truly responsive theme from what I can see from its layout CSS. You can still have that layout that you want for one screen type so that will be what I will show you here.

Change your view's format to Responsive Grid

Next change the settings for the Responsive Grid format to have  2 column in horizontal alignment and the class grid_6 to every column. You can also use grid_4 if you have a sidebar on your page.

Then change the Format's Show options to fields.

Now in the fields section add all the fields that you want to display. For example, I have the fields title, body and post date.

The next step requires you to add some custom html/css; normally advanced view display formats such as Views Bootstrap would have different options to display your fields. For example, had you been using a Bootstrap based theme the Media Object format would have served you well.
However, since you are using something different, I would recommend you override the out of the fields as follows.

Hide all but the last one of your fields by clicking on each field and checking the "Exclude from display option".

For the last field override its display by clicking on it and going to the Rewrite Results section. In the text box provided add in your custom HTML markup with along your fields using tokens provided by views.

In you theme make sure to add proper CSS classes, i.e, in the example HMTL I'm showing you should have the classes clinic, clinic-thumb and clinic-details. These should have the styling in such a ways that the clinic class clear floats, the clinic-thumb and clinic-details classes should have floats and respective widths.
Example CSS:
/**

.clinic has a clearfix taken from this page
*/

.clinic:before,
.clinic:after {
    content: " "; /* 1 /
    display: table; / 2 */
}
.clinic:after {
    clear: both;
}
/**

For IE 6/7 only
*/
.clinic {
*zoom: 1;
}

.clinic-thumb{
 width: 35%;
 padding-right: 5%;
 float: left;
}
.clinic-details{
 float: left;
 width: 60%;
}

If you followed my example you should get something like this:

Hope this helps!
Comment: Thanks, it almost works for me, but there's last one problem that it only has one column.
[screenshot](http://imgur.com/a/TdHv9)
Comment: I'm guessing this has to do with the class you used, did you use the `grid_6`? Please try with the `grid_4` classes.
Comment: When I try [grid4](https://imgur.com/a/Hh23q), it become [so](https://imgur.com/a/nne9j).
Comment: Oh I see, maybe you can try to revert back to `grid_6` and make sure that you don't have any padding and/or margin to the div with the `grid_6` class. If there is padding or margin added to the div it will go down to the next line; maybe that would have been the problem. Do you have the site live somewhere? I can look at it give you a suggestion.
Comment: Actually, I change classes into [this](http://imgur.com/a/uLgRt) and it becomes [normal](https://imgur.com/a/NJ7r0), I don't know how it works but it does.
Comment: Well if it works for you then that's good!
Answer: You need to create CSS rules for the output. To make it responsive and fluid, use percentage value instead of pixel value.
Grid 3:
.views-column {
  float: left;
  width: 31%;
}
Grid 4:
.views-column {
  float: left;
  width: 24%;
}
To switch the 4-column and 3-column to 2-column on view port width when it is less than 600px:
@media screen and (max-width: 600px) {
    /* change Grid 4 to 2-column */
    .views-column {
        width: 48.4%;
    }
    .views-column:nth-of-type(3n+1) {
        margin-left: 2%;
        clear: none;
    }
    .views-column:nth-of-type(2n+1) {
        margin-left: 0;
        clear: left;
    }
    /* change Grid 3 to 2-column */
    .views-column {
        width: 48.4%;
    }
    .views-column:nth-of-type(3n+1) {
        margin-left: 3.2%;
        clear: none;
    }
    .views-column:nth-of-type(2n+1) {
        margin-left: 0;
        clear: left;
    }
}

Responsive grid in view layout


Nginx - Routing to a different app server endpoint than matching locaion

Question: If I have the following inbound url: /blog/mailchimp.xml but I want to serve the endpoint from the app server of /blog/atom.xml and I don't want to do a rewrite, what is the best way to write this rule for nginx?
Comment: Please share your nginx configuration. Your question has too little details on the actual problem and therefore it cannot be answered.
Answer: If you don't want to use a rewrite then you should be able to return a 301 or 302 to where you want to go. I can't test this right now but I don't see why it wouldn't work
location /blog/mailchimp.xml {
    return 302 $scheme://YOUR-SITE/blog/atom.xml;
}


Why does promise resolve with promise?

Question: I have a promise in my code that consistently fails. When I return a promise to a Promise#then callback, rather than wait for the promise to resolve, it passes it as a parameter to the subsequent Promise#then call.
See code in this gist for more detailed code. Calling House#setEnergyData would cause the problem (see comments in gist).
The basic pattern that is causing problems in my code looks like this (although this literal code does work):
class Class1 {
    step1(){
       return new Promise((fnResolve, fnReject)=>{
       // do something
       fnResolve();
     });
    }

    step2(){
       return this.step1().then(()=>{
         // do something else
       });
    }
 }

 class Class2 {

   constructor(){
     this.class1 = new Class1();
   }

   doSomething(){
      this.class1.step2()
        .then((res)=>{
          console.log(res) // Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
          // do something that shouldn't happen until Class1#step2 has finished.
          // error!
        });
   }
 }

This is running in a browser and is compiled with Babel ES2015 preset and uses Babel polyfill. I'm not using any Promise npm module.
This has recurred in several places in my code. I'm not sure if it's an issue with the compilation process, babel polyfill, or I'm misunderstanding promises.
Comment: Your code makes no sense - promises never resolve with promises - they always unwrap the value
Comment: @Paulpro I saw that - it was a typo, now fixed.
Comment: show your actual code
Comment: In your sample, you never resolve or reject your promise.
Comment: @naomik The codebase isn't open source, but you can checkout [this gist](https://gist.github.com/Arbolista/52d5a1964414730a4f27) - the problem is when `House#setEnergyData` is called.
Comment: @rgvassar updated, see edit. Also see gist added to question.
Comment: @BenjaminGruenbaum that's exactly my response every I get this result - but it certainly happens. See gist if you want to look in more detail.
Comment: So, the only code included in your question is code that does work?  Please include code in your question that does not work - not only something in an external link - those are the stack overflow rules.
Answer: Try including return statement within .then() at step2 to return value from Promise at step2() call

class Class1 {
  step1() {
    return new Promise((fnResolve, fnReject) => {
      // do something
      fnResolve(123);
    });
  }
  step2() {
    return this.step1().then((data) => {
      // do something else
      // added `return` here
      return data
    });
  }
}

class Class2 {
  constructor() {
    this.class1 = new Class1();
  }
  doSomething() {
    this.class1.step2()
      .then((res) => {
        console.log(res) // 123
      });
  }
}

var c = new Class2();
c.doSomething();
Comment: `.then()` creates a new `Promise`, though the log message is not indicating that the value of the resolved `Promise` is a `Promise`. The `[[PomiseValue]]` private property is `undefined` at `js` at Question; the resolved value is not a `Promise` . No value was passed to `fnResolve` at `js` at Question. If `123` is passed to `fnResolve` , `123` should be logged at `.then()`
Comment: I see that works, but if you look at the gist I provided, that doesn't seem to be a critical difference (I am returning an object in the gist). Also, in `Class1#step2`, try setting an instance variable `this.step2_has_run = true;` and don't return anything. Then in `Class2#doSomething`, `console.log(this.class1.step2_has_run); // true`.
Comment: @EricH. _"I see that works, but if you look at the gist I provided, that doesn't seem to be a critical difference (I am returning an object in the gist). "_ The `javascript` at gist is different from `javascript` at Question ? _"Also, in Class1#step2, try setting an instance variable this.step2_has_run = true; and don't return anything. Then in Class2#doSomething, console.log(this.class1.step2_has_run); // true"_ ? Not certain what expected result is ?
Comment: Yes, the gist is a lot more complicated. In the question I'm just representing the problem in an abstract way... which may not be helpful given that it actually works - and my example in the comment above I was trying to indicate *even without* returning any data, the code still works as expected... I'll make that more clear in the question.
Comment: @EricH. What is expected result ?
Comment: The question is why would a promise ever resolve with another promise as shown in the log statement in the question above.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/106066/discussion-between-eric-h-and-guest271314).

Why does promise resolve with promise?


Invalid XML in a varbinary(max) column in SQL Server 2005

Question: So I got a varbinary(max) column in SQL Server 2005 and it's full of XML. A few records somewhere have truncated XML so they're invalid.
This means if I run a
SELECT CAST(myVarbinaryColumn as XML) ...

it blows chunks.
How can I filter out/skip invalid xml ?
When I've done similar with a varchar that supposedly has dates I could use ISDATE(blah) = 1. So an equivalent ISVALIDXML() would be nice.
Please don't comment about "Why isn't the column XML datatype anyway.." This happened in the past and I don't have a time machine.
Comment: Hmm interesting, the final bytes will always be the same so I could filter out those that don't match ? Luckily in this scenario the xml all use the same schema so they should all have a matching closing root element
Answer: I wish I had that IsValidXML() function, too..... unfortunately, I don't think there's anything like that.....
Just a thought: is there anything you could check for to filter out the invalid XML??
E.g. could you filter out all those strings that don't end in .....</data> or something like that?? (seeing that you say your invalid XML is typically truncated XML, so I would think the closing tag - </data> or whatever - would be missing in those cases).
Answer: I think your best bet would be to write a custom CLR function, perhaps using XmlDocument.Load. In the CLR you could trap the error on a failed load and return an appropriate result.
EDIT: The code below would also work although it's not as elegant as a UDF. Unfortunately, we can't use TRY/CATCH in a UDF.
create procedure dbo.usp_IsValidXML(@XMLCandidate varbinary(max), @Return bit output)
as
begin
    declare @x xml
    begin try
        set @x = cast(@XMLCandidate as xml)
        set @Return = 1
    end try
    begin catch
        set @Return = 0
    end catch
end
go

declare @test1 varbinary(max)
declare @test2 varbinary(max)
set @test1 = cast('<data>asdf</data>' as varbinary(max))
set @test2 = cast('<data>asdf</da' as varbinary(max))

declare @IsValid bit
exec dbo.usp_IsValidXML @test1, @IsValid output
select @IsValid
exec dbo.usp_IsValidXML @test2, @IsValid output
select @IsValid

drop procedure dbo.usp_IsValidXML

Comment: Yes, and create a persistent calculated column based on it, so it's not called every time you go `where valid_xml = 1`.


Extreme value outside domain

Question: Hi I'm practicing finding extremas/monotonicity.
What if the derivative changes sign (function changes the monotonicity) at some point $x$ that is outside the domain?
Like, for example, $f(x) = x^3e^{\frac{-1}{x}}$ the domain of derivative is $D_{f'} = (\infty;0),(0,\infty)$ and one of derivative's solutions is $x = 0$ which does not belong to neither domain of function $D_{f}$ nor domain of derivative $D_{f'}$. The function changes monotonicity, but does it have extreme value in there?
And similiar situation: What if the $x$ does belog to domain of $f$ but does not belong to domain of $f'$?
Answer:
What if the derivative changes sign (function changes the monotonicity) at some point $x$ that is outside the domain?

It doesn't: if a function doesn't exist at a certain point, it doesn't have a derivative there either.

Like, for example, $f(x) = x^3e^{\frac{-1}{x}}$ the domain of derivative is $D_{f'} = (\infty;0),(0,\infty)$ and one of derivative's solutions is $x = 0$ which does not belong to neither domain of function $D_{f}$ nor domain of derivative $D_{f'}$.

How can $x=0$ be a zero of the derivative, if the derivative doesn't even exist in $x=0$...?

And similiar situation: What if the $x$ does belog to domain of $f$ but does not belong to domain of $f'$?

That's possible since a function isn't necessarily differentiable at every point of its domain. That doesn't mean it can't have an extreme value at such a point, think of $|x|$ at $x=0$ for example: no derivative, but the function has a minimum there.

Extreme value outside domain


Dealing dataset with NAs (MNAR)

Question: I have a dataframe with many (>50%) NAs values and I am looking for a way to deal with it. From what I've found, I think many people recommend using imputation like multiple imputation or using random forest (rf deals with missing values by replacing the NAs with median). However, let me explain my situation with a sub-dataset:
         basket.Africa.1 basket.US.10 basket.France.20

apple           1              0                1

orange         NA              3                2

pear           NA              NA               2

peach           1              NA               NA

banana          1              2                3

Each basket is scan by a machine (pour the fruits from the basket and the machine will scan each fruit), and then the amount of fruits will be recorded. So, there are 1 apple, 1 peach, and 1 banana in basket.Africa.1. Note that basket.Africa.1 refers to basket #1 from Africa.
The NAs here is NOT missing by random, it means it is not possible to have NAs. For example, basket.Africa.1 has NAs in orange and pear, because Africa does not produce any orange and pear, so it is for sure that orange and pear counts are NAs.
In other words, the zero in basket.US.10 (this basket is from the US) does NOT mean missing value, but instead, it is possible to have apple in this basket but there're none in this particular basket (basket # 10 from the US).
My goal is to use the dataset (~100 columns of different baskets from 5 countries (Africa, US, France, China, Australia) and ~10 rows of different fruits), and answer: if I am given a random basket, how can I determine which country is this basket belongs to?
I don't think it is appropriate to fill any values for the NAs because the NAs should have no value! I also try the multiple imputation but my data contains WAY TOO MANY missing values, so this method doesn't work neither...
Answer: While I can understand why some people would say these data are MNAR (Missing Not At Random), I would rather say that they are missing by design. Another term that is somtimes used is structural missingness.
The way to handle this will depend very much on the model that you fit. One approach is to do nothing and retain the NAs. Some models will impute a value such as the mean or median - and you would not want that, but it might be OK if they ignore/delete NAs. Another approach that may work for you is to use a unique coding for the these data, such as -1 which would otherwise be impossible (since you seem to be observing counts). Obviously that would mean a model that uses a log transformation such as poisson or negative binomial regression would be out of the question, but there should be many others, perhaps tree based, that may work. This is not ideal so I would explore performance using different methods and models.
Answer:
I don't think it is appropriate to fill any values for the NAs because
the NAs should have no value!

What is the reasoning behind this statement? Consider the following example that you've provided:

For example, basket.Africa.1 has NAs in orange and pear, because
Africa does not produce any orange and pear, so it is for sure that
orange and pear counts are NAs.

Well, if you were to just look at the basket: what are the observed frequencies of pears and oranges in this basked? They are zero - fill the NAs with that.
Your effort to code 'outcome is impossible' with NA might not be necessary, since an event being impossible to occur under given circumstances will almost certainly show in the observed frequencies.

Dealing dataset with NAs (MNAR)


C# add item to JSON object

Question: I have this object and I want to add an other day to it.
[{
    "stone":"5kg",
    "years":
    [{
        "year":"2017",
        "stone":"5kg",
        "months":
        [{
            "month":"august",
            "stone":"0.5kg",
            "days":
            [{
                "day":"14",
                "stone":"0.1kg"
            }]
        }],
        "weeks":
        [{
            "week":"01",
            "stone":"0.5kg"
        }]
    }]
}]

I have this stored in a file and I deserialize it like so:
string file = System.IO.File.ReadAllText(@"C:\Users\luuk\desktop\test1.json");
var _data = JsonConvert.DeserializeObject<List<Data>>(file);

Now I want to add a day to it but I just can't figure it out.
I tried something like this:
_data.Add(new Data()
{

});

string json = JsonConvert.SerializeObject(_data);
System.IO.File.WriteAllText(@"C:\Users\luuk\desktop\test1.json", json);

but I can only access years[] and stone in there.
These are my classes:
public class Data
{
    public string stone { get; set; }
    public List<Years> years { get; set; }
}

public class Years
{
    public string year { get; set; }
    public string stone { get; set; }
    public List<Months> months { get; set; }
    public List<Weeks> weeks { get; set; }
}

public class Months
{
    public string month { get; set; }
    public string stone { get; set; }
    public List<Days> days { get; set; }
}

public class Days
{
    public string day { get; set; }
    public string stone { get; set; }
}

public class Weeks
{
    public string week { get; set; }
    public string stone { get; set; }
}

So how can I add an other day to the object?
(I have translated all the variabels in my code from dutch to english so there my be some that I forgot or some typo's)
Comment: You need to add a day to every month in every year or to some specific month in specific year?
Comment: to a specific month in specific year. (2017 - august)
Answer: You need to get the year and month first where you want to add another day. Here is how you can do that:
// Update the data in one line
_data[0].years.First(x=> x.year == "2017") // Get the year "2017"
        .months.First(x=> x.month == "august") // Get the month "august"
        .days.Add(new Days { day = "15", stone = "0.5kg" }); // Add a new day

OR

// Get the year
Years year = _data.years.First(x=> x.year == "2017");

// Get the month
Months month = year.months.First(x=> x.month == "august");

// Add the day in the month
month.days.Add(new Days { day = "15", stone = "0.5kg" });

Comment: Okay, thank you. this worked. I only had to use `_data[0]` instead of `_data` and I have changed all my arrays to lists.
Comment: I get a compiler error with your first code block: `'List' does not contain a definition for 'years'`
Comment: LuukWuijster glad it worked! I have also updated the code after @mason pointed out that error.
Answer: You're using arrays. You can't add things to already initialized arrays, they're fixed-size.
Change all arrays of T[] to List<T> and then you can call .Add() on them to add items.

C# add item to JSON object


Gerar CSV com resultados lado a lado no PHP

Question: Estou tentando obter resultados comparativos em um CSV gerado no php mas não consigo empilhar lado a lado da maneira que ilustra o RESULTADO ESPERADO da imagem anexa.
Fiz um código abaixo que não quebrou a linha quando muda para 2018
TABELA
CREATE TABLE `clientes_vendas` (
  `codigo` int(11) NOT NULL,
  `cliente_cnpj` varchar(40) NOT NULL,
  `codigo_cliente` int(11) NOT NULL,
  `codigo_repre` int(11) NOT NULL,
  `valor` decimal(10,2) NOT NULL DEFAULT '0.00',
  `dia` varchar(20) NOT NULL,
  `mes` varchar(40) NOT NULL,
  `ano` varchar(40) NOT NULL,
  `data` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CÓDIGO
while:

  if ($ano_atual2==0) {
      $ano_atual2 = $ano;
  }
  $pula_linha="\n";

  if ( $ano != $ano_atual2 )  :
      $ano_atual2 = $ano;
      $dadosTXT2 = "$pula_linha$nome_repre;$mes;$ano$pula_linha";
      $arraDados[] = $dadosTXT2;
      $soma=0;
  endif;

   @$soma +=  $row['valor'];
   $somaConvert = number_format($soma,2,",",".");
   $dadosTXT2 = "$cnpj_cliente;$nome_cliente;$nome_repre;$mes;$ano;$valor$pula_linha";
   $arraDados[] = $dadosTXT2;

endwhile;

$fp = fopen($csv, 'a');
$escreve1 = fwrite($fp,   utf8_decode($header));

foreach ($arraDados as $file) {
    $escreve2 = fwrite($fp,  $file);
}

fclose($fp);

RESULTADO ESPERADO: Exibir as SOMAS da vendas de clientes lado a lado EXEMPLO: AGOSTO 2017 , AGOSTO 2018, SETEMBRO 2017- SETEMBRO 2018 mas começando normalmente de janeiro
Comment: todos os cliente possuem cnpjs únicos ou podem se repetir? ou existe outro índice de id único na sua tabela?
Comment: O que eu não entendi é que na imagem do resultado esperado mostra, NA MESMA LINHA => `1, 2017, valor` - `1, 2018, valor` - `2, 2017, valor`. É isso que você quer? Porque?
Comment: Qual a relação? Não entendi. `O primeiro é o mês de janeiro de 2017, depois é janeiro 2018 e depois é fevereiro de 2017. A logo abaixo começa com janeiro de 2017, depois janeiro de 2018(outro valor), e fevereiro de 2018.`
Comment: @denis,você já pensou em fazer um tratamento similar ao que você está fazendo ao ano?o código é único por cliente,código vai começar em zero,na 1ª interação faz o preenchimento da 1ª linha com as informações por ex: $linha=$cnpj_cliente;...;$mes;$ano;$valor;
na interação seguinte se o código for igual você continua concatenando só os dados de mês,ano,valor, $linha.=$mes;$ano;$valor; e assim vai, até vir um código diferente,com isso $linha .=$pular_linha e armazena no array de saída.inicia novamente o $linha, atualizando o codigo ,colocando o "cabeçalho" como na primeira interação e etc..
Comment: @AndreiCoelho Coelho eu editei a imagem aquela não estava clara ! o cabeçalho não precisa apenas os resultados
Comment: Agora eu entendi!
Comment: apenas o codigo é único AnthraxisBR
Comment: Vou analisar @MarcusItalo Italo obrigado.
Answer: $codigo_cliente = 0;
$pula_linha="\n";
while:

  if ($ano_atual2==0) {
      $ano_atual2 = $ano;
  }
  if ( $ano != $ano_atual2 )  :
      $ano_atual2 = $ano;
      $dadosTXT2 = "$pula_linha$nome_repre;$mes;$ano$pula_linha";
      $arraDados[] = $dadosTXT2;
      $soma=0;
  endif;

  if ($codigo_cliente == 0) {
      $codigo_cliente  = $row['codigo'];
      $linha = "$cnpj_cliente;$nome_cliente;$nome_repre;";
  }

  @$soma +=  $row['valor'];
   $somaConvert = number_format($soma,2,",",".");

  if ( $row['codigo']!= $codigo_cliente)  {
       $codigo_cliente  = $row['codigo'];
       $linha .= $pula_linha;
       $arraDados[] = $linha;
       $linha = "$cnpj_cliente;$nome_cliente;$nome_repre;$mes;$ano;$valor";
  }
  else{
    $linha .= "$mes;$ano;$valor;";
  }

endwhile;

$fp = fopen($csv, 'a');
$escreve1 = fwrite($fp,   utf8_decode($header));

foreach ($arraDados as $file) {
    $escreve2 = fwrite($fp,  $file);
}

fclose($fp);

Espero ter ajudado ou pelo menos chegado perto.
Comment: Uma dica: por que ao invés de fazer essa trabalheira toda na mão, vocês não usam a função [`fputcsv`](http://php.net/manual/pt_BR/function.fputcsv.php)?
Comment: +1 por ter tirado o `$pula_linha` do loop
Answer: Para responder a sua pergunta eu tive que criar outras tabelas que não foram informadas para obter o nome_representante e o nome_cliente. E para fazer testes eu criei alguns registros diversos, veja:

Coloquei como opcional o valor de entrada do inicio do ano e do fim do ano a ser analisado, pois pode ser que você queira realizar um filtro. Veja a linha abaixo:
$anoInicio = "2017";
$anoFim = "2018";

Por fim, criei o código com base no seu. Repare que o select está ordenando, primeiro pelo mês, depois pelo código do cliente e depois pelo ano. Deste modo você conseguirá o resultado esperado.
    $anoInicio = "2017";
    $anoFim = "2018";

    $query = mysqli_query($conn, "SELECT ano, mes,
        (
            SELECT nome_cliente FROM cliente
            WHERE cliente.codigo_cliente = clientes_vendas.codigo_cliente
        ) AS 'nome_cliente',
        (
            SELECT nome_representante FROM representante
            WHERE representante.codigo_representante = clientes_vendas.codigo_representante
            GROUP BY representante.codigo_representante
        ) AS 'nome_representante',
        SUM(valor) AS 'total' FROM clientes_vendas
        WHERE ano >= '$anoInicio' AND ano <= '$anoFim'
        GROUP BY mes, codigo_cliente, ano ORDER BY codigo_cliente, mes, ano ASC"
        );

    $arraDados = array();
    $strTmpCliente = "";
    $mes = array('', 'Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'); // formatador dos meses
    $x = 1;

    while($dados = mysqli_fetch_assoc($query)){

        if($strTmpCliente != $dados['nome_cliente']){
            $strTmpCliente = $dados['nome_cliente'];
            $arraDados[$strTmpCliente] = array();
            $arraDados[$strTmpCliente]['nome'] = $dados['nome_cliente'];
            $arraDados[$strTmpCliente]['representante'] = $dados['nome_representante'];
        }

        $strMesAno = $mes[$dados['mes']]."_".$dados['ano'];
        $arraDados[$strTmpCliente][$strMesAno] = number_format($dados['total'],2,",",".");

    }

    $header = "Cliente;Representante;";
    $mesAtual = 1;
    $anoAtual = (int)$anoInicio;

    $arrayDatas = array();

    for($x = 0; $x < 24; $x++){

        $data = $mes[$mesAtual]."_".$anoAtual;
        $arrayDatas[] = $data;
        $header .= str_replace("_", "'",$data).";";

        $alteraMes = $x % 2 == 0 ? false : true;
        if($alteraMes){
            $mesAtual++;
            $anoAtual = $anoInicio;
            continue;
        }
        $anoAtual = $anoFim;
    }
    $header = substr($header, 0, -1);
    $header .= "\n";

    $strDados = array();

    foreach($arraDados as $cliente ){

        $strTmp = $cliente['nome'].";".$cliente['representante'].";";
        for($i = 0; $i < count($arrayDatas); $i++){
            $data = $arrayDatas[$i];
            if(isset($cliente[$data])){
                $strTmp .= $cliente[$data].";";
                continue;
            }
            $strTmp .= "-;";
        }

        $strTmp = substr($strTmp, 0, -1);
        $strTmp .= "\n";
        $strDados[] = $strTmp;

    }

    $csv = "arquivo.csv";

    // escreve o cabeçalho
    $fp1 = fopen($csv, 'w');
    fwrite($fp1, $header);
    fclose($fp1);

    // escreve o resultado
    $fp2 = fopen($csv, 'a');
    foreach ($strDados as $file) {
        fwrite($fp2,  $file);
    }
    fclose($fp2);

O arquivo gerado ficou assim:

EDIT
Eu reparei que na imagem que você postou que alguns meses ficaram sem vendas. Fui fazer o teste no meu código e, como eu imaginava, deu erro. Pois os valores eram preenchidos sequencialmente.
Eu alterei o código e agora está funcionando corretamente. Aproveitei para inserir o number_format que você está usando. O resultado foi esse:

EDIT 2
Altere essa parte que irá funcionar:
           if($strTmpCliente != $dados['nome_cliente']){
                $strTmpCliente = $dados['nome_cliente'];
                $arraDados[$strTmpCliente] = array();
                $arraDados[$strTmpCliente]['nome'] = $dados['nome_cliente'];
                $arraDados[$strTmpCliente]['representante'] = $dados['nome_representante'];
            }

            //---> o erro estava aqui
            $dadosMes = (int)$dados['mes']; // aqui ele transforma em inteiro
            $strMesAno = $mes[$dadosMes]."_".$dados['ano']; // aqui ele grava a strinmg corretamente
            $arraDados[$strTmpCliente][$strMesAno] = number_format($dados['total'],2,",",".");

Comment: @denis pode ser... Vou fazer outros testes.
Comment: @denis o erro era exatamente esse. Acabei de alterar. Está no EDIT 2
Comment: Consegui era a formatação para inteiro mesmo ! Resposta perfeita Muito obrigado !
Comment: @denis Tranquilo! Abraço!
Comment: aparentemente seu código funcionou mas só começa preencher os valores depois de Out'2017 sendo que existe vendas nos meses anteriores, estou analisando para ver encontro o porque depois te retorno!
Comment: acho que porque na minha tabela os meses são gravados em VARCHAR e com 0 tipo 01,02,03 e sua variável está $mesAtual =1 estou a verificar .....
Comment: veja como está ! @AndreiCoelho https://codeshare.io/aJAJMK
Comment: mudei para $mesAtual = '01'; e começou pegando de JAN'2017 e JAN'2018 depois já pula para Out'2017 novamente ... link atualizado com as outras duas tabelas que só são para pegar os nomes https://codeshare.io/aJAJMK
Comment: @denis conseguiu?


How to create a rule to email all users with a profile field X with same value as the current-user?

Question: I'm using Drupal 7.57 and I have 2 roles in my website, role X and role Y.
I want to compare a field (field_code_postal) of the X member profile of the current-user, with the fields (field_code_postal) of all Y members profiles, and this when X member save a new entityform submission.
Each time the field field_code_postal is the same, an email should be sent to that Y member.
So if there are 100 Y members and for 20 of them the value of the field is equal to the value of it for the current user X, then 20 emails are sent.
Do I need to use flags, or are the roles sufficient?
I'm a bit lost, any help?
Comment: It is possible with simple hook in a custom module, but please specify what Drupal version you are using and the machine name of the field.
Comment: Thanks for the answer, i'm using drupal 7.57 with rules, the machine name of the field is : field_code_postal, i added it in the main post ^^
Comment: @Pierre.Vriens : After saving a new entityform submission
Comment: I used node as an example in below answer, however it can be replaced by another entity type. What is your entity type?
Comment: It's good you are going to try the proposed methods, however please do not leave your question with no answer accepted if you want others to keep helping you. Choose one and accept it or share with your own solution.
Comment: Alright sry for the mistake ! I will not leave my question without answer @AltaGrade it's a promess :p i'm just not free to manage my time in my job for now so this project is suspended for some days... :/
Answer: D7, use rules views module, make a users rules view and load it in rules as a views rules loop, in view settings add a filter criteria Y members = your special field, inside loop, add an action: fetch entity by id: UID from loop, action: send email to fetched UID.
EDIT:
because of Pierre comment i'm adding a little more info. Let me first explain something: ID's (uid, nid, tid, etc.) must be passed from rules views to rules as an integer, if you don't, rules will not understand what you are sending in, this is done in rules view settings in "row variable settings" in middle column. So rules inside loop recieves UID as an integer, this means you do not have that user object avilable in rules, that's why you must fetch user by the integer value (UID) passed to rules. Now, you have two objects to work with, inside rule views loop, you have to compare current logged-in user postalcode field value againts the postalcode field of the fetched user, and last, send your email or whatever.
you may need also rules conditional module
Comment: That seems indeed another approach, though I wonder why you'd need "fetch entity by id". Since for any data you'd need to send the eMail, you can just include them as an extra field in your view, so that those data are available as rules tokens within the Views-loop in your rule. No? The only thing I'm unsure about: how to pass the value of the "special field" for the current user (from the rule to the view, within the Rules action to create that Views loop). Can you refine your answer about that?
Answer: Import and give a try to the following rule. Note I used After saving new content trigger, however you can change to or add another event suitable to your case. For example, you could add After saving a new comment.
{ "rules_notify_users_with_the_same_postal_code" : {
    "LABEL" : "Notify users with the same postal code",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [] },
    "IF" : [
      { "NOT data_is_empty" : { "data" : [ "node:author:field-code-postal" ] } }
    ],
    "DO" : [
      { "entity_query" : {
          "USING" : {
            "type" : "user",
            "property" : "field_code_postal",
            "value" : [ "site:current-user:field-code-postal" ],
            "limit" : "100"
          },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "entity-fetched" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "mail" : {
                "to" : "list-item:mail",
                "subject" : "A new post #[node:nid] [node:title] has been posted",
                "message" : "A new post #[node:nid] [node:title] has been posted",
                "from" : "[site:mail]",
                "language" : [ "node:language" ]
              }
            }
          ]
        }
      }
    ]
  }
}

Comment: Glad it worked for you.
Comment: Reference or just a regular field doesn't matter that much as long as you implement similar rule with the same principles. Anyway, I've updated my answer providing exported rule that should work.
Comment: It looks to me that the "field_code_postal" field is related to user entities, not to nodes. So what's the purpose of those node-tokens in your exported rule?
Comment: The [ "node:author:field-code-postal" ] is not a node token. PO mentioned entity submission without specifying what kind of entity it was, so I used node entity as an example. It can be easily replaced by any entity, but what is most important is that we need to derive entity author's field_code_postal anyway.
Comment: Hi @AltaGrade, i'm comming back to say thank you, it's work pretty well, i changed some fields and added a conditionnal to check the role of the user. i was using entityform ^^
Answer: You may want to give it a try to process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions:

Load the VBO list that you want to be processed.
Add a loop to perform a Rules Action, for each row contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".
To actually trigger such Rules Action, you should be able to use pretty much any Rules Event that fits your needs.
Also, to select only those members (= Y) with the same value of that field_code_postal field, it seems you can use either of these techniques:

Pass it as an argument to the view (so that you only get 1 views result for each member). Refer to the video in the linked tutorial about how to do so.
Yse an extra Rules Component in which you actually send those eMails, and in which you perform an extra Rules Condition to check that the value for the field_code_postal field of member Y is equal to the one for member X (you probably want to pass this value as an extra Rules Component parameter).


Como enviar uma lista de objetos por bundle?

Question: Estou trabalhando com um sistema de abas, uma para cada mês, e uma listagem de aniversário nas respectivas abas.
Meu adapter está da seguinte maneira:
FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter(
                getSupportFragmentManager(), FragmentPagerItems.with(this)
                .add(R.string.mes1, MesFragment.class, bundles.get(1))
                .add(R.string.mes2, MesFragment.class, bundles.get(2))
                .add(R.string.mes3, MesFragment.class, bundles.get(3))
                .add(R.string.mes4, MesFragment.class, bundles.get(4))
                .add(R.string.mes5, MesFragment.class, bundles.get(5))
                .add(R.string.mes6, MesFragment.class, bundles.get(6))
                .add(R.string.mes7, MesFragment.class, bundles.get(7))
                .add(R.string.mes8, MesFragment.class, bundles.get(8))
                .add(R.string.mes9, MesFragment.class, bundles.get(9))
                .add(R.string.mes10, MesFragment.class, bundles.get(10))
                .add(R.string.mes11, MesFragment.class, bundles.get(11))
                .add(R.string.mes12, MesFragment.class, bundles.get(12))
                .create());

O fragmento do mês receberá pelo bundle a lista completa dos aniversários e o mês em si para poder realizar os filtros antes da exibição.
Configurei uma lista de bundles da seguinte maneira:
ArrayList<Aniversario> listaAniversariantes = new ArrayList<>()
/* a lista foi declarada assim e por hora já está alimentada estaticamente*/

List<Bundle> bundles = new ArrayList<>(12);
        for (int i = 1; i <= 12; i++) {
            Bundle b = new Bundle();
            b.putInt("mes", i);
            b.putSerializable("listaAniversario", listaAniversariantes);
            bundles.add(b);
        }

No fragmento do mês estou recuperando as informações do bundle da seguinte maneira:
int mes = getArguments().getInt("mes");
ArrayList<Aniversario> listaAniversariantes = (ArrayList<Aniversario>) getArguments().getSerializable("listaAniversario");

O mês está sendo recuperado corretamente, porém a lista não. Em testes com as informações separadas, quando passo pelo bundle só o mês e eu crio a lista dentro do fragmento, tudo funciona normal, quando eu incluo a lista no bundle, a aplicação quebra.
Alguém sabe o que pode estar acontecendo?
PS: cogitei usar Intent, mas a função .add("nome da aba", fragmento) permite a inclusão apenas de um bundle.
Answer: No episódio de hoje aprendemos que devemos sempre revisar o nosso código!
No adapter passei .add(R.string.mes1, MesFragment.class, bundles.get(1)) do 1 ao 12 tendo na cabeça os meses, porém o campo é do índice da lista, que vai de 0 a 11, a aplicação estava quebrando pois estava tentando acessar a posição 12 inexistente da lista de bundle.
Tópico encerrado e muito obrigado!


Calcular média de distância percorrida com único tapply

Question: Tenho meu banco de dados proveniente do pacote hflights do R, que mostra uma quantidade de voos nos EUA. Preciso calcular a média da distância percorrida (Distance) para cada dia da semana (variável DayofWeek) entre os voos com atraso maior que 60 e entre os com atraso menor que 60 (variavel DepDelay). É necessário usar um único tapply.
Tentei algo parecido com isso, mas está errado:
y=(c(which(sapply(dados,is.numeric))))y
apply(as.matrix(y),1,function(x){tapply(dados[,x],list(dados$DayofWeek,dados$DepDelay>60),mean)})

Comment: Felipe se alguma resposta atendeu a sua pergunta, você pode aceitá-la clicando no botão verde de ok do lado esquerdo da resposta.
Answer: Ao meu ver a forma mais elegante de fazer isso é usando os pacotes dplyre tidyr. O código usando essas funções fica muito mais simples de ler. Vale a pena aprender!
library(dplyr)
library(tidyr)

hflights %>%
  filter(!is.na(DepDelay)) %>% # filtra os voos sem atraso
  mutate(DepDelay2 = ifelse(DepDelay>60, ">60", "<=60")) %>% # atraso maior que 60
  group_by(DayOfWeek, DepDelay2) %>% # indica o calculo em grupo
  summarise(media = mean(Distance)) %>% # usa a media para agregar
  spread(DepDelay2, media) # coloca em colunas separadas

# Source: local data frame [7 x 3]
#
#   DayOfWeek      <60      >60
# 1         1 783.1453 796.0078
# 2         2 778.1595 796.8847
# 3         3 779.2828 816.0626
# 4         4 782.5144 816.7166
# 5         5 785.8960 790.0505
# 6         6 823.0040 821.7922
# 7         7 797.2524 803.0468

Answer: Não sei como fazer isso para os dois grupos (DepDelay > 60 e DepDelay < 60) utilizando um único tapply, mas eu faria assim para cada um dos grupos:
tapply(X = hflights[which(hflights$DepDelay > 60),"Distance"], INDEX = hflights[which(hflights$DepDelay > 60),"DayOfWeek"], FUN = mean)
tapply(X = hflights[which(hflights$DepDelay < 60),"Distance"], INDEX = hflights[which(hflights$DepDelay < 60),"DayOfWeek"], FUN = mean)

Só note que há também 232 casos com DepDelay == 60, caso você queira considerar todos os vôos (não-cancelados) da base de dados.
EDITADO
 Aqui está uma forma (não muito elegante) de se fazer isso com um único tapply:
tapply(X = hflights$Distance, INDEX = list(hflights$DayOfWeek, ifelse(test = hflights$DepDelay > 60, yes = "> 60", no = "<= 60")), FUN = mean)

O único problema é que dessa forma você precisa incluir os 232 casos com DepDelay == 60 em algum dos dois grupos (no meu código eu coloquei no segundo grupo, DepDelay < 60)
Answer: Outras duas formas de fazer:
Usando tapply, como o Nishimura, mas com o cut. O legal do cut é que ele estende facilmente para mais do que duas condições, basta aumentar os breaks e os labels:
tapply(X = dados$Distance,
       INDEX = list(dados$DayOfWeek,
                    cut(dados$DepDelay,
                        breaks =c(-Inf, 60, Inf),
                        labels = c("menor60", "maior60"))),
       FUN = mean)

Usando o dplyr sem cut:
dados %>%
  group_by(DayOfWeek) %>%
  summarise(menor60 = mean(Distance[DepDelay <= 60], na.rm = TRUE),
            maior60 = mean(Distance[DepDelay > 60], na.rm = TRUE))

A solução do dplyr com cut seria equivalente à resposta do Daniel trocando o ifelse.


How to fix AppStore rejection "Your app requests admin access in order to function" for macOS

Question: I'm currently developing an App that contains a XPC Service embedded.
The App starts in background and communicates with the XPC Service in order to make the service move the mouse from time to time.
My app review by Apple returned this:
Guideline 2.4.5(v) - Performance
Your app requests admin access in order to function.
- App requires Accessibility in order to function.
Resources
An informational video concerning requesting access from users is available from our WWDC 2019 conference. See the Advances in macOS Security video.
AppDelegate.swift
func applicationDidFinishLaunching(_ aNotification: Notification) {
connection = NSXPCConnection(serviceName: "com.some.ServiceName")
        connection?.remoteObjectInterface = NSXPCInterface(with: MyHelperXPCProtocol.self)
        connection?.resume()
}

MyHelperXPC.swift (XPC Service Target)
import Foundation
import Cocoa

@objc class MyHelperXPC: NSObject, MyHelperXPCProtocol {
    func terminateHelper() {
    }

    /* This function triggers the dialog informing that the app would like
       to control this computer using accessibility features. */
    func activate(duration: TimeInterval) {
        CGEvent(mouseEventSource: nil, mouseType: CGEventType.mouseMoved, mouseCursorPosition: point, mouseButton: CGMouseButton.left)?.post(tap: CGEventTapLocation.cghidEventTap)
    }
}

When the function 'activate' is called this dialog is shown:

The user now have to unlock Security & Privacy preferences and check my App.
After this, my application can now move the mouse without a problem.

XPC Service Info.plist contains:
com.apple.security.app-sandbox = 1
App Info.plist contains:
Application is background only = YES
The question is, how can I understand better this App Store rejection and fix it?
My App and XPC Service are signed with a Developer ID Application.
I'm using Xcode 12.4, macOS Big Sur and swift 5, not using frameworks.
Comment: Does your application have any useful features when the user refuses to give it admin access?  If the answer is No, then you may not convince your reviewer.
Answer: After appealing to the Apple Review Board, turned out that moving the mouse using the Accessibility is considered inappropriate.
I understand that using the Accessibility this way exploits the feature originally designed to make your app more accessible for people.
They also wrote that will look into other apps that have the same functionality because they may be considered inappropriate as well.


Very strange problem with VMDK thin/thick disks

Question: I have some ESXi (4.1) virtual machines which were initially created using thin-provisioned disks, but where then physically moved to different datastores (all of them iSCSI); since these are stand-alone hosts, there is no vCenter Server available to manage them, so the operation was done from the ESXi command line using the mv command.
Now the VMs exhibit a rather interesting behaviour: the disk format in the VM settings is shown as "thick", the VMDK files do not have the ddb.thinProvisioned = "1" line, but the actual file size is much less than the virtual disk size. When examined via the Datastore Browser, it shows two different columns for "Size" and "Provisioned Size", just as it would do with a thin-provisioned disk.
Howewer, this doesn't seem to be a problem, as the machines are working fine.
Then, another copy of them was taken for backup purpose; this copy was also made from the command line, using the cp command, between two datastores on the same host (again, both of them iSCSI).
Then we lost the original VMs, and were in need of the backed-up ones.
And these don't work anymore, complaining about corruption of the VMDK files.
So, to recap:

VM created with thin-provisioned disk -> working
VM physically moved between two datastores -> disk shows as thick but behaves as thin, yet VM works fine
VM physically copied between two datastores -> disk behaves the same, VM doesn't work anymore

I tried manually editing the VMDK file to add the ddb.thinProvisioned = "1" line, but this didn't fix the problem. I tried inflating the virtual disk, cloning it and converting it: nothing works, every command complains about the disk being corrupted.
I'm in quite a struggle to bring these VMs up again; can someone please help?
Answer: Looks like physically copying thin-provisioned disks is a bad idea. VMFS does strange things with thin-provisioned disks, things that cp or mv can't cope with. Corruption ensues.
Don't do it. vmkfstools handles them much better (and safer).
Answer: I suspect your storage is a VMFS datastore and not NFS?
You could try downloading / copying the vmdk in question somewhere safe, where you then could start working on it using vmware-vdiskmanager or vmware-mount - both part of VMWare Server / Workstation or available as a standalone download IIRC.
If it all fails, try using 3rd party tools on it - tools like qemu-img from the QEMU package or VBoxManage clonehd from VirtualBox are able to convert vmdks to raw files which you then might simply dd back to your ESX guest.
There is also an alternative disk driver called "vdk" for Windows (the original author's page seems down, but there are downloads of older builds and a 64-bit build around) which is rumored to be able to read partially corrupted vmdk files rather well - although I yet have to try that out.
As for the possible cause of corruption, I'd speculate that the "cp" command was not the culprit. There are plenty of ways to get data corrupted - using iSCSI targets which do not support / implement SCSI reservations is one of them. Anyway, I think the best documented way for a copy process is using vmkfstools - you should stick with that.
Comment: All involved storage was VMFS on iSCSI, but a third copy was made on a NFS datastore on a Windows system, too; I didn't mention this because I know NFS (at least on Windows) doesn't support thin-provisioned disks, so I'm just assuming that's the least salvageable copy I have.
Comment: I already tried vmware-mount, too; it says the virtual disk is corrupted, too.


How can I modify the space between a DevExpress candlestick?

Question: I want to increase the space between candle sticks since my candles overlap when I increase the candle width.
How can I do this from within my xaml code?
Answer: I believe you should decrease the range of values displayed by an date-time axis. To accomplish this task use an instance of the AxisRange type that can be accessed via the Axis.Range property.


Selecting the name for a diminished or augmented chord

Question: Each diminished chord can have 4 names so what is the rule/convention for determining what to call it - or is there none? It would make sense to me if it were named as the VII chord of the scale/key in which the tune is being played, but that clearly wouldn't work if it doesn't include the 7th note of that scale. Does it depend on the chord inversion, i.e. which note is at the top or which note is at the bottom of the chord?
How about Augmented chords, each of which have 3 potential names?
Comment: Sometimes more than 4! E.g. C/B#, D#/Eb, F#/Gb, A/Bbb could be names, depending on keys and functions, of the same sounding dim. chord. Confusing or what?
Comment: Although fully-diminished chords on Ef, Gf, and Bff would be *really* rare; the diminished seventh above each would be Dff, Fff, and Afff (!).
Comment: @Richard - can't think of another reason why bbb would be used!
Answer: For diminished chords, the way the chord is spelled will tell you the root. If the chord is spelled B D F Af, B is the root because it's the bottom of the chord when you stack it in thirds. But if the Af is spelled as a Gs, B is no longer the bottom when you stack it in thirds, but Gs is, so now Gs is the root.
Later in the 19th century, this changes a bit, and composers spell things differently sometimes. If that's the case, run with how the chords functions (=resolves), and provide a label that explains its function best.
As for augmented chords, the process is the same: determine the bottom pitch when you stack it in thirds. If the collection is E C Af, Af is the bottom when you stack it in thirds, so Af is the root. If Af is Gs, suddenly C is the root.
The reason this is difficult is because both of these chords are symmetrical, constructed of consecutive minor and major thirds, respectively. But if you think in terms of thirds, the root should always be clear.
Comment: "'When you stack in thirds' - is there another way" Yes @Tim there is another way. Consider these notes from bottom to top - Ab-B-D-F. That's a diminished 7th chord. What's the interval between A-flat and B natural?
Comment: '*When you stack it in thirds*' - is there another way to play dim. chords? I'm sure I'm missing something, but it's eluding me! I've seen dims (the same chord, ) in different places in the same song, written as a different name, e.g. Co, then later Ao, and never figured why. These are lead sheets, so maybe that's the clue as to which bass/root note gets played?
Comment: @Tim: As given in the example, E-C-Ab is clearly an augmented triad, but it's not stacked in thirds. Just like you can play a major triad in an open voicing, e.g. G-E-C for C major; same for diminished chords
Comment: @MarkM - If Ab was the bottom, the others would be called Cb, Ebb, Gbb. making 'min3rds' between. Actually, it'll be m3, b5, dim7. Ab and B would be #2. Were the bottom G#, it'll be G#, B, D, F.
Comment: @Tim That's the point. Af to B would be an augmented second, therefore it wouldn't be stacked in thirds, therefore Af wouldn't be the root. But "stacking" starting on B *would* result in consecutive thirds, so B would be the root.
Comment: @Richard - I'm obviously missing something here! Would a diminished chord be written with an aug.2nd?
Comment: @Tim I'm not sure how else to say this. The OP's question is important because fully-diminished sevenths are symmetrical; Fs-A-C-Ef are consecutive minor thirds. But once you move from Ef up to Fs, you have an augmented second. Thus, in order to find the root, you have to stack the chords so that they're consecutive thirds; if you have this augmented second on the bottom, it won't be in root position.
Answer: If the 'diminished chord, has a 'minor 3rd, minor 5th, & minor 7th, the chord would be symmetrical in shape / not needing to alter finger position, However: The notes are now, stacked, in 'minor 3rd's.
Comment: Minor 5th doesn't exist. Can't make a perfect interval minor.
Comment: Major  Triad 1-3-5. / Minor Triad 1-b3-5.  Major 7th 1-3-5-7.  Minor 7th 1-b3-5-b7th.  Half Dim,1- b3- b5 - b7th.  Full Dim 7th, 1, b3, -b5,  bb7th


Error installing python 3.7.6 using pyenv on new macbook pro M1 in OS 12.3+

Question: I am struggling to install python version 3.7.6 using pyenv on my new macbook pro M1 running on mac os 12.3.1.
My configuration
$ clang -v
Apple clang version 13.1.6 (clang-1322.214.171.124)
Target: arm64-apple-darwin21.4.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

$ pyenv install 3.7.6

python-build: use email@example.com from homebrew
python-build: use readline from homebrew
Downloading Python-3.7.6.tar.xz...
-> https://www.python.org/ftp/python/3.7.6/Python-3.7.6.tar.xz
Installing Python-3.7.6...
python-build: use tcl-tk from homebrew
python-build: use readline from homebrew
python-build: use zlib from xcode sdk

BUILD FAILED (OS X 12.3.1 using python-build 2.2.5-10-g58427b9a)

Inspect or clean up the working tree at /var/folders/4t/1qfwng092qz2qxwxm6ss2f1c0000gp/T/python-build.20220405170233.32567
Results logged to /var/folders/4t/1qfwng092qz2qxwxm6ss2f1c0000gp/T/python-build.20220405170233.32567.log

Last 10 log lines:
checking for --with-cxx-main=<compiler>... no
checking for clang++... no
configure:

  By default, distutils will build C++ extension modules with "clang++".
  If this is not intended, then set CXX on the configure command line.

checking for the platform triplet based on compiler characteristics... darwin
configure: error: internal configure error for the platform triplet, please file a bug report

Answer: Finally this patch works in installing 3.7.6 on macbook m1 using pyenv.
To install python 3.7.6 version in mac os 12+ , M1 chip, apple clang version 13+ using pyenv, create a file anywhere in your local and call it python-3.7.6-m1.patch and copy the contents(below) to that file and save it.

diff --git a/configure b/configure
index b769d59629..8b018b6fe8 100755
--- a/configure
+++ b/configure
@@ -3370,7 +3370,7 @@ $as_echo "#define _BSD_SOURCE 1" >>confdefs.h
   # has no effect, don't bother defining them
   Darwin/[6789].*)
     define_xopen_source=no;;
-  Darwin/1[0-9].*)
+  Darwin/[12][0-9].*)
     define_xopen_source=no;;
   # On AIX 4 and 5.1, mbstate_t is defined only when _XOPEN_SOURCE == 500 but
   # used in wcsnrtombs() and mbsnrtowcs() even if _XOPEN_SOURCE is not defined
@@ -5179,8 +5179,6 @@ $as_echo "$as_me:
 fi

-MULTIARCH=$($CC --print-multiarch 2>/dev/null)
-

 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for the platform triplet based on compiler characteristics" >&5
 $as_echo_n "checking for the platform triplet based on compiler characteristics... " >&6; }
@@ -5338,6 +5336,11 @@ $as_echo "none" >&6; }
 fi
 rm -f conftest.c conftest.out

+if test x$PLATFORM_TRIPLET != xdarwin; then
+  MULTIARCH=$($CC --print-multiarch 2>/dev/null)
+fi
+
+
 if test x$PLATFORM_TRIPLET != x && test x$MULTIARCH != x; then
   if test x$PLATFORM_TRIPLET != x$MULTIARCH; then
     as_fn_error $? "internal configure error for the platform triplet, please file a bug report" "$LINENO" 5
@@ -9247,6 +9250,9 @@ fi
      ppc)
        MACOSX_DEFAULT_ARCH="ppc64"
        ;;
+     arm64)
+        MACOSX_DEFAULT_ARCH="arm64"
+       ;;
      *)
        as_fn_error $? "Unexpected output of 'arch' on OSX" "$LINENO" 5
        ;;
diff --git a/configure.ac b/configure.ac
index 49acff3136..2f66184b26 100644
--- a/configure.ac
+++ b/configure.ac
@@ -490,7 +490,7 @@ case $ac_sys_system/$ac_sys_release in
   # has no effect, don't bother defining them
   Darwin/@<:@6789@:>@.*)
     define_xopen_source=no;;
-  Darwin/1@<:@0-9@:>@.*)
+  Darwin/@<:@[12]@:>@@<:@0-9@:>@.*)
     define_xopen_source=no;;
   # On AIX 4 and 5.1, mbstate_t is defined only when _XOPEN_SOURCE == 500 but
   # used in wcsnrtombs() and mbsnrtowcs() even if _XOPEN_SOURCE is not defined
@@ -724,8 +724,7 @@ then
 fi

-MULTIARCH=$($CC --print-multiarch 2>/dev/null)
-AC_SUBST(MULTIARCH)
+

 AC_MSG_CHECKING([for the platform triplet based on compiler characteristics])
 cat >> conftest.c <<EOF
@@ -880,6 +879,11 @@ else
 fi
 rm -f conftest.c conftest.out

+if test x$PLATFORM_TRIPLET != xdarwin; then
+  MULTIARCH=$($CC --print-multiarch 2>/dev/null)
+fi
+AC_SUBST(MULTIARCH)
+
 if test x$PLATFORM_TRIPLET != x && test x$MULTIARCH != x; then
   if test x$PLATFORM_TRIPLET != x$MULTIARCH; then
     AC_MSG_ERROR([internal configure error for the platform triplet, please file a bug report])

NOW we can Install python 3.7.6 using pyenv as follows (need to be in the same directory as the patch file that we just created):
pyenv install --patch 3.7.6 < python-3.7.6-m1.patch

To install other python version on mac os 12+ , M1 chip, apple clang version 13+ using pyenv (not tested but should work)
Shallow clone the branch of python version you are interested in installing. go to https://github.com/python/cpython  and find the versions available for cloning under "tags" dropdown
git clone https://github.com/python/cpython --branch v3.x.x --single-branch
cd cpython

Now make changes to the two files in it (configure.ac and configure). the git diff should look like the one shown above. The line numbers will be different based on which version of python you are installing, this git diff file is for 3.7.6 and can't be directly used for other versions. for other versions of python, search for the exact line of code being edited/deleted in the exact file as shown in the above git diff and make the changes accordingly. then save the git diff in a new file as follows.
git diff > python-3.x.x-m1.patch

Now we can install that version using:
pyenv install --patch 3.x.x < python-3.x.x-m1.patch

Comment: Thanks for your answer. It is not working for me.  Output:
pyenv install --patch 3.7.6 < python-3.7.6-m1.patch
python-build: use email@example.com from homebrew
python-build: use readline from homebrew
Downloading Python-3.7.6.tar.xz...
-> https://www.python.org/ftp/python/3.7.6/Python-3.7.6.tar.xz
Installing Python-3.7.6...
patching file configure
Hunk #4 FAILED at 9250.
1 out of 4 hunks FAILED -- saving rejects to file configure.rej
patching file configure.ac

BUILD FAILED (OS X 12.0.1 using python-build 20180424)
Answer: If you are not bound to a particular patch (i.e. z in x.y.z), this excerpt from the following link could help you:

I can confirm yesterday's releases 3.7.13, 3.8.13, 3.9.11 and 3.10.3 all work fine on my Intel mac. The GCC solution was not a viable one for me as it caused issues with pip modules that were built with clang. I don't think I need 3.6 or older branches at the moment but I suspect they might need manual patches via pyenv since they're EOL upstream.

I personally needed the 3.8.x version and succeeded with pyenv install 3.8.13.
Comment: I have updated my comment, Chris.


Finding equilibrium solutions of $y'+y=te^{-1}+1$

Question: $$y'+y=te^{-1}+1$$
I'm trying to find the equilibrium solutions, and the "long time behaviour" of this differential equation
I quickly recognized the form $y'+p(t)y=g(t)$ and found $\mu (t)$ to be $e^{t}$, since $p(t)=1$, $\mu (t)=e^{\int p(t)dt}$.
Then, since $\mu (t)y=\int\mu (t)g(t)dt$, I found $y=te^{t}$.
The solutions manual says that $\mu (t)=e^{2t}$, but I see no reason that the $2$ should be there.
Then long term behaviour would be the $\lim_{t->\infty} y=te^{t}$.  Any help plotting this in Matlab using 'dirfield.m' would be also much appreciated.
Comment: @LetThisNightExplode: Are you sure that $g(t)$ is supposed to be $te^{-1}$? If so, then your integratong factor is correct, but your solution is not.
Comment: I just did a correction to the original equation.  I think I need to move that $-1$ over, since it's not  a function of $t$ either.  So then my $p(t)$ is $y-1$.
Comment: No, you want to leave it where it is. If you moved it over, your $p(t)$ would be $1-\frac1y,$ which is not an explicit function of $t.$
Answer: Edit: Note that by examining the form of the solution given by the manual, we have the indeterminate $c$ multiplied by $e^{-t},$ rather than $e^{-2t}.$ This suggests that the integrating factor $e^t$ was, in fact, intended by the manual, and that $e^{2t}$ was just a typo.
Assuming that the posted ODE is correct, then $$(ye^t)'=y'e^t+ye^t=(y'+y)e^t=te^{t-1}+e^t,$$ so $$ye^t=\int\left(te^{t-1}+e^t\right)\,dt=(t-1)e^{t-1}+e^t+c,$$ and so $$y=(t-1)e^{-1}+1+ce^{-t}$$ is the family of solutions to the posted ODE.

How could such a different solution have been obtained? Well, it turns out that, letting $u=t^2e^{-t}/2+1+ce^{-t}$ for any constant $c,$ we then have $$u'+u=te^{-t}+1.$$ Thus, I suspect that the ODE was intended to be $$y'+y=te^{-t}+1,$$ instead. From this ODE, we have in a similar fashion that $$(ye^t)'=t+e^t,$$ whence $$ye^t=\int(t+e^t)\,dt=t^2/2+e^t+c,$$ and we have exactly the solution family from the manual (as one would hope).


Cut non-binary tree into sub-trees of maximum depth

Question: Is there an algorithm to cut a non-binary tree into a minimal number of sub-trees with a given maximum depth?
Example: Given this non-binary tree with node A as its root. Cut the tree into a minimal number of sub-trees with a maximum depth of 2.
In the example the cut would need to be performed between nodes A-B or B-G to achieve the desired result.
Answer: Each edge removal partitions the tree into two subtrees, so minimizing the number of subtrees is equivalent to minimizing the number of removed edges.  One approach is to use dynamic programming.  Let $f(T)$ be the desired minimum number of removed edges for tree $T$.  The boundary case is $f(T)=0$ if $T$ has depth at most two.  Otherwise,
$$f(T) = 1 + \min_{(i,j)\in E(T)} \{f(T_1) + f(T_2)\},$$
where $T_1$ and $T_2$ are the two subtrees obtained by removing edge $(i,j)$.


What does "moderato" in the middle of a musical score mean?

Question: A study I am playing has these tempo hints:

Slowly, Freely in the beginning
Accelerando when the next section starts
moderato shortly afterwards

(I cut the score in the middle)
What does moderato mean in this context?
Does it mean "accelerate gradually until you play at the moderato tempo"?
Or does it mean "accelerate, but then slow back down to the moderato tempo"?
Or is it a hint on dynamics?
P.S. Here is an example recording:
Comment: Have you listened to any recordings of this piece? That'd be my first port of call.
Comment: They are very different (checked 3). Didn't help me understand what is going on.
Comment: Which maybe says a lot about the 'moderato' mark. As in "We don't really know what the composer wanted either...". Seems to be a piece where rubato reigns supreme.
Comment: It's an etude so tempo isn't really a big deal.  As Todd Wilcox suggests below, you accelerate until from after the pause and then 'ease in' to a medium tempo (moderato) where you can comfortably make the chords 'flow' as the composer suggests.
Answer: I would certainly read it as:

Start accelerating at the accelerando so that you are playing at a moderato tempo when you get to the moderato, then continue to play moderato until you reach another tempo marking or the end of the piece.

That might not be exactly how others play it, and every performance involves interpretation of the score by the performer(s), but that is the only literal interpretation I can think of for those markings.
Moderato indicates a tempo faster than andante and slower than allegro, usually between 108 and 120 beats per minute.
Slowly could also be called lento and is likely meant to be 45 - 60 beats per minute. If so, that accelerando is really brief, since at the end of it you are being told to play twice as fast as at the beginning. Slowly might instead mean more of an adagio tempo of 66 - 76 beats per minute. Before you get too caught up in exactly how slow or fast to play, read the next paragraph.
Note the word freely in the initial tempo marking. That means you are invited to play around with the tempo a little bit. The composer expects/suggests that you speed up and slow down a little bit as you play to better convey emotion. A good question about that is, should we continue to play freely through the whole piece, even after other tempo markings? I would say yes, and I would interpret the freely at the beginning to indicate the whole piece is to be played with interpretive tempo.
Comment: Hence lots of rubato.
Comment: @Tim Personally I see "freely" and "rubato" being slightly different, but I'm not sure if I could the difference into words. With *rubato* I see it as the player has to pay back what has been robbed, so if you slow down in place you have to catch up later. *Freely* to me is whatever the player wants to do (within reason).
Answer: If I would have a guess I would say that it is a poor score and what the piece really wants is a return to the original tempo. It would be better to indicate that with the terms tempo primo or a tempo.
It is confusing as you rightly point out. Moderato is an indication of character, not mere speed or tempo. As with such things the character is indicated at the beginning of the piece.
Comment: Moderato is so vague a term to not bother putting it on music anywhere!
Comment: @Tim That's funny. As indicated in my answer, I find *moderato* to be just as specific and useful as all other tempo markings like *allegro*, *andante*, *largo*, etc. But the different interpretations we all have is what keeps music alive.


Unrecognized file format in stored as clause CSV Hive

Question: I'm trying to create a csv hive table (using Hive CLI) into S3.
create external table hello (
name INT)
stored as csv
location 's3://bucket/myfolder;

==> Error SemanticException Unrecognized file format in stored as clause 'CSV'
I deleted EXTERNAL
create table hello (
name INT)
stored as csv
location 's3://bucket/myfolder;

==> The same Error SemanticException Unrecognized file format in stored as clause 'CSV'
Knowing that I'm using an Apache Hive + Apache Hadoop (I installed it because Hive need some hadoop binaries).
Do you have an idea please, Thanks
Answer: CSV is not a valid file type. Try this instead:
create external table hello (
name INT)
row format delimited
fields terminated by ','
stored as textfile
location 's3://bucket/myfolder';

Or
create external table hello (
name INT)
row format serde 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
stored as textfile
location 's3://bucket/myfolder';


Alguém sabe se é possível estilizar a API de notificação (Notification) nativa do Chrome?

Question: Olá, foi-me pedido que utilize a API de notificação (Notification) nativa do Chrome para exibir uma notificação para o usuário assim que ele entrar no sistema (sei que poderia utilizar outros modos, porém me foi pedido para utilizar isso).

Essa notificação é criada em JS e faz uma requisição no PHP que retorna dados de uma consulta.
O arquivo que eu faço a consulta  é o notificacoes-pontuais-consulta.php que aparece no código mostrado logo abaixo.

Gostaria de saber se é possível estilizar essa Janela que é aberta. Gostaria de, por exemplo, mudar o background-color, color, font-size, entre outros...
Vocês sabem se isso é possível ? Procurei bastante, porém achei nada falando sobre o assunto.
Segue abaixo o código que utilizo para criação dessa janela de notificação:

<code>$(document).ready(function() {
  let chamar = minhaNotificacao();

});

document.addEventListener('DOMContentLoaded', function() {
  if (!Notification) {
    alert("As notificações no desktop não estão disponíveis para o seu navegador. Tente o Chrome");
    return;
  }

  if (Notification.permission !== "granted") {
    Notification.requestPermission();
  }
});

function minhaNotificacao() {
  if (Notification.permission !== "granted") {
    Notification.requestPermission();
  } else {
    $.ajax({
      url: "../banco/notificacoes-pontuais/notificacoes-pontuais-consulta.php",
      data: {
        fonte: 'aocarregar'
      },
      type: "POST",
      async: true

    }).done(function(data) {

        var notification = new Notification('Notificação diária', {
          icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
          body: 'Você possui: \nLembretes de eventos para hoje: ' + data.eventos_lembretes + '\nLembretes de Tarefas: ' + data.eventos_tarefas + '\nEventos Vencidos: ' + data.eventos_vencidos,

        });

      }
    }</code>

Abaixo, mostro como a notificação aparece quando chamada:

Obrigado!
Comment: Por favor, caro downvoter, me mostre onde errei nessa pergunta para que talvez eu possa melhorá-la ou melhorar minhas próximas.
Answer: Você pode conferir aqui as opções de personalização:
https://developer.mozilla.org/pt-BR/docs/Web/API/notificacoes
e compatibilidades:
https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API
Como você deve fornecer um objeto com essas propriedades citadas, a menos que a API interpretasse HTML no campo body, não existe nenhum campo para mudar o layout, e o campo body é somente uma string.
E essa padronização é necessária para o bom funcionamento da API e para preservar o usuário, imagina se pudesse botar CSS nas notificações, iria abrir uma possibilidade para fazer as notificações serem mais agressivas, não precisa nem comentar javascript.
Comment: é uma limitação da API mesmo, para evitar o que foi mencionado, sem está possibilidade alguns sites já conseguem abusar com imagens extremamente irritantes e propagandas que nem se fala, já li a documentação atraz disso e tal função é barrada mesmo, se pudesse usar outras API aí poderia fazer qualquer coisa mas a nativa permite no máximo o Dialog Grande
Comment: aqui o motivo https://stackoverflow.com/a/19834197/2741415 por exemplo
Comment: Sim, brother. Eu já havia acessado esses seus links. Realmente nesses links não mostra nada sobre fazer isso. Mas achei que talvez houvesse um jeito.
Comment: Eu acredito que não há, pois se houvesse diria na documentação. Acredito que haveria uma propriedade Notification.background com opções pre-selecionadas por eles ao invés de deixar personalizar livremente, ou por ex: Notification.body.style.font-size.
Comment: Poxa, pessoal. Valeu mesmo pelos esclarecimentos.