Alternatives to Apache

Question: Our current stack is Apache + Tomcat + MySQL, using ProxyPass AJP to fire requests from Apache to Tomcat. We also run PHP for Wordpress on the same sites, and so need working .htaccess files. In response to an annoying problem (see this Stack Overflow page), we're considering alternative stacks. Note that we generally quite like apache, but this problem is a show-stopper: if we can't fix it, we can't use Apache.
Alternatives include:

Tomcat alone
Glassfish (Java app server, forked from Tomcat)
Jetty (Java server)
Resin
LightTPD (lightweight HTTP server)
Nginx (lightweight HTTP server)

The way I see it, solutions fall into two camps: the pure Java camp, such as Glassfish; or the split camp such as our current Apache + Tomcat. We like the idea of a pure Java solution, since fewer moving parts should mean less to go wrong; but do any of them support PHP, .htaccess files, etc?
In theory we could do the split the other way - have a simple front end that proxies to Apache on only those bits that need those features - but in practice that would be 80% of requests.
What options do people suggest?
Comment: Would you mind elaborating your "annoying show-stopper problem" a bit more, or is it completely irrelevant?
Comment: Follow the link to the StackOverflow page for more details. It's a bug where clients are delivered the wrong response - sometimes getting JS or CSS files instead of HTML ones, or just the wrong page entirely. We've tried pretty much everything within Apache and Tomcat we can think of.
Answer: I strongly suspect your problem is related to AJP.
I was in a course with one of the main Tomcat developers a few weeks ago (he was running it), his advice was to avoid AJP and mod-JK etc, and stick to regular mod-proxy HTTP.
Reasons:

It's by far the most mature and stable Tomcat connector.
Neither AJP implementation has been consistently developed; both projects have suffered a bit of stop / start.
NBIO does not result in any real world performance gain over blocking-IO, in this situation.

My advice, try using regular mod-proxy HTTP with your current setup. It's the least change for you and it will take you on to the most widely used and stable Tomcat deployment architecture.
/ Richy
Comment: ProxyPreserveHost On is probably what you're looking for.

http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#proxypreservehost
Comment: How can I use regular mod-proxy and still get the correct host names coming through to Tomcat? I'm pretty sure they're all being recieved as localhost at the moment.
Comment: I suppose I could give it a go. Do you have any hard numbers on the performance difference?
Answer: My current preferred stack is to use nginx as a replacement for Apache. Wherever necessary, php-fpm fills in the need for PHP. Such a setup has worked nicely for deploying apps such as Rails, Magento and SugarCRM.
Answer: Glassfish will be more scalable than Tomcat because it uses Grizzly (NIO based). You don't have many options other than a variation of Tomcat, Jetty, or Glassfish because of the Java requirement. PHP can be run using Quercus, but it may be better to just deploy it using Nginx.
Answer: There are PHP implementations on Java, The one I know (but haven't used) is this one. There is a blog post on how to install it on GlassFish (including WordPress), but I guess the installation on tomcat is the same. Regarding the .htaccess, you haven't written what exactly you have there, but if it is for URL rerwriting then there is the  UrlRewriteFilter who does the same work with the same semantics.
Comment: The .htaccess files are mostly those generated by WordPress, so they contain a few simple RewriteRules
Comment: I guess the PHP will not support them, but it shouldn't be hard to have a process that reads them and passes the definitions to the filter.
Answer: Cherokee ? where is he ? http://www.cherokee-project.com/

Alternatives to Apache


Fatal Error - Fatal error: Unsupported operand types in public_html/includes/common.inc on line 2999

Question: The page of my work is not loading anymore!
And Im not used to deal with drupal!
What I have to do to the page load properly! I even cant login as user or see any page of the site!
PLZ im really desesperated!
this error show when i try to enter in the page:
Fatal error: Unsupported operand types in /home/storage/2/58/58/xxxxx/public_html/includes/common.inc on line 2999
the page i wanna to work is that: www.meddco.com.br!
Comment: Welcome to Drupal Answers. Could you please provide more information about your issue and improve your question, thank you.
Comment: i dont know what is happening......i just cant access the site anymore!
Comment: the last think i did was try to put a new form with php......and before it everthing was crashed!
Comment: is this a custom module that you added the form with .  if so are you using drush .  As I would disable (dis) the module using drush if it where me.
Comment: how can i do it? im a newbie in drupal!
Comment: @Meddco you need to provide more information otherwise we cannot help you. Please re-edit the question and add details such as what you did before this issue, what kind of form is this (is it a custom module?) or where you placed the piece of code (some PHP field?) etc.
Comment: Actually i placed the code in "text" field and put php filtered! i cant give more details cause i have not more access at page or main page or user page and admin page!
Comment: i did this edit when im create a new block
Comment: Do you have access to the database? Phpmyadmin or something?
Comment: Yes,  I have access!
Answer: You need to access the installation's database.

Find the 'block_custom' table. This contains all custom blocks.
Browse the records and locate the one which creates the problem.
Clear the field 'body' which should contain your custom PHP code.
Comment: ok! im in database! i found just blocks / blocks_roles /
cache_block and  multiblock!
Comment: how i find "body" in this lines! im dont have any experience in DB!
Comment: Man! I think I resolved.....i didnt find the "body" but found the blocks with the name i did put when setting! Now i have access back!
Comment: u saved my life and my job!
Comment: Where did you find them? If the answer satisfied your question mark it as accepted, and I would recommend you to modify your original post to form a proper question that could help other users as well.


Plotly paper formatting is not uniform

Question: I am using the annotation system in Plotly to annotate the axis of a graph. I am specifying coordinates using the "paper" setting in plotly. However, I have noticed that paper coordinates are not always uniform across a figure, at least when arrows are turned off. Does anyone know why this might be happening? Here I provide code to show you:
def test():

    fig = go.Figure()

    ylabels = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
    annotations = []
    for i, label in enumerate(ylabels):
        print(label/100)
        annotations.append(
            dict(
                yref = 'paper',
                y = label/100, x = 0,
                text = ylabels[1],
                showarrow = False,
                yshift = 0,
            )
        )
    fig.update_layout(
        annotations = annotations,
        yaxis = dict(
            showticklabels = False,
            tickvals = ylabels,
            range = [0, 100]
        ),
        xaxis = dict(
            showticklabels = False
        )
    )
    fig.show()

Non-uniform spacing when arrows are off
For some reason, this has to do with turning off the arrows. When the arrows are on, they are evenly spaced across the x-axis.
Uniform spacing when arrows are on
Answer: The issue seems to be resolved by setting yanchor equal to either top, middle, or bottom, see the Plotly documentation.
import plotly.graph_objects as go

fig = go.Figure()

ylabels = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

annotations = []
for i, label in enumerate(ylabels):
    annotations.append(
        dict(
            yref='paper',
            y=label / 100,
            x=0,
            text=ylabels[1],
            showarrow=False,
            yshift=0,
            yanchor='middle' # default is 'auto'
        )
    )

fig.update_layout(
    annotations=annotations,
    yaxis=dict(
        showticklabels=False,
        tickvals=ylabels,
        range=[0, 100]
    ),
    xaxis=dict(
        showticklabels=False
    )
)

fig.show()

Plotly paper formatting is not uniform


Right aligning text in PdfPCell

Question: I have a C# application that generates a PDF invoice. In this invoice is a table of items and prices. This is generated using a PdfPTable and PdfPCells.
I want to be able to right-align the price column but I cannot seem to be able to - the text always comes out left-aligned in the cell.
Here is my code for creating the table:
PdfPTable table = new PdfPTable(2);
table.TotalWidth = invoice.PageSize.Width;
float[] widths = { invoice.PageSize.Width - 70f, 70f };
table.SetWidths(widths);
table.AddCell(new Phrase("Item Name", tableHeadFont));
table.AddCell(new Phrase("Price", tableHeadFont));

SqlCommand cmdItems = new SqlCommand("SELECT...", con);

using (SqlDataReader rdrItems = cmdItems.ExecuteReader())
{
    while (rdrItems.Read())
    {
        table.AddCell(new Phrase(rdrItems["itemName"].ToString(), tableFont));
        double price = Convert.ToDouble(rdrItems["price"]);
        PdfPCell pcell = new PdfPCell();
        pcell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
        pcell.AddElement(new Phrase(price.ToString("0.00"), tableFont));
        table.AddCell(pcell);
    }
}

Can anyone help?
Comment: I've met with the same problem, and found no workable solution for a `Phrase` object. THe best I can suggest is that you use a `Paragraph` instead of `Phrase` and set the alignment for the Paragraph itself.
Answer: I'm the original developer of iText, and the problem you're experiencing is explained in my book.
You're mixing text mode and composite mode.
In text mode, you create the PdfPCell with a Phrase as the parameter of the constructor, and you define the alignment at the level of the cell. However, you're working in composite mode. This mode is triggered as soon as you use the addElement() method. In composite mode, the alignment defined at the level of the cell is ignored (which explains your problem). Instead, the alignment of the separate elements is used.
How to solve your problem?
Either work in text mode by adding your Phrase to the cell in a different way.
Or work in composite mode and use a Paragraph for which you define the alignment.
The advantage of composite mode over text mode is that different paragraphs in the same cell can have different alignments, whereas you can only have one alignment in text mode. Another advantage is that you can add more than just text: you can also add images, lists, tables,... An advantage of text mode is speed: it takes less processing time to deal with the content of a cell.
Comment: Thank you! Through the right combination of paragraphs and cells, I've managed to get this working. It's been driving me mad for months!
Comment: "In a different way?"
Comment: does this mean I can do `.AddCell(new Paragraph("txt"){ Alignment = Element.ALIGN_RIGHT})`  and right align in cell?
Answer: private static PdfPCell PhraseCell(Phrase phrase, int align)
{
    PdfPCell cell = new PdfPCell(phrase);
    cell.BorderColor = BaseColor.WHITE;
    // cell.VerticalAlignment = PdfCell.ALIGN_TOP;
    //cell.VerticalAlignment = align;
    cell.HorizontalAlignment = align;
    cell.PaddingBottom = 2f;
    cell.PaddingTop = 0f;
    return cell;
}

Comment: Yes, that's one possible solution. See my answer for a more elaborate explanation.
Answer: Here is my derivation of user2660112's answer - one method to return a cell for insertion into a bordered and background-colored table, and a similar, but borderless/colorless variety:
private static PdfPCell GetCellForBorderedTable(Phrase phrase, int align, BaseColor color)
{
    PdfPCell cell = new PdfPCell(phrase);
    cell.HorizontalAlignment = align;
    cell.PaddingBottom = 2f;
    cell.PaddingTop = 0f;
    cell.BackgroundColor = color;
    cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
    return cell;
}

private static PdfPCell GetCellForBorderlessTable(Phrase phrase, int align)
{
    PdfPCell cell = new PdfPCell(phrase);
    cell.HorizontalAlignment = align;
    cell.PaddingBottom = 2f;
    cell.PaddingTop = 0f;
    cell.BorderWidth = PdfPCell.NO_BORDER;
    cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
    return cell;
}

These can then be called like so:
Font timesRoman9Font = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 9, BaseColor.BLACK);
Font timesRoman9BoldFont = FontFactory.GetFont(FontFactory.TIMES_BOLD, 9, BaseColor.BLACK);

Phrase phrasesec1Heading = new Phrase("Duckbills Unlimited", timesRoman9BoldFont);
PdfPCell cellSec1Heading = GetCellForBorderedTable(phrasesec1Heading, Element.ALIGN_LEFT, BaseColor.YELLOW);
tblHeadings.AddCell(cellSec1Heading);

Phrase phrasePoisonToe = new Phrase("Poison Toe Toxicity Level (Metric Richter Scale, adjusted for follicle hue)", timesRoman9Font);
PdfPCell cellPoisonToe = GetCellForBorderlessTable(phrasePoisonToe, Element.ALIGN_LEFT);
tblFirstRow.AddCell(cellPoisonToe);

Answer: I ended up here searching for java Right aligning text in PdfPCell. So no offense if you are using java please use given snippet to achieve right alignment.
private PdfPCell getParagraphWithRightAlignCell(Paragraph paragraph) {

 PdfPCell cell = new PdfPCell(paragraph);
 cell.setBorderColor( BaseColor.WHITE);
 cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
 return cell;

}

In getParagraphWithRightAlignCell   pass paragraph
Thanks
Answer: Perhaps its because you are mixing the different ways to add the cells? Have you tried explicitly creating a cell object, massaging it however you want then adding it for every cell?
Another thing you could try is setting the vertical alignment as well as the horizontal.
Answer: cell.HorizontalAlignment = Element.ALIGN_RIGHT;

Right aligning text in PdfPCell


InjectionToken mat-select-scroll-strategy error with angular material lazy loading problem

Question: i have two modules in my angular 9 app
only one module uses angular material.
so my app.module.ts don't load it, i use lazy loading
but when i run the app it shows an error

NullInjectorError: R3InjectorError(t)[InjectionToken mat-select-scroll-strategy -> InjectionToken mat-select-scroll-strategy -> InjectionToken mat-select-scroll-strategy -> InjectionToken mat-select-scroll-strategy]:
NullInjectorError: No provider for InjectionToken mat-select-scroll-strategy!

some one help please.
Comment: I believe this is related to https://github.com/angular/components/issues/19335, unfortunately the bug is not getting a lot of traction.
Comment: i think material modules should be loaded on the first instance
Answer: What removed the error for me, was including MatDialogModule and MatMenuModule in the AppModule, which isn't lazy-loaded:
import { MatDialogModule } from '@angular/material/dialog';
import { MatMenuModule } from '@angular/material/menu';

Then finally the mat-menu worked again!
Why does this work?
My guess is that some @angular/material components have some implicit dependencies on those 2 specific modules. Hopefully they fix it in the future, so you don't need this...
Comment: why this solved the issue?
Comment: @pixparker updated answer ^
Answer: I faced the same situation. What solves me is to import MatAutocompleteModule in app.module.ts even you need it in submodules.
app.module.ts
import {MatAutocompleteModule} from '@angular/material/autocomplete';

imports: [
  MatAutocompleteModule,
]

Comment: Thank you for your answer which solved the problem for me too. I wonder if you figured out why it is also needed in app.module.ts ?
Answer: The below solution works for me:
You must have to import this module at the root level instead of the module based, earlier I imported it at the module level.
Import below three modules in your app.module.ts or shared module which you shared across the application

MatInputModule
MatAutocompleteModule
MatSelectModule

import { MatInputModule } from '@angular/material/input';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatSelectModule } from '@angular/material/select';
Answer: In my case, there was a routing error. In the parent path using lazy loading, I have placed the bookmarks component. In the morning I also referred to the same component with tabs.
Parent:
{
    path: MyProfileRoutesEnum.settings,
    data: {[MY_DATA_PARAM]: true},
    component: MySettingsContainerComponent, // need to delete this
    loadChildren: () => import('./my-settings/my-settings.module').then((m) => m.MySettingsModule),
},

Child:
{
    path: `:${TAB_PARAM}`,
    component: MySettingsContainerComponent,
},

Must be parent:
{
    path: MyProfileRoutesEnum.settings,
    data: {[MY_DATA_PARAM]: true},
    loadChildren: () => import('./my-settings/my-settings.module').then((m) => m.MySettingsModule),
},

Answer: In my case, I accidentally placed a route in app.routing that refers to the lazily loaded component.
So I had the path in app.module added as
{path: 'worksheet-list', component: WorksheetListComponent},

Instead of keeping the path inside the lazy module


MySQL query with WHERE clause, but drop a condition if no results?

Question: I'm currently doing this via two separate queries from PHP, but would love to optimize and somehow in a single query.
First query..
SELECT `referrer`
FROM `tbl_traffic_log`
WHERE `domain` = 'mysite.com'
  AND `referrer` != '$referringDomain'
  AND CASE WHEN `clicks_in_unique`=0 THEN 2 ELSE `clicks_out_unique`/`clicks_in_unique` END < 1.4
ORDER BY RAND()
LIMIT 1

..and if mysql_num_rows shows no results, I do a second query to try again and check if there are any results minus the referrer != 'partner1.com' part.
The code is basically trying to find a random trade partner who ISN'T the partner who sent that click, but if there are no matches, as a last resort it's ok to send back, provided it matches the other criteria.
I'm pretty sure there is a way to do this, but just can't find a way after searching (probably because I'm not understanding the problem enough to type in the right thing).
Any other critique of the query is welcome as well.
Thank you :)
Comment: 2 queries are perfectly fine. Don't try to fit everything into 1 query.
Answer: I think you can do this like this:
SELECT `referrer`
FROM `tbl_traffic_log`
WHERE `domain` = 'mysite.com'
  AND CASE WHEN `clicks_in_unique`=0 THEN 2 ELSE `clicks_out_unique`/`clicks_in_unique` END < 1.4
ORDER BY `referrer` != '$referringDomain' desc, RAND()
LIMIT 1

The idea is to put the condition in the order by.  The condition (in MySQL) evaluates to either 0 or 1, so we want where the condition is true first (hence the desc).  It then chooses a random row.  If there are no rows where the condition is true, then it chooses a random row.


Simplyfying the equation

Question:
It is given that, $a+b+c=0$ we will have to prove that,
  $$\frac{1}{x^b + x^{-c}+1} + \frac{1}{x^a + x^{-b}+1} + \frac{1}{x^c +
 x^{-a}+1} =1$$

What I have done is, $a=-(b+c)$ into the equation and also I have tried with multiplying $x^a, x^b x^c$ but it didn't look simple. What should be done here?
Answer: Keeping the first term as is, I am trying to set the numerator of the rest two terms as parts of the denominator of the first term.
$$\frac1{x^a+x^{-c}+1}=\frac{x^b}{x^{b+a}+1+x^b}=\frac{x^b}{x^{-c}+1+x^b}\text{ as }b+a=-c$$
$$\frac1{x^c + x^{-a}+1}=\frac{x^{-c}}{1+x^{-(c+a)}+x^{-c}}=\frac{x^{-c}}{1+x^b+x^{-c}}\text{ as }c+a=-b$$

Simplyfying the equation


jquery .find to get the text in a

Question: So I have a series of 2 nested ul's.  When you click on the text (which is in an a tag) in the li, my page makes that editable and adds a save button.  clicking the save button needs to give me back the new text inside that li and the id of that li.  The id is not a problem.  I'm trying to use jQuery's .find to select that anchor tag (which is successful) but i can't seem to get the text from it.
Here is an example of the first list and it's sublists.

     List 1 Name

         Sub 1 Name

         Sub 2 Name

         Sub 3 Name

Here's the code for identifying which save button you clicked.
function SaveName(parentid){
  $('li').find('a').each(function(){
    if (this.id == parentid){
      alert(this.id+' '+this.text)
      }
  }
});

I am wanting this.text to show me the text inside the anchor tags.  Help, please?
===========================================================
Edit:
Please excuse this post.  The problem was that I was using Jeditable and didn't know that it would put in a form in place of the text, so anything that would call text wouldn't work.  Sorry.
Answer: simply use $(this).text() instead of this.text
To be honest, I don't understand the logic behind this function, because your function could have been written as:
function SaveName(parentid) {
     alert($('li a#' + parentid).text();
  }
});

Or may I suggest an alternative way of doing what you intented:

     List 1 Name

         Sub 1 Name

         Sub 2 Name

         Sub 3 Name

Javascript:
function SaveName(element) {
   alert($(element).prev("a").text());
}

Comment: i have tried that.  i also tried it again after your response and it still gave me nothing (an empty string?).
Comment: i also tried the alternatives you suggested.  i still got nothing for the .text().  would it make a difference that using firebug i can see that there is an inline form that is added by jquery when the field becomes editable?
Answer: Remove the inline handlers, bad karma.
$(document).ready(function(){
   $('.list1subs > li').find('img').bind('click', function(e){
      var $this = $(this);
      alert($this.siblings('a').text());
   });
});

Comment: siblings() is more reliable just in case he changes the markup
Comment: the problem with this solution is that there are a variable (and possibly infinite) number of lists and subs within those lists.  i am using python and HTML_TMPL, so i can use TMPL_LOOPS but i'd rather avoid that if possible.  i'll give it a shot either way.
Comment: i'm dumb.  the UL's have consistent classes.  the id on the sublists changes with the sublist id, but the classes are always 'lists' and 'sublists'
Comment: it also still appears to be giving me an empty string in response to $this.siblings('a').text()
Answer: Ok, so when I clicked on the field, I was using Jeditable to make the field edit in place.  Clearly I didn't understand what this doing, because it inserts a form using what you supply.  This is why whatever.text() was coming back blank.  It wasn't counting the form as text, so it skipped it.

jquery .find to get the text in a


Prove $3\mid σ(3n + 2)$ and $4\mid σ(4n + 3)$ for any positive integer n.

Question: In this problem, $\sigma$ is sum of the positive divisors of $n$.
Comment: [This formula](https://docs.google.com/document/d/1WZt02aSDHDNiKmh0artRaQ9g0ercrs7fi5B1oTwdmYw/edit) could help you.
Comment: I was thinking about using the sum notation of sigma to show that it is divisible by 3 but am unsure where to go from there. Possibly showing one portion of the sum is congruent $mod2$ and the other is congruent $mod1$?
Answer: We solve the $4n+3$ problem. Suppose that $4n+3$ has prime power factorization
$$4n+3=p_1^{a_1}p_2^{a_2} \cdots p_k^{a_k}.$$
Since the function $\sigma$ is multiplicative, we have
$$\sigma(4n+3)=\sigma(p_1^{a_1})\sigma(p_2^{a_2}) \cdots \sigma(p_k^{a_k}).$$
The number $4n+3$ must have at least one prime divisor congruent to $3$ modulo $4$ occurring to an odd power. Without loss of generality we may assume that $p_1\equiv 3\pmod{4}$ and that $a_1$ is odd.
We show that $4$ divides $\sigma(p_1^{a_1})$. Note that
$$\sigma(p_1^{a_1})=\frac{p_1^{a_1+1}-1}{p_1-1}.$$
Finally, since $a_1+1$ is even, we have that $p_1^{a_1+1}-1$ is divisible by $8$. Since $2$ is the highest power of $2$ that divides $p_1-1$, the result follows.  Alternately, the sum $1+p_1$ is divisible by $4$, as is the sum $p_1^2+p_1^3$, and so on.
The result for $3n+2$ can be proved in a very similar way.
Comment: can you explain why the top portion is divisible by 8?
Comment: If $y$ is odd, then $y^2\equiv 1\pmod{8}$. One way to show this is that $y^2-1=(y-1)(y+1)$, and one of $y-1$ or $y+1$ is divisible (at least) by $4$, while the other is divisible by $2$. Or else square each of $1,3,5,7$ and observe that each of $1,9,25,49$ is congruent to $1$ modulo $8$.
Answer: HINT: Suppose that $a\mid 3n+2$. Then there is an integer $b$ such that $ab=3n+2$. Show that one of $a$ and $b$ is congruent to $1$ and the other to $2$ modulo $3$, and conclude that $3\mid a+b$. The other problem is very similar.


How to reproduce the sound of Dizzy's muted trumpet in early bebop jazz recordings?

Question: How can I reproduce the muted trumpet sound of Dizzy Gillespie's that can be heard in many of the early bebop recordings together with Charlie Parker?
I believe he was using a cup mute, but is the material and/or other properties of the mute relevant? What do I need to emulate this sound?
Here are some listening examples with the sound I'm asking about:
* Bloomdido (Melody plus solo @1:26)
* Mohawk (Melody plus solo @1:48)
* Groovin' High (Melody plus solo at @1:34)
Answer: Bobby Shew names a mute made in Sweden (how ironic, given your name) in the following words:

There is a company in Sweden that makes the Dizzy Gillespie model
  mutes which, when you can find them, are worth purchasing although
  very expensive. The cup in this set is made of a white plastic and
  separates into two pieces, one of which looks like a straight mute and
  which could be used as one, and another piece which is similar to a
  plunger which snaps over the end of the straight to form a cup. It has
  a surprisingly good sound for being plastic. It lacks the hard,
  brittle quality which makes the metal mute undesirable,

http://www.bobbyshew.com/clinics/Mutes.htm
People at thetrumpetherald seem to think the brand name is Ullven:
http://www.trumpetherald.com/forum/viewtopic.php?p=396166&sid=54cff5da7758ec3fd70599160a0101bf
They don't seem to be in business anymore, and I am not even sure that that is the model Gillespie actually uses.
Bobby Shew seems to like the Humes & Berg MIC-A-MUTE,

which is the same as the basic cup with a rubber ring around the edge
  of the cup to control the seal or space near the bell of the horn.
  This mute also has a soft fuzzy material covering the inside of the
  cup area, the purpose of which is to soften the "wooden" hardness of
  the sound of the regular cup.

I believe this could be the best you can aim for?


What is the difference between the classes ArchiverTar and Archive_Tar?

Question: What is the difference between the classes ArchiverTar and Archive_Tar?
I am mostly interested to understand which one a Drupal module is supposed to use.
Answer: The Archive_Tar class is a very-slightly modified version of the PEAR library Archive_Tar. ArchiverTar can be thought of as a wrapper to that library. However, depending on what your module is trying to achieve, you will probably want to call archiver_get_archiver(), since this is agnostic of the specific archive format (the system module supplies tar and zip, and your module could provide additional formats using hook_archiver_info()).


How to Extract Label of a Field, which is inside FieldCollection?

Question: I have a field collection with the name 'field_stk_fld1'.
Inside this field collection('field_stk_fld1') there is a field with name 'field_fld_stk_ques1'.
I wanted to extract label of the field ('field_fld_stk_ques1'), Any idea on how to get it?
Note: This field ('field_fld_stk_ques1') is used in multiple places and in each place it has its own label associated.
Answer: This should do it:
<code>$entity_type = 'field_collection_item';
$bundle_name = 'field_some_field'; // Field name the collection is attached to
$field_name = 'field_some_other_field'; // Field name within the field collection

$info = field_info_instance($entity_type, $field_name, $bundle_name);

if ($info) {
  $label = $info['label'];
}
</code>


Log message transfer in RabbitMQ

Question: I have implemented RabbitMQ in .Net MVC successfully.Now i need to log each message transfer done  through my RabbitMQ server,is it possible.
Please help me.
Thanks in advance
Answer: If you only need to log failed message details then RabbitMQ already provide a log file with failed message transfer detailes.The Log file located at `C:\Users\UserName\AppData\Roaming\RabbitMQ\log\email@example.com'
Answer: If you want to test the logs for the messages going through Rabbitmq then you can enable the rabbitmq_tracer plugin in rabbitmq and it will log the messages for you. This plugin is good for testing as it shows detailed log for the messages.
Comment: Thanks.I tried rabbitmq_tracer plugin firehose and it is working.but i noticed some performance issue.Is there any solution to solve it?

Log message transfer in RabbitMQ


Contradictory result from adf.test and ndiffs in R

Question: I want to check if a time series is stationary in R.
For ndiffs,
 > ndiffs(GDPlst_t$GDP110000, test="adf")
 [1] 0

the result is 0.
However for adf.test
> adf.test(GDPlst_t$GDP110000)

Augmented Dickey-Fuller Test

data:  GDPlst_t$GDP110000
Dickey-Fuller = -2.2519, Lag order = 3, p-value = 0.4729
alternative hypothesis: stationary

Why do they differ? And what is the detailed ADF test in ndiffs? How are the lag order and type of ADF (3 types) determined?
Comment: @oszkar the result is the same.  `ndiffs(GDPlst_t$GDP110000,max.d = 3)
[1] 0`
Comment: Could you try to set the `max.d` parameter of `ndiffs` to at least 3, and report back what happens? (The default is `max.d = 2`.)
Comment: I have the same error. Did you figure out what caused this problem?
Answer: We need to set lag order k=1 in adf.test to be able to compare with ndiffs.
For example, if ndiffs(x, test='adf') returns 2, it suggests 2 lagged differences are required for a stationary series, which means:

adf.test(x, k=1) => not significant
adf.test(diff(x), k=1) => not significant
adf.test(diff(diff(x)), k=1) => Significant!

Using the example from @Richard Hardy's answer, a function based on adf.test is equivalent to ndiffs.
set.seed(1)
x_random = rnorm(1000) # a random stationary series
x = cumsum(cumsum(cumsum(x_random))) # order 3 integration

# Note that `diff` cancels out `cumsum`
# the following three are the same
x_random[-(1:3)][1:5]
diff(diff(diff(x)))[1:5]
diff(x,differences=3)[1:5]
# 1.5952808  0.3295078 -0.8204684  0.4874291  0.7383247

# using `ndiffs` for the min number of differences required for a stationary series
library(forecast)
ndiffs(x, max.d=10, test="adf", type='trend')
# 0
ndiffs(diff(x,differences=1), max.d=10, test="adf", type='trend')
# 2
ndiffs(diff(x,differences=2), max.d=10, test="adf", type='trend')
# 1
ndiffs(diff(x,differences=3), max.d=10, test="adf", type='trend')
# 0

#an equivalent function based on `adf.test`
library(tseries)
ndiffs_adf.test <- function(x) {
    for (i in 0:10) {
        if (i==0){
            x_ = x
          } else {
            x_ = diff(x, differences=i)
          }
        if (adf.test(x_, k=1)$p.value < 0.05) return(i)
      }
    return(NULL)
  }
ndiffs_adf.test(x)
# 0
ndiffs_adf.test(diff(x,differences=1))
# 2
ndiffs_adf.test(diff(x,differences=2))
# 1
ndiffs_adf.test(diff(x,differences=3))
# 0


Using older SAS drives on percH310 RAID as hot spare

Question: Recently got a dell T320 with a percH310 controller, and I've decided to put the OS on a raid 5 of 3x300GB 15k SAS drives but would like a hot spare, we have a spare 15k 300GB sas drive which has been a hot spare in the old server, and has never been used it's from 2013. My priority here is placed on redundancy and reliability/uptime over performance.
1) Will this have any detrimental/negative effects such as reduce reliability of automatic raid rebuilds, load other disks higher when in use, or any such?
2) Would i be better off setting all 4 up in a raid 10 array or again could this older drive cause me any potentially dangerous circumstances or even just reduce performance of the other drives?
This won't be containing most of the data this will be on a separate SATA raid 10 of 6TB drives.
Comment: Make sure that the disk has equal or larger size than other disks in the array! 300GB may not be the same 300GB...
Answer: Regarding detrimental effects in a RAID5 specific to the drive being older:

Test the drive as a non-spare drive first (perhaps as a single-drive RAID0) and verify that it doesn't fail under workload. Try a tool that allows you to read/write the full capacity of the drive so you don't get hit by existing undiscovered bad sectors later on.
Make sure the older drive is running up to date firmware.
Note comment from Jaroslav Kucera. If the old drive is a few sectors smaller, it may not be able to support the others as a spare. You could probably avert this by making your virtual disk 1GB smaller than the full space available.

If your priority is on "redundancy and reliability/uptime over performance", RAID10 is absolutely a better choice. RAID5 is technically still acceptable by industry standards for that drive capacity/speed, but RAID10 will be safer by far. You should consider testing the drive as mentioned above (test under load, update firmware, etc).
Another option to consider, again in the name of redundancy and reliability/uptime over performance, would be RAID6. The H310 does actually support RAID6 on four spindles. You would see the same usable capacity as you would with RAID10, with the added benefit that ANY two drives could fail without losing data access. This also prevents stripe punctures after a single drive failure and rebuild, which you might run into with RAID10 if the non-failed drive in a mirror has new bad blocks encountered during rebuild.
Comment: @JimNim how would you suggest i best go about conducting this test? And if they are different interface versions, will it just cause a speed issue or potentially a stability issue as well? Thanks again for your advice here :)
Comment: Something as simple as CrystalDiskMark would give you throughput stats worth comparing for single drive performance. I would stick with something like HDTune to check reads and writes across the whole drive though, verifying there are no errors encountered on your SECOND pass of each drive. The first pass might catch some bad blocks, but those should end up re-mapped to new reserve sectors by the 2nd run I believe.
Comment: *If your priority is on "redundancy and reliability/uptime over performance", RAID10 is absolutely a better choice.* To me, that seems to say that RAID5 would outperform RAID10. RAID10 almost certainly will outperform RAID5, giving it better reliability/uptime **and** performance.  The real choice would be between the performance of RAID10 and slightly better availability of RAID6.
Comment: Thanks for the precise answer, so if i were to update the fw on the device, and test with HDTune and both report it's fine, putting this in a raid 10 is going to perform like any normal SAS? My doubts came from the fact we have had SATA 2 and 3 during this drive's life, and i wasn't sure if there was similar differences in terms of SAS?
Comment: @AndrewHenle It was intended as a comparison between "keeping the potentially untrustworthy 4th drive as a spare for RAID5" and "using the 4th drive actively in a RAID10", but you're absolutely right. RAID5 would be inferior in every way unless comparing all four drives active, giving RAID5 a small capacity advantage (and much greater risk to data).
Comment: @user3407675 That's a great point - I did not consider the possibility of different interface generations. You probably ought to test the old drive AND one or more of the new ones to verify there's no major difference in performance capability.


Overriding region theme file for user profile pages

Question: I am on D7 using Omega as a base theme. The
 tag of my theme can be found in the region--content.tpl.php theme file.
But I want to override this theme in one specific situation: on the user profile pages, I don't want the title to be set on region--content.tpl.php. I will take care of the title on the user-profile.tpl.php theme file. So what I want is a theme file that will override the custom default region theme file in the specific situation where user profiles are being viewed. That theme won't have a title set in it.
I have tried creating specific themes called region--content--user.tpl.php and region--content--user-profile.tpl.php, but they didn't override the default region--content.tpl.php theme. Any ideas? Thank you.
Answer: I found solution on this blog http://eureka.ykyuen.info/2012/05/10/drupal-7-customize-region-template-file-for-specific-content-type/
and here is my code to suggest a user profile region.
    function YOURTHEME_alpha_preprocess_region(&$vars) {
      $menu_object = menu_get_object();
      if (isset($menu_object->type) && $vars['region'] == 'content') {
        $vars['theme_hook_suggestions'][] = 'region__content__'.$menu_object->type;
        $vars['attributes_array']['class'][] = 'region-content-'.$menu_object->type;
      }
//theme suggestion for user profile
      elseif ($vars['region'] == 'content' && $vars['elements']["system_main"] && $vars['elements']["system_main"]["#entity_type"] == 'user') {
        $vars['theme_hook_suggestions'][] = 'region__content__userprofile';
        $vars['attributes_array']['class'][] = 'region-content-userprofile';
      }
    }


Double mapped relation in symfony? It is possible?

Question: I have no ideal how to double map entity in symfony.
I have table
Matches
________
id

u_id1 : reference to user

u_id2 : reference to user

status: enum

Now i don't want to create double records per one match.
I want to load user matches where u_id1 = user_id or u_id2 = user_id.
So.. i want make my method in user object inteligent usefully . eg $user->getMatches(); what returns matches where first or second u_id have current user id.
Any idea?
Answer: Maybe you can try something like this.
Define two relations in User entity
class Matches {

        /**
         * @ORM\ManyToOne(targetEntity="User", inversedBy="userOneMatches")
         * @ORM\JoinColumn(name="u_id1", referencedColumnName="id")
         * **/
        protected $u_id1;

        /**
         * @ORM\ManyToOne(targetEntity="User", inversedBy="userTwoMatches")
         * @ORM\JoinColumn(name="u_id2", referencedColumnName="id")
         * **/
        protected $u_id2;
}

and in User entity method getAllMatches(); to combine all matches.
class User {
    /** @ORM\OneToMany(targetEntity="Matches", mappedBy="u_id1" **/
    protected $userOneMatches;

    /** @ORM\OneToMany(targetEntity="Matches", mappedBy="u_id2" **/
    protected $userTwoMatches;

   public function getAllMatches()
   {
    // return $userOneMatches + $userTwoMatches
   }

}


correct rotation and translation matrices

Question: I wrote a C++ program that can calculate the magnetic field $\bar{B}$ generated by a circular coil that is placed in the origin, for a given point $\bar{P}$ in 3D space.
The coil is in the $x$,$y$-surface, with $z=0$.
I want to describe multipoles now so I would have to be able to transform the coordinates of $\bar{P}$ to the coordinate system of a coil that is shifted and rotated $\bar{P}^\prime$.
The coils that are shifted and rotated would have their coordinate systems like so:

the origin of the coil system is at $O^\prime=(R\cos\phi,R\sin\phi,0)$
The $z^\prime$-axis points to the origin of the normal system, is also in the $x$,$y$-surface and makes an angle $\phi$ with the $x$-axis of the normal system.
The $y^\prime$-axis is parallel to the $z$-axis
the $x^\prime$-axis follows (all systems being orthonormal).

Thus all coils (the number of coils is arbitrary) lie on a circle with radius $R$ and their central axis $z$.
My approach has been this so far:

transform $\bar{P}$ to $\bar{P}^\prime$ in the coil's system
calculate $\bar{B}^\prime$ using my program
transform $\bar{B}^\prime$ back to the normal system (only rotation has to be undone, since $\bar{B}$ is a free vector and I only need it's components).

I've been using a transformation matrix $M=R_y(\phi)R_x(\pi/2)$ that looks like this:
$$M=\begin{bmatrix}\cos\phi&0&\sin\phi\\0&1&0\\-\sin\phi&0&\cos\phi\end{bmatrix}\begin{bmatrix}1&0&0\\0&0&-1\\0&1&0\end{bmatrix}=\begin{bmatrix}
\cos\phi&\sin\phi&0\\0&0&-1\\-\sin\phi&\cos\phi&0\end{bmatrix}$$
so $\bar{P}^\prime=M\bar{P}$, after first translating $\bar{P}$ to $\bar{P}_t$ by:
$$\bar{P}_t=\bar{P}-O^\prime$$
And $\bar{B}=M^\prime \bar{B}^\prime$ with $M^\prime=M^T$.
My results are fautly, so what am I doing wrong?
Also, let me know if this question is too concrete to post on a math forum.

Added image for clarity:
The gray circle is where the coil always is in the system that's being used for my C++ program, the dark circle is the coil where it should be.
Comment: Ok I know for sure the matrix $M$ is wrong! Also for inverse transformations one should take the inverse and not the transposed as I have done.

Some help on the correct transformation matrix would be great. Also, should I first rotate or first shift?
Comment: The transpose and the inverse of a rotation matrix are the same thing...
Comment: Hm yes your right.. Wow this really isn't my domain.
Comment: $M$ is definitely not a rotation-matrix. How did you arrive at it?
Comment: I tried two different methods so far: 1. multiply rotation matrices $R_x$, $R_y$ and $R_z$ and 2. put the components of the $a^\prime_i$, calculated in $a_i$ in a matrix. 3. mess around with a graphical program, I think that's were I got this. Was kind of busy so might have messed things up.
Comment: updated, with a more correct $M$... still not working though.
Comment: Have you checked at that your matrix has determinant 1? If the determinant is negative the transformation reverses orientation, which I guess is not what you want. (Note: this is only meant as a sanity check.  I'm saying this because the first matrix you put up was singular.)
Comment: Yes, the determinant is $+1$ now.
Answer: I don't understand how you arrived at your rotation matrix, so I'll just go by your description of the transformed system and the image, which I think I understand.
If we choose $\phi=0$, $O'$ lies on the $x$-axis, so the $z'$-axis should be the negative $x$-axis, the $y'$-axis should be the $z$-axis, and the $x'$-axis should correspondingly be the negative $y$-axis. That corresponds to the transformation matrix
$$\left(\begin{array}{ccc}0&-1&0\\0&0&1\\-1&0&0\end{array}\right)\;.$$
This is not what your expression for the rotation matrix yields for $\phi=0$. Since the $y'$-axis always points along the $z$-axis and only the $x'$-axis and the $z'$-axis are rotated into each other if we change $\phi$, we can immediately infer the general form of the rotation matrix as
$$\left(\begin{array}{ccc}\sin\phi&-\cos\phi&0\\0&0&1\\-\cos\phi&-\sin\phi&0\end{array}\right)\;,$$
where only the sign of the sine was still to be determined and can be fixed by considering $\phi=\pi/2$.
Comment: Okay, I've been trying to fix my program, recalculating and recalculating.. Always coming to this result. Something seems wrong though, my program keeps given faulty results..


mysql two tables with the same structure - want to get one common field ordered by via a union

Question: I have two tables that have the same structure, I need a query to order by from both tables at the same time so that the array fetched with php grabs the order correctly out of the two tables selected with a single query at the same time.
avoiding selection of each table separately, storing on php arrays and then sorting.
Answer: <code>select * from
(select * from tbl1
union all
select * from tbl2
) a
order by col1
</code>
Answer: According to the documentation, it should be just like you would think. Here is an example from the documentation:
<code>(SELECT a FROM t1 WHERE a=10 AND B=1)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2)
ORDER BY a LIMIT 10;
</code>


Javascript change variable using buttons

Question: I am trying to make a button open up another window using jquery.
The button should be able to open the window. Then the same button should be used to close the window afterwards. The problem I seem to be having appears that my variables are not being set after the button opens the window. I am really new to javascript and jquery, so I'm not sure if I did something wrong.

       <button>Start Animation</button>

http://jsfiddle.net/tqpTE/
Comment: You should chain all the animation calls, or put `$("div")` in a variable.
Comment: @Krycke I'm not sure what you mean. Can you explain a little more for me?
Comment: When you use `$("div")` on every line, jQuery will search for all div elements three times. By using `var divs = $("div");` you can use that variable on the other lines, and just have one lookup, or use chaining like `$("div").doSomthing().doSomethingElse();`
Comment: @Krycke Ah, gotcha. Thanks for the tip.
Answer: jsFiddle DEMO
var FileEdit = 0;

$("button").on('click', function(){

    // You only need one on('click') function
    // Test for FileEdit here & do whatever you need

    if (FileEdit === 0) {

        // Also having those 3 animations right in a row won't make them
        // go one - after - another. You need to use callback functions
        // to start the next animation after the previous one finished.

        $("div").animate({opacity:0.4},"fast", //callback1
            function () { $(this).animate({height:300,width:300},"slow", //callback2
                function () { $("div").animate({opacity:1},"slow"); }
            )}
        );
        FileEdit = 1;
    }

    else {
         $("div").animate({height:000,width:000},"slow");
         FileEdit = 0;
    }
});

More info on .animate() callback functions
Answer: Your condition needs to run on each click - not just once, on DOM ready, as currently. Also note your code can quite drastically be reduced to something like this:
var fileEdit = 0;
$(function(){
    $("button").on('click', function() {
        var anim_data = !fileEdit ? {width: 300, height: 300} : {width: 0, height: 0};
        $("div").animate(anim_data, 'slow');
        fileEdit = !fileEdit ? 1 : 0;
    });
});

A few notes:
1) You seemed to be animating the opacity twice (once to .4, and, simultaneously, to 1) so, for the purpose of this demo, I removed reference to it entirely.
2) Unless you need to animate to partial opacity (rather than 0 or 1) it's easier to use jQuery's fadeIn() and fadeOut() methods.
3) Setting width: 000 is the same as width: 0.
4) Avoid capital letters in var names - capital letters are used normally to denote constructor functions.
5) Be careful when testing against 0 and 1 values with double equals as you will get some surprising due to the concept of truthy/falsy values. In unsure, it's always safest to test with === not ==.
6) Whilst click is fine, jQuery 1.7 introduced a tidy-up of its messy events API and so you can now just use on() and off(). click() and others are just aliases that, behind the scenes, delegate to on().


Create new array from existing array with specifc node values

Question: I have following array:
[
  {
    fileName: "test.pdf",
    fileUrl: "https://test-url1.com/test.pdf",
    isDeleted: true
  },
  {
    fileName: "test.pdf",
    fileUrl: "https://test-url1.com/test.pdf",
    isDeleted: true
  }
]

Now I need to create new array from this array which will contain only fileUrl data.
So that new array will have only fileUrl node and all it's links.
Should I use map OR filter method, or any other suggestion for this.
Thanks
Comment: please add a code snippet instead of code screenshots
Answer: You should use map for this.
const urlArray = array.map((item: any) => item.fileUrl);

// [ "https://test-url1.com/test.pdf", "https://test-url1.com/test.pdf"]

The rule of thumb is if you want to change the structure of the array you use map, if you want to get a subset of the array you use filter.
Comment: I tried it but I am getting this error : 'item' is of type 'unknown'.ts(18046)


Replacing "\" value from String in iOS Swift 4

Question: I have String shown below and I want to replace "\" this with "" but Xcode doesn't allow me to do so. It gives Error like "Unterminated string literal"
let jsonStr = "[{\"isSelected\":true,\"languageProficiencies\":[{\"isSelected\":true,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"English\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Malay\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Chinese\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Tamil\"}]"

Code for replacing "\" to "" is:
let newString = jsonStr.replacingOccurrences(of: "\", with: "", options: .literal, range: nil)

Comment: I suppose you converted json to string. What do you want to do with that string ? Wouldnt it make sense to use JSONSerialization or JSONDecoder to decode the json and actually use it ?
Comment: what is final o/p you want? remove "\" or `Json` object?
Comment: Yes I want to convert it into JSON
Comment: JSON o/p @PratikPrajapati
Comment: `let jsonData = jsonStr.data(using: .utf8); let jsonArray = try! JSONSerialization.jsonObject(with: jsonData!, options: []); print("jsonArray:\n \(jsonArray)")`?
Answer: let jsonStr = "[{\"isSelected\":true,\"languageProficiencies\":[{\"isSelected\":true,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"English\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Malay\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Chinese\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Tamil\"}]"

These \ are to say: Do not interpret the next ", they escape it. If you don't, since they are used to delimit the start/end of the String, it's an escape sequence: \".
One of the most known used for it is the \n, if you don't use the \, it will read n (the letter), not a new line.
Well, for the double quotes, it's the same: Do not interpret as a "code" value to delimit the start/end of the String.
You might want to read this.
If you do print("jsonStr:\n \(jsonStr)"), you'll have in console:
$>jsonStr:
[{"isSelected":true,"languageProficiencies":[{"isSelected":true,"name":"Advance"},{"isSelected":false,"name":"Proficient"},{"isSelected":false,"name":"Basic"},{"isSelected":false,"name":"Below Basic"}],"name":"English"},{"isSelected":false,"languageProficiencies":[{"isSelected":false,"name":"Advance"},{"isSelected":false,"name":"Proficient"},{"isSelected":false,"name":"Basic"},{"isSelected":false,"name":"Below Basic"}],"name":"Malay"},{"isSelected":false,"languageProficiencies":[{"isSelected":false,"name":"Advance"},{"isSelected":false,"name":"Proficient"},{"isSelected":false,"name":"Basic"},{"isSelected":false,"name":"Below Basic"}],"name":"Chinese"},{"isSelected":false,"languageProficiencies":[{"isSelected":false,"name":"Advance"},{"isSelected":false,"name":"Proficient"},{"isSelected":false,"name":"Basic"},{"isSelected":false,"name":"Below Basic"}],"name":"Tamil"}]

No \ seen.
For the rest, with bad unwrapping, but more for the logic.
let jsonData = jsonStr.data(using: .utf8)
let jsonArray = try! JSONSerialization.jsonObject(with: jsonData!, options: [])
print("jsonArray:\n \(jsonArray)")

Comment: Perfect!! Works for Me!
Answer: You need to convert it into JSON.
let string = "[{\"isSelected\":true,\"languageProficiencies\":[{\"isSelected\":true,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"English\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Malay\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Chinese\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Tamil\"}]"
let data = string.data(using: .utf8)!
do {
    if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String, Any>]
    {
          print(jsonArray)
    } else {
        print("json can not be formed !!")
    }
} catch {
   print(error)
}

If you want to replace "/" then...
print(jsonStr.replacingOccurrences(of: "\\", with: ""))

Comment: I want to replace "\" this one not "/"
Answer: i have same issue once try this
extension Data
{
func dataToJSON() -> Any? {
    do {
        return try JSONSerialization.jsonObject(with: self, options: [])
    } catch let myJSONError {
        print(myJSONError)
    }
    return nil
}
}

extension String
{
    func decodeUrl() -> String
    {
        return self.removingPercentEncoding!
    }
}

Usage :
let yourJsonString = "".decodeUrl()
        if let data = yourJsonString.data(using: .utf8) {
            if let json = data.dataToJSON() {
                print(json)
            }
        }

Answer: Please use the "\\" example like below.
let jsonStr = "[{\"isSelected\":true,\"languageProficiencies\":[{\"isSelected\":true,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"English\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Malay\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Chinese\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Tamil\"}]"
let convertedStr = jsonStr.replacingOccurrences(of: "\\", with: "", options: .literal, range: nil)
print(convertedStr)


Starting with administering a linux box

Question: I'm rather new to this, and I'd like to play with administering a linux box.
Things I need to know how to do:

Setup subdomains
Setup FTP accounts
Setup full domains / add domains
MySQL setup / install / management
LAMP setup / install / management

This is probably going on a CentOS distro. I'd like links or a break down on how I can learn to do this. I am comfortable with a command line, but I'm trying to move from shared hosting to a VPS and would like to have some idea on how deep the water is before I do.
Comment: Well... install VirtualBox, download Centos, see the docs listed below, and have at it. Also take a look a programs like Puppet/Chef/etc. if you want to automate some of that administration.
Answer: RUTE
RHEL docs
That'll get you most of the way there. Make sure you find a box that you don't mind nuking and reinstalling on, because the best way of getting a handle on it is destroying it a few times.
Comment: The worst possible thing that can happen when learning is that everything goes according to plan.
Answer: Lots of good stuff at howtoforge as well.
LINK: HERE
Comment: Be careful with HTF though. Some of their instructions are... suspect, and without the proper knowledge already in place it's hard to know what to avoid doing.
Comment: @Ignacio, very true. I generally use them as a template for process rather than as a step-by-step tutorial.

Starting with administering a linux box


RecylerView Horizontal como WhatsApp

Question: Gostaria da ajuda de vocês de como fazer este layout da parte "Mídia" em um determinado Contato do WhatsApp. Seria este CardView inteiro chamado de "Mídia".

Seria quase exatamente desse mesmo jeito, não tenho dúvida quanto aos adapters, apenas dúvida em relação ao xml do layout. As imagens também seriam todas de mesmo tamanho neste quadrado.
Answer: Quando você cria um RecyclerView tem que lhe atribuir um LayoutManager. Neste  caso(lista horizontal) atribua um LinearLayoutManager especificando LinearLayoutManager.HORIZONTAL no construtor:
LinearLayoutManager manager = new LinearLayoutManager(this,
                                                      LinearLayoutManager.HORIZONTAL, false);

RecyclerView midiaList = (RecyclerView) findViewById(R.id.a_sua_recycler_view);
midiaList.setLayoutManager(manager);

Comment: E como os itens do RecyclerView irão ficar naquele tamanho específico? Todos quadrados exatamente como da imagem?
Comment: Os quadrados podem ser obtidos usando uma CardView como pai das tuas rows
Comment: Me refiro aos quadrados dentro de mídia e não os externos que são CardViews. Os quadrados são as imagens exibidas em lista dentro de um recycler view horizontal.
Comment: Julgo que isso depende do layout que define cada linha(coluna neste caso) do RecyclerView.
Comment: Das duas uma. Ou sao simples imageviews com cantos arredondados, ou entao é outra recyclerview mas com orientaçao vertical
Comment: @PedroOliveira não olhe para os cardviews, olhe apenas para o que está debaixo do texto Mídia.
Comment: exatamente isto que o @ramaral falou que também quero saber.
Comment: Como pode ser vertical se as imagens são exibidas na horizontal?
Comment: @ramaral testei o que você colocou na resposta  deu certo. Também consegui definir as imagens que nem no WhatsApp, escolhi um pouco maior para cada item da lista que foi 96dp. O problema agora foi que o recyclerview não fica "wrap_content" mesmo definindo sua altura assim. Ele toma todo os espaço restante como se estivesse "match_parent". Sabe o que pode ser?
Comment: Lucas, o melhor é você criar uma nova pergunta onde deve postar o xml dessa parte e se possível uma imagem.

RecylerView Horizontal como WhatsApp


Is that possible to call to external PHP script from Ajax?

Question: I'm trying to call to external PHP script using Ajax like this:
$(function() {
    $.ajax({'url': 'http://stokes.chop.edu/web/zscore/result.php',
            'type': 'POST',
            'success': function(response, textStatus, XMLHttpRequest) {
                alert('[' + response + ']');
            },
            'error': function(XMLHttpRequest, textStatus, errorThrown) {
                alert('Error');
            }
    });
});

The result is: [] (i.e. success function is called!),
but I see the following error in HTTPFOX plugin for FireFox:
Error loading content (NS_ERROR_DOCUMENT_NOT_CACHED)
What's wrong with my code ?
Comment: Lol, this would be such a gaping security hole if browsers allowed cross domain requests like that
Comment: It looks like a HTTPFox bug: http://code.google.com/p/httpfox/issues/detail?id=20
Answer: You cannot load contents from pages that does not have the same domain name as the one from which the ajax request is called from. This is a well known security feature call the Same Origin Policy.
Comment: There are special mechanisms, such as [JSONP](http://en.wikipedia.org/wiki/JSON#JSONP), but they require server support.


Can I safely disable SSH-1 access from my server?

Question: SSH-2 has been out for almost a decade. I know at least that all computers that currently connect to my server use the updated version 2 protocol. With that in mind, is there any benefit (security or otherwise) from disabling or blocking SSH-1?
Can I safely disable any access via the SSH protocol version 1 from the server, still allowing SSH clients using version 2 to access the server, without breaking anything?
(And a bonus question if anyone knows where to find the usage statistics) Even if the server is later used by more people, how likely is it that anyone is actually still using the SSH-1 protocol?
Comment: What kind of ancient stuff have you got? Everything shipped in the last decade or so already has SSH1 disabled by default.
Comment: @MichaelHampton I'm running Ubuntu 15.04 (which uses OpenSSH 6.7p1), and the reason I ask is there is still a section in the configs with options like `ServerKeyBits` which is only used for SSH-1 key exchanges. Is there any way to test if SSH-1 is disabled or not?
Answer: Yes there is.
<code>Protocol
Specifies the protocol versions
sshd(8) supports. The possible
values are '1' and '2'. Multiple
versions must be comma-separated.
The default is '2'. Note that the order
of the protocol list does not indicate
preference, because the client selects
among multiple protocol versions
offered by the server. Specifying "2,1"
is identical to "1,2".
</code>
See http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man5/sshd_config.5?query=sshd%5fconfig&sec=5 for more configuration options.
Using SSH-1 is not recommended so you should force your users to use SSH-2 for your and your users security.
99,9% of all applications use SSH-2 so you won't break anything.


How can I compare this 2 value then show to FirebaseRecyclerAdapter?

Question: I want to connect the user id with the same key in Users, then show the key to FirebaseRecyclerAdapter. I get the key in Friend child already but don't know how to match this to Users.

And my code:
    mFriendList = FirebaseDatabase.getInstance().getReference().child("Friends").child(current_id);

    mFriendDatabase = FirebaseDatabase.getInstance().getReference().child("Users");

    mFriendList.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {

                String sd = snapshot.getKey(); //key from Friends

                final FirebaseRecyclerAdapter<Users_Friends, UsersFriendViewHolder> firebaseRecyclerAdapter =
                        new FirebaseRecyclerAdapter<Users_Friends, UsersFriendViewHolder>(
                                Users_Friends.class,
                                R.layout.users_single_friend_layout,
                                UsersFriendViewHolder.class,
                                filter
                        ) {
                            @Override
                            protected void populateViewHolder(UsersFriendViewHolder viewHolder, Users_Friends users, int position) {
                                viewHolder.setDisplayName(users.getName());
                                viewHolder.setStatusUsers(users.getStatus());
                                viewHolder.setUserImage(users.getImage(), getContext().getApplicationContext());

                                final String user_id = getRef(position).getKey();

                                viewHolder.mView.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent profileIntent = new Intent(getActivity(), ProfileActivity.class);
                                        profileIntent.putExtra("user_id", user_id);
                                        startActivity(profileIntent);
                                    }

                                });
                            }
                        };
                mReqList.setAdapter(firebaseRecyclerAdapter);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Answer: You only need to use exists() method directly on the dataSnapshot object like this:
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if(dataSnapshot.child(current_id).exists()) {
            Log.d("TAG", "User exists");
        } else {
            Log.d("TAG", "User does not exist");
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
mFriendDatabase.addListenerForSingleValueEvent(eventListener);

Comment: In the exact place where you need to do the check.
Comment: oh I fotgot this... thank you for your answer. But because of my logic so this problem is so misunderstanding for everyone.


Fetch result of query twice

Question: I faced with problem while fetching query results, my code:
$result = $query->execute();
$array1 = $result->fetchAllKeyed(1, 0);
$array2 = $result->fetchAllKeyed(2, 0);

But the $array2 is empty, so fetchAllKeyed cut all values from $result.
I'm already tried to use the following:
$query2 = clone $query;
$result = $query->execute();
$result2 = $query2->execute();
$array1 = $result->fetchAllKeyed(1, 0);
$array2 = $result2->fetchAllKeyed(2, 0);

It's works, but I don't want do two queries instead of one.
So, how can I do two (or more) different "fetch" from one result?
Comment: Did try duplicating the `$result` directly instead of recreating the query? `$result2 = $result` and then fetching the keys?
Comment: Doesn't works too.

If I use `$result2 = $result;` - I get empty fetch result.

If I use `$result2 = clone $result;` - the same.
Comment: Hmm, then I guess you'll have to use fetchAssoc() wich gets you an array of objects and then use a foreach loop to generate the 2 sub arrays. Seems like the only solution.
Answer: Since fetchAllKeyed() internally uses foreach loop to sort the data, the answer given by  Suranga Panagamuwa Gamage to use fetchAssoc() and then a loop seems the most efficient way.

Fetch result of query twice


Weak-Strong, Lipschitz and uniform continuity

Question: In our lecture of stationary differential equations with the theory of monotone operators we introduced the concept of weak-strong continuity with sequences:

Defintion (weak-strong continuity)
  Let $V$ be a reflexive Banach space.
  A (not not necessarily linear) operator $A: V \to V^*$ ($V^*$ is the continuous dual space) is called weak-strong continuous if
  $$
v_n \rightharpoonup v \text{ in } V
\implies A v_n \to Av \text{ in } V^*
$$
  for all sequences $(v_n)_{n \in \mathbb{N}} \subset V$.

This is obviously a stronger requirement than continuity.
Since uniform and Lipschitz continuity are also stronger than continuity I wondered if there is a connection between them (as in: one implies the other under certain conditions) as i.e. $$\textrm{Lipschitz } \implies \textrm{ uniform } \implies \textrm{ continuous}$$on compact intervals in $\mathbb{R}$.
Answer: I think there is no connection between this properties in general.
First, let $A=Id$. This is a nice Lipschitz continuous and  uniformly continuous but not weak-strong continuous.
Second, for $V=\mathbb R$, $A(x)=x^2$ is weak-strong continuous but neither Lipschitz nor uniformly continuous.


Como fazer uma função utilizar quantos argumentos forem fornecidos a ela

Question: Há alguma forma de fazer uma função utilizar múltiplos argumentos sem a declaração deles? Por exemplo:
#import<stdio.h>
#import"rlutil.h" //para as cores

void a(color,string){
    setColor(color);
    printf("%s",string);
    setColor(15); //Seleciona a cor Branca
}

Eu queria saber se ha um jeito de colocar
a(1,"Este",2,"E",8,"Um",4,"Exemplo");

sem declarar cor1, string1, cor2, string2, etc.
e que mostrar o resultado
Este E Um Exemplo

em que Este fique azul(1), E fique verde(2), Um fique em cinza(8) e Exemplo fique em vermelho(4)
Answer: Pode criar isto:
void a(int tamanho, ...) {
    va_list valist;
    va_start(valist, tamanho);
    for (int i = 0; i < tamanho; i += 2) {
        setColor(va_arg(valist, int));
        printf("%s", va_arg(valist, char *));
        setColor(15); //Seleciona a cor Branca
    }
    va_end(valist);
}

Coloquei no GitHub para referência futura.
Não me lembro se é exatamente isto e não posso testar agora, provavelmente tem uns erros, acho que já vi um :), mas a ideia é esta.
Referência.
Answer: Para fazer uma função utilizar quantos argumentos forem fornecidos a ela em C é necessário utilizar "..." na hora de declarar os parâmetros.
No caso do exemplo que você apresentou eu sugiro preservar a função a() como está:
void a(color c, string s) {
    setColor(c);
    printf("%s ",s);
    setColor(15); // o número 15 seleciona a cor branca
}

E utilizar uma nova função func() que receberia a lista de parâmetros de tamanho variável e chamaria a() a cada par (color,string). Ficaria assim:
void func(int num, ...) {  // o inteiro é obrigatório, os três pontinhos
                           // indicam que a quantidade de parâmetros será
                           // determinada em tempo de execução
    va_list valist; // estrutura que irá receber a lista de argumentos
    va_start(valist, num);  // macro que inicializa a lista de argumentos
    int i, cor;
    char * palavra;

    for ( i= 0; i < num; i=i+2 ) {
        cor = va_arg(valist, int);
        palavra = va_arg(valist, char *);
        a (cor, palavra);
    }

    va_end(valist); // limpa a memória reservada para valist
}

No caso deste exemplo sua chamada ficaria assim:
func(8, 1,"Este",2,"É",8,"Um",4,"Exemplo");

reference (em inglês).


How to fix replytocom & comment_error_msg in my website

Question: I need your solution for my web. Sorry for my bad english.
I have a website with wordpress cms. my wp-comments-post.php is working when my web in shared hosted but after i moving my web in vps, reply & comment error not working in my web. My vps using centos 6.9 x 64, php 5.6. This is my wp-comments-post.php
<?php
/**
 * Handles Comment Post to WordPress and prevents duplicate comment posting.
 *
 * @package WordPress
 */

if ( 'POST' != $_SERVER['REQUEST_METHOD'] ) {
    header('Allow: POST');
    header('HTTP/1.1 405 Method Not Allowed');
    header('Content-Type: text/plain');
    exit;
}

/** Sets up the WordPress Environment. */
require( dirname(__FILE__) . '/wp-load.php' );

nocache_headers();

$comment_post_ID = isset($_POST['comment_post_ID']) ? (int) $_POST['comment_post_ID'] : 0;

$post = get_post($comment_post_ID);

if ( empty($post->comment_status) ) {
    do_action('comment_id_not_found', $comment_post_ID);
    exit;
}

// get_post_status() will get the parent status for attachments.
$status = get_post_status($post);

$status_obj = get_post_status_object($status);

if ( !comments_open($comment_post_ID) ) {
    do_action('comment_closed', $comment_post_ID);
    wp_die( __('My error masssage.......') );
} elseif ( 'trash' == $status ) {
    do_action('comment_on_trash', $comment_post_ID);
    exit;
} elseif ( !$status_obj->public && !$status_obj->private ) {
    do_action('comment_on_draft', $comment_post_ID);
    exit;
} elseif ( post_password_required($comment_post_ID) ) {
    do_action('comment_on_password_protected', $comment_post_ID);
    exit;
} else {
    do_action('pre_comment_on_post', $comment_post_ID);
}

$comment_author       = ( isset($_POST['author']) )  ? trim(strip_tags($_POST['author'])) : null;
$comment_author_email = ( isset($_POST['email']) )   ? trim($_POST['email']) : null;
$comment_author_url   = ( isset($_POST['url']) )     ? trim($_POST['url']) : null;
$comment_content      = ( isset($_POST['comment']) ) ? trim($_POST['comment']) : null;

// If the user is logged in
$user = wp_get_current_user();
if ( $user->ID ) {
    if ( empty( $user->display_name ) )
        $user->display_name=$user->user_login;
    $comment_author       = $wpdb->escape($user->display_name);
    $comment_author_email = $wpdb->escape($user->user_email);
    $comment_author_url   = $wpdb->escape($user->user_url);
    if ( current_user_can('unfiltered_html') ) {
        if ( wp_create_nonce('unfiltered-html-comment_' . $comment_post_ID) != $_POST['_wp_unfiltered_html_comment'] ) {
            kses_remove_filters(); // start with a clean slate
            kses_init_filters(); // set up the filters
        }
    }
} else {
    if ( get_option('comment_registration') || 'private' == $status )
        wp_die( __('My error masssage.......') );
}

$comment_type = '';

//MOD Customize comment error message.
//Need to add the following code to your comments.php file wherever you want error message to display:
/*
  <?php if ($_GET['comment_error_msg']) { // Display Comment Error Message ?>

Comment <?php echo $_GET['comment_error_msg']; ?>
Note: If your comment text disappeared, try clicking your browser BACK button.

  <?php } ?>
*/
$comment_error_true = false; //MOD new code
if ( '' == $comment_content ) {
    $comment_error_msg = __('   My error masssage.......'); //MOD new code
    $comment_error_true = true; //MOD new code
    //wp_die( __('My error masssage.......') ); //original
}

if ( get_option('require_name_email') && !$user->ID ) {
    if ( 6 > strlen($comment_author_email) || '' == $comment_author ) {
        $comment_error_msg = __('   My error masssage.......'); //MOD new code
        $comment_error_true = true; //MOD new code
        //wp_die( __('My error masssage.......') ); //original
    } elseif ( !is_email($comment_author_email)) {
        $comment_error_msg = __('   My error masssage.......'); //MOD new code
        $comment_error_true = true; //MOD new code
        //wp_die( __('My error masssage.......') ); //original
    }
}

//MOD Original code is now in the ELSE statement
if (true == $comment_error_true) { //MOD new code

    //Set this to false to use default wp_die page
    $use_comment_custom_error_page = true; //MOD new code

    if ($use_comment_custom_error_page) { //MOD new code
        $location = get_permalink() . '?comment_error_msg=' . urlencode($comment_error_msg); //MOD new code
        if ( !$user->ID ) { //MOD new code
            $comment_cookie_lifetime = apply_filters('comment_cookie_lifetime', 30000000); //MOD new code
            setcookie('comment_author_' . COOKIEHASH, $comment_author, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN); //MOD new code
            setcookie('comment_author_email_' . COOKIEHASH, $comment_author_email, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN); //MOD new code
            setcookie('comment_author_url_' . COOKIEHASH, esc_url($comment_author_url), time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN); //MOD new code
            //setcookie('comment_content_' . COOKIEHASH, $comment_content, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN); //MOD new code //TO DO: Figure out how to get Comment field to re-appear and not be deleted.
        } //MOD new code
    } else { //MOD new code
        wp_die($comment_error_msg); //MOD new code //This performs the default comment error page action
    } //MOD new code
} else { //MOD new code

    //Original unmodified code STARTS here
    $comment_parent = isset($_POST['comment_parent']) ? absint($_POST['comment_parent']) : 0;

    $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_ID');

    $comment_id = wp_new_comment( $commentdata );

    $comment = get_comment($comment_id);
    if ( !$user->ID ) {
        $comment_cookie_lifetime = apply_filters('comment_cookie_lifetime', 30000000);
        setcookie('comment_author_' . COOKIEHASH, $comment->comment_author, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN);
        setcookie('comment_author_email_' . COOKIEHASH, $comment->comment_author_email, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN);
        setcookie('comment_author_url_' . COOKIEHASH, esc_url($comment->comment_author_url), time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN);
    }

    $location = empty($_POST['redirect_to']) ? get_comment_link($comment_id) : $_POST['redirect_to'] . '#comment-' . $comment_id;
    $location = apply_filters('comment_post_redirect', $location, $comment);
    //Original unmodified code ENDS here

} //MOD new code

wp_redirect($location);
exit;
?>

Please help me.... Thanks
Answer: I have seen this issue on my own WordPress site. You can solve this issue simply by delete the following code from your wp-comments-post.php page.
if ( 'POST' != $_SERVER['REQUEST_METHOD'] ) {
    header('Allow: POST');
    header('HTTP/1.1 405 Method Not Allowed');
    header('Content-Type: text/plain');
    exit;
}

I hope it works...


Optimization equivalence

Question: Can someone help me with the step by step demonstration of the following equivalence used in SVM:
$$maximize: m = \frac{1} {\|w\|} \equiv minimize: m =\frac{1} {2}\|w\|^2 $$
I would be most grateful if related theorems are included or mentioned.
Answer: The argument goes like this.
1) the value that maximizes $1/||w||$ is the value that minimizes $||w||$
2) the value that minimizes $||w||$ also minimizes $||w||^2$,
3) which also minimizes $1/2 ||w||^2$
Comment: As far as theorems are concerned, you can justify each of these statements by checking derivatives (Fermat's theorem) and using the chain rule
Answer: I presume that you are referring to the maximising/minimising values over some range $w \in \mathscr{W}$.  The reason this equivalence holds is that you are using a strictly decreasing transformation.  You therefore have:
$$\begin{aligned}
\underset{w \in \mathscr{W}}{\text{arg max }} \frac{1}{||w||}
&= \Big\{ w \in \mathscr{W} \Big| (\forall w'): \frac{1}{||w||} \geqslant \frac{1}{||w'||} \Big\} \\[6pt]
&= \Big\{ w \in \mathscr{W} \Big| (\forall w'): ||w'|| \geqslant ||w|| \Big\} \\[6pt]
&= \Big\{ w \in \mathscr{W} \Big| (\forall w'): \frac{1}{2} ||w'||^2 \geqslant  \frac{1}{2} ||w||^2 \Big\} \\[6pt]
&= \Big\{ w \in \mathscr{W} \Big| (\forall w'): \frac{1}{2} ||w||^2 \leqslant  \frac{1}{2} ||wl||^2 \Big\} \\[6pt]
&= \underset{w \in \mathscr{W}}{\text{arg min }} \frac{1}{2} ||w||^2. \\[6pt]
\end{aligned}$$

Optimization equivalence


Drop column from tuple list in Pandas dataframe

Question: This is my tuple I guess
df = [(1.8799187420058687, 1), (1.5963945918878317, 2)]

The type of df shows up as this
print(type(df))
<type 'list'>

My goal is to remove the second variable column displayed as 1 and 2
This is how I came up to the result (if that can help)
df = df.groupby('CBF_01').mean()
df = list(zip(df,df.index))

Expected output
df = (1.8799187420058687,1.5963945918878317)

Answer: loop through each tuple, save the first value in a list and convert it to tuple.
new_df = tuple([x[0] for x in df])

output: (1.8799187420058687, 1.5963945918878317)

Comment: `tuple([x[0] for x in df])` .... I don't think you need to the `list(x)` you can access the first element of a tuple with indexing.
Comment: @ScottBoston you are right, I dint know that, Thank you!
Answer: Depending on how big the dataset is, you can loop through the dataframe and drop those, for example:
for i in range(len(df)-1):
    df['CBF_01'][i] = df['CBF_01'][i][0]

Comment: I don't understand your answer


How do I modify a template file to show elements side-by-side?

Question: I am working on views with embedded filters and my resultant view fields have the following code.
{ % set index = 0 %}

      {% for key, field in fields %}

        {% if index == 0 or index == 5 %}

        {% endif %}

        {% if field.wrapper_element %}
          <{{ field.wrapper_element }}{{ field.wrapper_attributes }}>
        {% endif %}

        {% if field.label %}
          {% if field.label_element %}
            <{{ field.label_element }}{{ field.label_attributes }}>{{ field.label }}{{ field.label_suffix }}</{{ field.label_element }}>
          {% else %}
            {{ field.label }}{{ field.label_suffix }}
          {% endif %}
        {% endif %}

          {% if field.element_type %}
            <{{ field.element_type }}{{ field.element_attributes }}>{{ field.content }}</{{ field.element_type }}>
          {% else %}
            {{ field.content }}
          {% endif %}

        {% if index == 4 %}

              <button class="button js-form-submit form-submit btn-info btn" type="button" value="Btn1" name="">Btn1</button>

              <button class="button js-form-submit form-submit btn-info btn" type="button" OnClick = "window.print();" value="PRINT" name="">PRINT</button>

        {% endif %}

        {% if field.wrapper_element %}
          </{{ field.wrapper_element }}>
        {% endif %}

        {% if index + 1 == fields | length %}
          Click to go to next page
        {% endif %}

        {% if index == 4 or index + 1 == fields | length  %}

        {% endif %}

        {% set index = index + 1 %}

      {% endfor %}

In this setup the label is showing above the text. Is there a way to show them on the same line?
Comment: Instead of relying on Bootstrap markup have you tried it with your own CSS already?
Answer: It's likely because field.label_element contains a
 tag.
You should instead use a  tag.
{{ field.label }}{{ field.label_suffix }}

  {{ field.content }}

You can also add a
 tag after the closing  tag to show all the label/content sets on separate lines.
If this doesn't work, you can add a
 tag around the two elements and add some simple Flexbox styling in the CSS to get the desired result.


How to prevent entering value in table when primary is used on other table?

Question: I have to construct and populate a supertype-subtype relationship, but I cannot get it to work the way it is supposed to be. Basically PERSON table is the supertype of table STUDENT and TEACHER(subtypes). But a person can be either a student or a teacher.
Attributes:
PERSON(p_id, name, dob)
STUDENT (s_id, p_id, grade)
TEACHER(t_id, p_id, tel)

Both student and teacher should have names and DOB's along with the p_id as a foreign key, but if it exist on one table it shouldn't be on the other
CREATE TABLE PERSON ( -- SUPERTYPE
    p_id NUMBER(2) CONSTRAINT c1 PRIMARY KEY,
    name CHAR(15),
    dob DATE
);

CREATE TABLE STUDENT ( -- SUBTYPE
    s_id NUMBER(2) CONSTRAINT c2 PRIMARY KEY,
    p_id_fk,
    grade CHAR(1),
    FOREIGN KEY (p_id_fk) REFERENCING PERSON (p_id)
);

CREATE TABLE TEACHER( -- SUBTYPE
    t_id NUMBER(4) CONSTRAINT c3 PRIMARY KEY,
    p_id_fk,
    tel CHAR(8),
    FOREIGN KEY (p_id_fk) REFERENCING PERSON (p_id)
);

INSERT INTO PERSON VALUES (11, 'John', to_date('12/12/12', 'dd/mm/yy'));
INSERT INTO PERSON VALUES (22, 'Maria', to_date('01/01/01', 'dd/mm/yy'));
INSERT INTO PERSON VALUES (33, 'Philip', to_date('02/02/02', 'dd/mm/yy'));

INSERT INTO STUDENT VALUES (98, 11, 'A');

INSERT INTO TEACHER VALUES (1234, 11, 14809510);

How to prevent Person 11 (John) from existing in both tables?
Comment: good call, i didn't know there is difference between sql-server and sql*plus.
Comment: The terminology you're using suggests you might be expected to be using objects rather than normal tables. It might be helpful to include (in the question) exactly what you were asked to do - and why you think what you have is wrong.
Comment: This looks like Oracle SQL. Are you *really* using sql-server (where this script would fail)?
Comment: I forgot to put VALUES in the case above, but now it has been corrected. definetely works for me, but the problem still remains. [SQL-SERVER SCREENSHOT](https://ibb.co/D5MN1ZV)
Comment: There is no `to_date()` in sql-server. Your screenshot looks like Oracle's `sql*plus` command line utility. I am tagging your question `oracle`, feel free to rollback.
Comment: I  know it wasn't your question.  That's why i opened with "Just as a side observation".  It may not be relevant to your immediate question, but it is very relevant to your writing high-quality code, going forward.
Answer: Use a materialized view with an appropriate constraint to check complex requirements such as this.
For example, let's create the tables and a materialized view, add data to the tables, and refresh the MV:
CREATE TABLE PERSON ( -- SUPERTYPE
    p_id NUMBER(2) CONSTRAINT c1 PRIMARY KEY,
    name CHAR(15),
    dob DATE
);

CREATE TABLE STUDENT ( -- SUBTYPE
    s_id NUMBER(2) CONSTRAINT c2 PRIMARY KEY,
    p_id_fk,
    grade CHAR(1),
    FOREIGN KEY (p_id_fk) REFERENCING PERSON (p_id)
);

CREATE TABLE TEACHER( -- SUBTYPE
    t_id NUMBER(4) CONSTRAINT c3 PRIMARY KEY,
    p_id_fk,
    tel CHAR(8),
    FOREIGN KEY (p_id_fk) REFERENCING PERSON (p_id)
);

CREATE MATERIALIZED VIEW PERSON_MV
  REFRESH COMPLETE
  AS SELECT p.P_ID,
            s.S_ID,
            t.T_ID
       FROM PERSON p
       LEFT OUTER JOIN STUDENT s
         ON s.P_ID_FK = p.P_ID
       LEFT OUTER JOIN TEACHER t
         ON t.P_ID_FK = p.P_ID;

-- Add constraint to the table underlying the MV

ALTER MATERIALIZED VIEW PERSON_MV
  ADD CONSTRAINT PERSON_MV_CK1
    CHECK( (S_ID IS NULL AND       -- either both are NULL
            T_ID IS NULL) OR
           ( (S_ID IS NULL OR      -- or only one is NULL
              T_ID IS NULL) AND
             (S_ID IS NOT NULL OR
              T_ID IS NOT NULL)));

INSERT ALL
  INTO PERSON (P_ID, NAME, DOB) VALUES (11, 'John', to_date('12/12/2012', 'dd/mm/yyyy'))
  INTO PERSON (P_ID, NAME, DOB) VALUES (22, 'Maria', to_date('01/01/2001', 'dd/mm/yyyy'))
  INTO PERSON (P_ID, NAME, DOB) VALUES (33, 'Philip', to_date('02/02/2002', 'dd/mm/yyyy'))
SELECT * FROM DUAL;

COMMIT;

INSERT INTO STUDENT VALUES (98, 11, 'A');

COMMIT;

BEGIN
  DBMS_MVIEW.REFRESH('PERSON_MV', 'C', '', TRUE, FALSE, 0, 0, 0, FALSE, FALSE);
END;
/

SELECT *
  FROM PERSON_MV;

Note the constraint added to the materialized view:
ALTER MATERIALIZED VIEW PERSON_MV
  ADD CONSTRAINT PERSON_MV_CK1
    CHECK( (S_ID IS NULL AND       -- either both are NULL
            T_ID IS NULL) OR
           ( (S_ID IS NULL OR      -- or only one is NULL
              T_ID IS NULL) AND
             (S_ID IS NOT NULL OR
              T_ID IS NOT NULL)));

This constraint allows data to exist where:

a PERSON row exists, but neither a related STUDENT or TEACHER row exists
a PERSON row exists along with either a related STUDENT or TEACHER row, but not both

So when we execute the final SELECT from the materialized view we get:
P_ID  S_ID  T_ID
11     98    -
33     -     -
22     -     -

Now let's modify the script above, adding the following just after the INSERT INTO STUDENT:
INSERT INTO TEACHER VALUES (1234, 11, 14809510);

COMMIT;

If we re-run the entire script, we find that when DBMS_MVIEW.REFRESH is called to refresh the materialized view we get:
ORA-12008: error in materialized view or zonemap refresh path ORA-06512: at "SYS.DBMS_SNAPSHOT_KKXRCA", line 3012
ORA-06512: at "SYS.DBMS_SNAPSHOT_KKXRCA", line 2424
ORA-06512: at "SYS.DBMS_SNAPSHOT_KKXRCA", line 88
ORA-06512: at "SYS.DBMS_SNAPSHOT_KKXRCA", line 253
ORA-06512: at "SYS.DBMS_SNAPSHOT_KKXRCA", line 2405
ORA-06512: at "SYS.DBMS_SNAPSHOT_KKXRCA", line 2968
ORA-06512: at "SYS.DBMS_SNAPSHOT_KKXRCA", line 3255
ORA-06512: at "SYS.DBMS_SNAPSHOT_KKXRCA", line 3287
ORA-06512: at "SYS.DBMS_SNAPSHOT", line 16
ORA-06512: at line 2
ORA-06512: at "SYS.DBMS_SQL", line 1721

This is Oracle's rather long-winded way to say that the constraint was violated.
See this LiveSQL Oracle session
Comment: I'm not as familiar with materialized views as I'd like/should be, but I believe you can set the MV up so it refreshes on commit so the issues would be detected then. But I don't know if the commit would complete normally and then the MV refresh would complain or what. Still, it's a thought.
Comment: That's a nice approach, +1. But the problem is that it only detects duplicates *afterwards*, when you refresh the MV. It does not *prevent* duplicates, like the canonical approach using triggers.
Answer: One option is to use database triggers, one for each table (STUDENT and TEACHER); they look the same:
Trigger on STUDENT:
SQL> create or replace trigger trg_bi_stu
  2    before insert on student
  3    for each row
  4  declare
  5    l_cnt number;
  6  begin
  7    -- inserting into STUDENT: check whether that person exists in TEACHER table
  8    select count(*)
  9      into l_cnt
 10      from teacher
 11      where p_id_fk = :new.p_id_fk;
 12
 13    if l_cnt > 0 then
 14       raise_application_error(-20001, 'That person is a teacher; can not be a student');
 15    end if;
 16  end;
 17  /

Trigger created.

Trigger on TEACHER:
SQL> create or replace trigger trg_bi_tea
  2    before insert on teacher
  3    for each row
  4  declare
  5    l_cnt number;
  6  begin
  7    -- inserting into TEACHER: check whether that person exists in STUDENT table
  8    select count(*)
  9      into l_cnt
 10      from student
 11      where p_id_fk = :new.p_id_fk;
 12
 13    if l_cnt > 0 then
 14       raise_application_error(-20001, 'That person is a student; can not be a teacher');
 15    end if;
 16  end;
 17  /

Trigger created.

SQL>

Testing:
SQL> INSERT INTO STUDENT VALUES (98, 11, 'A');

1 row created.

SQL>
SQL> INSERT INTO TEACHER VALUES (1234, 11, 14809510);
INSERT INTO TEACHER VALUES (1234, 11, 14809510)
            *
ERROR at line 1:
ORA-20001: That person is a student; can not be a teacher
ORA-06512: at "SCOTT.TRG_BI_TEA", line 11
ORA-04088: error during execution of trigger 'SCOTT.TRG_BI_TEA'

SQL>

Comment: @Littlefoot - re. 'concurrent inserts': insert person and commit. Then one session inserts student; another session inserts teacher with same person ID. Neither trigger sees the other session's uncommitted data, so both count zero and proceed, and both can commit, and the person is then present in both tables.
Comment: Sorry for the formulation that I removed. My point was 1) trigger is a *wrong* way to enforce constraints in a database. 2) the right way is to change the DDL based on the standard way of mapping *Class Table Inheritance*.
Comment: A-ha! Now I understand, thank you, both @Alex & Marmite.
Comment: Oh, Tom wouldn't be amused with a lot of code I wrote. Although you posted one hint ("concurrent inserts"), please - yet another hint - what about concurrent inserts, @Marmite?
Answer: Following on from @Bob's materialized view approach, a version that catches the issue on commit might look like this:
CREATE MATERIALIZED VIEW LOG ON STUDENT WITH PRIMARY KEY, ROWID;

CREATE MATERIALIZED VIEW LOG ON TEACHER WITH PRIMARY KEY, ROWID;

CREATE MATERIALIZED VIEW PERSON_HACK (p_id_fk, marker, rid)
BUILD IMMEDIATE
REFRESH ON COMMIT AS
SELECT p_id_fk, 1, ROWID FROM STUDENT
UNION ALL
SELECT p_id_fk, 2, ROWID FROM TEACHER;

ALTER MATERIALIZED VIEW PERSON_HACK
ADD CONSTRAINT PERSON_HACK_PK PRIMARY KEY (p_id_fk);

That should act similarly to a deferred constraint, erroring when the MV is refreshed (and its primary key violated) on commit. With concurrent inserts the second session to commit would see the error.
Live SQL, though it seems to have some issues with MVs (reported elsewhere). It should report the constraint violation, not throw ORA-12008. But I don't currently have access to test elsewhere - neither SQL Fiddle or db<>fiddle allow MVs to be created.

Of course, if you haven't been taught about MVs yet then using one in an assignment might look a bit odd. It seems a bit more likely that you've been taught about objects and the assignment is expecting those - even though they are very rarely used in the real world (within the DB), they seem to be taught anyway, along with old join syntax and other bad practices...
Answer: There exists four ways how to map an inheritance to relational database.
You are using the most exotic third option, which is causing the problem. Consider to switch to one of the other options as a solution.
The first three are well understood and documented, this page provides usefull links.
Basically you can map
1) all classes in one table
2) use one table for all concrete classes
3) define one table for aech class
All this options have some problems either with excesive joins or with deactivated constraints (e.g. you can't define non nullable columns in option 1), so for completness the option 4) is do not use inheritance in relational database.
You have tried to implement the option 3), but the problem is that all tables must inherite the same primary key (to enfornce 1:1 relation) and use this primary key as a foreign key.
Here the overview of all options for your example
-- 1) single table
CREATE TABLE PERSON (
    p_id NUMBER(2) CONSTRAINT pers_pk PRIMARY KEY,
    name CHAR(15),
    dob DATE,
    grade CHAR(1),
    tel CHAR(8),
    person_type VARCHAR2(10) CONSTRAINT pers_type CHECK  (person_type in ('STUDENT','TEACHER'))
);

-- 2) table per concrete class
CREATE TABLE STUDENT (
    p_id NUMBER(2) CONSTRAINT stud_pk PRIMARY KEY,
    name CHAR(15),
    dob DATE,
    grade CHAR(1)
);

CREATE TABLE TEACHER(
    p_id NUMBER(2) CONSTRAINT tech_pk PRIMARY KEY,
    name CHAR(15),
    dob DATE,
    tel CHAR(8)
);

-- 3) table per class
CREATE TABLE PERSON (
    p_id NUMBER(2) CONSTRAINT pers_pk PRIMARY KEY,
    name CHAR(15),
    dob DATE
);

CREATE TABLE STUDENT (
    p_id NUMBER(2) CONSTRAINT stud_pk PRIMARY KEY,
    grade CHAR(1),
    FOREIGN KEY (p_id) REFERENCING PERSON (p_id)
);

CREATE TABLE TEACHER(
    p_id NUMBER(2) CONSTRAINT tech_pk PRIMARY KEY,
    tel CHAR(8),
    FOREIGN KEY (p_id) REFERENCING PERSON (p_id)
);

INSERT INTO PERSON (P_ID, NAME, DOB) VALUES (11, 'John', to_date('12/12/2012', 'dd/mm/yyyy'));
INSERT INTO PERSON (P_ID, NAME, DOB) VALUES (22, 'Maria', to_date('01/01/2001', 'dd/mm/yyyy'));
INSERT INTO PERSON (P_ID, NAME, DOB) VALUES (33, 'Philip', to_date('02/02/2002', 'dd/mm/yyyy'));

INSERT INTO STUDENT (P_ID, GRADE) VALUES (11, 'A');
INSERT INTO TEACHER (P_ID, TEL) VALUES (11, 14809510);

Comment: The problem still remains I tried using your suggestion but it didn't work for me. What is the point of adding 'John' in both Student and Teacher table? It shouldn't accept it.
Comment: @LoizosVasileiou Well a *teacher* may be a *student* as well (in other course). If you want to disable it, use either the option 1) and add a *discriminant* column defining the ´person_type´ or the option 2) with key assigned from a single sequence,that will ensure that the tables have no disjunct keys.


Expired "authentication token" for user with deleted password

Question: The Setup:
1) The user's password was deleted with "passwd -d " command
2) The user has cron jobs running
The Problem:
Once every 30 days (default password expiration policy) the cron fails with an error
Authentication token is no longer valid; new one required
ERROR: failed to open PAM security session: Success
ERROR: cannot set security context

My Questions:
Is there a way to prevent this from happening?
Why is the authentication token expired for a user with deleted password?
Answer: I had this issue on a Debian 8 DigitalOcean droplet created using the 'user data' (web-form-posted setup script (bash or cloud-init)) option.
check systemd journal for relevant error messages:

journalctl | grep -B 1 -i "cron.*authentication token" | tail -n 3

May 19 13:17:01 debian-512mb-fra1-01 CRON[16714]: pam_unix(cron:account): expired password for user root (root enforced)
May 19 13:17:01 debian-512mb-fra1-01 CRON[16714]: Authentication token is no longer valid; new one required
May 19 13:17:01 debian-512mb-fra1-01 cron[470]: Authentication token is no longer valid; new one required

see which account(s) have expired status

cut -d: -f 1 /etc/passwd | while read U ; do chage -l $U | sed
  "s|^|$U:|"; done | grep "must be"

root:Last password change                   : password must be changed
root:Password expires                   : password must be changed
root:Password inactive                  : password must be changed

use 'chage' tool to update expiry fields, first attempt

chage -I -1 -m 0 -M 999999 -W 31 root

Note: didn't have the desired effect until I also added the 'last-changed' option (-d)
use 'chage' tool to update expiry fields, second attempt

chage -d `date "+%F"` -E 2999-01-01 -I -1 -m 0 -M 999999 -W 31
  root

check the field expiry

chage -l root

Last password change                    : May 19, 2017
Password expires                    : never
Password inactive                   : never
Account expires                     : Jan 01, 2999
Minimum number of days between password change      : 0
Maximum number of days between password change      : 999999
Number of days of warning before password expires   : 31

Answer: It sounds like your system removed the password but did not clear the password expiration requirements.
If this is the case you can clear these manually using vipw -- The affected field will either be in the passwd file or the shadow file depending on your OS (See man 5 passwd and man 5 shadow for details on the file formats so you know which field(s) you need to clear)
Comment: If you update your question to include a specific OS tag and leave a comment here and I'll come back and update this answer with specifics for your OS.
Answer: On Ubuntu my /etc/shadow file was missing (though there was an /etc/shadow-) so all I did was run...
sudo pwconv

...And it fixed this issue for me by recreating the /etc/shadow file.
(Though I can not yet confirm this is a long term fix, it may last until the password change/expire time or until some other factor happens) --- someone back me up or correct me