How to protect Apache server from SQL injection

Question: Without going into the platform underneath, is there any effective way to protect a web server from SQL injection?
Any special Apache module or config?
Would fail2ban be appropriate here?
Comment: Apache isn't an SQL server, but by the time the SQL gets to *any* server it has already potentially been injection-attacked. You're asking the wrong question about the wrong component at the wrong side of the system.
Answer: Apache is not subject to an SQL injection, as it is not a database.
If you want to protect an application Apache runs which in turn calls a database, you could put  a WAF (Web Application Firewall) in front if it.
Another approach would be to use mod_security in Apache with a ruleset that looks for SQL in the post/gets.
Fail2ban would be of very limited use as it scans log files for signs of brute force attempts. An SQL injection would often  not be visible in the logs, and even if the logs are extended so as to expose this information, they are unlikely to be of much use, as they will pick up the request after its been processed.
Comment: "Another approach would be to use mod_security in Apache with a ruleset that looks for SQL in the post/gets." Sorry, but [that's a terrible idea](https://thedailywtf.com/articles/Injection_Rejection). In all seriousness, there's no way to have that sort of protection in the general case without either being completely ineffective, or being horribly susceptible to false positives.
Comment: @josephsible - Shall we agree that the correct place to fix SQL injection is in the app, and anything else is less then ideal - but if yodefinately u can't control the app and can't substitute it, limiting SQL using mod_security or equivalent appliance is better then nothing (but not  great)
Comment: @davidgo If virus scanners had as high of a false positive rate as that sort of SQL injection "protection" does, we absolutely wouldn't run them either. The reason that virus scanners are acceptable is that they stop a reasonable number of viruses and have few false positives.
Comment: I'm looking into modsecurity ( https://www.modsecurity.org/ ). I've never used it before. It looks interesting. Thanks!
Comment: @JosephSible That article is from 2006 and does not mention mod_security.  Yes, its impossible to fully prevent SQL injection in arbitrary code, but its like saying dont run AV scanners because they wont detect all new Virii.  Perfect is the Enemy of good.  I understand the SQL injection rules for mod_security are quite well established, so obviously they have some beneficial effect.   Also, if you have known SQL injection vectors on servers you cant update (it happens, even though it shouldnt), this can help.
Comment: @davidgo And yes, specific known SQLi vulnerabilities that you can't patch for [insert bad reason here] are a good use case for mod_security. But that's very different than trying to stop them in general.
Comment: You should update your answer to mention using paramatized prepared statements from your programming language of choice. Almost all (all?) offer this as a way to mitigate or eliminate SQLi attacks.
Comment: @Snakedoc but that's not an answer to the question asked.
Comment: Guys, I am 17 rn, and have no idea about any of this. Can you please recommend me a source from where I can learn?
Comment: @mathdudemathdude3013 Learning recommendations are off topic here, but SQL injections are number 1 on the OWASP top 10. Find your local/closest chapter and connect with them.
Comment: @davidgo it's not the direct answer they asked, but it's the right answer. telling OP how to kinda-sorta mitigate SQLi in a system that's not meant to do that is leading them down the wrong path. OP clearly doesn't understand the problem space - so pointing down a futile path is wrong. Help them learn - and point them in the right direction.
Answer: SQL injection is well documented. Fix your applications, not necessarily your web server.
CWE-89 categorizes SQL injection in detail. Note how mitigations like parameterization or using a decent persistence library are in the development phase. There's only so much a WAF style filter can do post deployment.
OWASP has practical resources for how to develop applications correctly avoiding SQL injection in the first place.
MITRE ATT&ACK categorizes it as a public-facing app exploit and lists software updates and application isolation among mitigations.
Comment: Also think that this is far more of an application problem than it would be a server problem.
Answer: SQL injection should be prevented at the application (using parameterized queries, escaping user input, using stored procedures, etc). Other ways of mitigating against SQL injection would be things like Apache's mod_security or using a service like Cloudflare.
Comment: I'm the system administration, not the programmer of the ap. Sometimes, (most of the times) this approach is out of our reach and we have to implement as many security features as possible because even if there's anything with this objective already implemented in the app code, it could be flawed as well.
Answer: As written previously, you should tackle SQL injections on an application level.
If you use out-of-the-box software like wordpress, keep it up to date. If you develop yourself, use prepared statements whenever possible and never ever trust user input.
If you really want to do some hardening, use .htaccess to forbid any URLs that contain a semicolon or two dashes. ( ; and -- ), That will catch... well, maybe 1/3 of the attacks? Don't rely on that though.
That said, you can and should harden your server as much as you can, just keep in mind that some restrictions might affect legit traffic as well. Assuming you use PHP, check Suhosin.
Answer: In the olden days we used to sanitise inputs in the application, before they got near the database.  Maybe things are 'different' these days.  Here's a post from 11 years ago, which has been active recently: https://stackoverflow.com/questions/129677/how-can-i-sanitize-user-input-with-php
Comment: it still happens at application level. It's just these days often handled transparently by web application frameworks rather than the application developer having to hand code it all.


nginx-ingress returns 502 After upgrading to kubernetes v1.24.6

Question: When trying to upgrade from kubernetes v1.23.X to v1.24.X.
I has been seen that the health probe needs to be changed to be /healthz (azure)
I have a configuration that works in 1.23 but not 1.24
I have a configuration that works in 1.24 but not 1.23
The problem I've got is whilst upgrading to v1.24 nginx-ingress will break introducing down-time.
I've seen some people suggest setting the ports to TCP
Kubernetes v1.24.3 upgrade broke ingress-nginx
However they have informed us on how to set the healthz probe (great can confirm that works with 1.24) they havn't said how they got the TCP fix to work. I'm hoping that the TCP fix will run in both 1.23 and 1.24
Hopefully one of you can help me?
Answer: Setting the following annotation worked:
<code>    annotations:
      service.beta.kubernetes.io/azure-load-balancer-health-probe-request-path: /healthz
</code>


How to join tables?

Question: I have three tables:
parts:

+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
+-------+------------------+------+-----+---------+----------------+
+----+
| id |
+----+
|  1 |
|  2 |
|  3 |
+----+

parts_partid:

+-----------+------------------+------+-----+---------+-------+
| Field     | Type             | Null | Key | Default | Extra |
+-----------+------------------+------+-----+---------+-------+
| part_id   | int(10) unsigned | NO   | PRI | NULL    |       |
| partid_id | int(10) unsigned | NO   | PRI | NULL    |       |
+-----------+------------------+------+-----+---------+-------+
+---------+-----------+
| part_id | partid_id |
+---------+-----------+
|       1 |         1 |
|       1 |         2 |
|       1 |         3 |
|       2 |         1 |
|       2 |         4 |
|       2 |         5 |
|       3 |         6 |
|       3 |         7 |
|       3 |         8 |
+---------+-----------+

partid:

+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| key   | varchar(50)      | NO   | MUL | NULL    |                |
| value | varchar(50)      | NO   |     | NULL    |                |
+-------+------------------+------+-----+---------+----------------+
+----+-----+-------+
| id | key | value |
+----+-----+-------+
|  1 | l   | foo   |
|  2 | p   | bar   |
|  3 | s   | baz   |
|  4 | l   | 3     |
|  5 | p   | 5     |
|  6 | s   | r     |
|  7 | l   | rr    |
|  8 | l   | rrr   |
+----+-----+-------+

Basically each part consists of arbitrary part-ids. e.g. part #1 has l = 'foo', p = 'bar' and s = 'baz'.
If I want to search for all parts which have l = 'foo' I use this join
SELECT p.id FROM parts AS p
INNER JOIN parts_partid ppi ON ppi.part_id = p.id
INNER JOIN partid pi ON ppi.partid_id = pi.id
WHERE pi.key = 'l' AND pi.value = 'foo';

Which gives me part #1 and #2.
Now I want to search for all parts which have l = 'foo' and p = '5' (which should result in only part #2). How can I do this?
Comment: What RDBMS you are using??
Answer: Try this....
SELECT p.id FROM parts AS p
INNER JOIN parts_partid ppi ON ppi.part_id = p.id
INNER JOIN partid pi ON ppi.partid_id = pi.id
WHERE (pi.key = 'l' AND pi.value = 'foo')
or    (pi.key ='p' and pi.value = '5')

Comment: I don't think that workds. Because it is possible that a parrt with p=5 exists which doesn't have l=foo. I want both, but if I "AND" everything together I get nothing.
Comment: so u can use "OR" Operator.
Answer: Try this:
SELECT id
FROM
(
  SELECT
    p.id,
    MAX(CASE WHEN pi.Key = 'l' THEN value END) AS l,
    MAX(CASE WHEN pi.Key = 'p' THEN value END) AS p,
    MAX(CASE WHEN pi.Key = 's' THEN value END) AS s
  FROM parts AS p
  INNER JOIN parts_partid ppi ON ppi.part_id = p.id
  INNER JOIN partid pi ON ppi.partid_id = pi.id
  GROUP BY p.id
) AS t
WHERE l = 'foo'
  AND p = 5;

SQL Fiddle Demo
This will give you only the part2:
Results:
| ID |
------
|  2 |

The idea behind this query, is the subquery, which will pivot the keys' values into columns; it will give you those keys for each id as columns headers:
| ID |   L |      P |      S |
------------------------------
|  1 | foo |    bar |    baz |
|  2 | foo |      5 | (null) |
|  3 | rrr | (null) |      r |

Then in the outer query you can filter on the values of these columns.
Comment: @user2210830 - So does it work fine for you? If so try to accept it, by checking the mark on the left.

How to join tables?


Android Listview don't receive onItemClick with custom ViewGroup

Question: Hey I made a custom viewgroup extends relative layout and override the onTouchEvent(), and always return true in onTouchEvent(). I make this custom viewgroup as my listview's item layout. I also add the onItemClick listener for the listview. But I can't receive onItemClick event for my listview! Could anybody help me?
Thanks very much!!!
Answer: just difine onitemclick in the adapter class getView (... ) i think it will work for you
public View getView(final int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.list_row, null);
  vi.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {

        }
    });

Answer: If you return true in onTouchEvent(), the event is handled and thus does not bubble up to the ListView. Try returning false.
Comment: If I return false, then I can't get other MotionEvent later in my viewgroup. How to fix this? Thanks!
Comment: How about if you return `super.onTouchEvent()`?
Comment: super.onTounchEvent()will return false at this case. And the viewgroup will not receive ACTION_UP event anymore.
Answer: Using only onitemClick event is enough i guess as far as your question is concerned
Comment: No, I should do some work when MotionEvent down and MotionEvent up.
Comment: @Override
public boolean onTouchEvent(MotionEvent event) {

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            doMyWork();

            break;

        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP:
            endMywork();

            break;

        default:
            break;
    }
    return super.onTouchEvent(event);
}
Answer: The issue is that you always return true from your ViewGroup's onTouchEvent(MotionEvent) method. That means that your relative layout is responsible for handling this touch events.
Read android documentation for more information http://developer.android.com/training/gestures/viewgroup.html


whether a ray can presented as a union of open rays

Question: Suppose $[2, \infty) \subset \mathbb{Q} $. Can we represent $[2,\infty)$ as a union of open rays in $\mathbb{Q}$: That is, can we have
$$ (2, \infty) = \bigcup_{x > 2} [x, \infty) $$
???
Answer: Since $2 \notin (x, \infty)$ for any $x > 2$, the union
$$\bigcup_{x > 2} (x, \infty)$$
does not include $2$.
Note than even if $(x, \infty)$ is replaced by $[x, \infty)$, the statement does not hold by the same argument.
Comment: what if we replace $\mathbb{Q}$ with $\mathbb{N}$ ?
Comment: What do you mean by $[2, \infty) \subset \mathbb{Q}$? Is $\mathbb{Q}$ the set of rational numbers? If so why would $[2, \infty) \subset \mathbb{Q}$?
Comment: Or do you indeed mean $[2, \infty) = \bigcup_{x > 2, x \in \mathbb{Q}} (x, \infty)$?
Comment: yeah this is what I mean
Comment: Not true either. It is even a (improper) subset of $\cup_{x > 2} (x, \infty)$ which does not include $2$.
Comment: Usually the problem appears at the end-points. You just check whether the 2 sets include/exclude the same set of accumulation points.
Comment: but isnt $$(2, \infty) = \bigcup_{n} [2 + \frac{1}{n}, \infty) $$?
Comment: Yes it is. Indeed $\cup_{x>2,x \in \mathbb{Q}} (x, \infty) = \cup_{x>2,x \in \mathbb{Q}} [x, \infty) = (2, \infty) \subsetneq [2, \infty)$


Virtualenv django package unresolved

Question: I'm new to django and find my django package always unresolved, but the project runs successfully, the interpreter setting is right, the pip list shows the django package, I clip some pics here, can someone tell me how to remove these warnings? Are there any pronlems in environment variables or version conflicts?
Warnings:
enter image description here
Interpreter setting:
enter image description here
project structure setting:
enter image description here
run/debug configuration:
enter image description here
Answer: have you tried to run it with virtual environment ?  use the poetry
to avoid the conflicts with other django projects in your local machine, i am not
sure but the maybe it conflicts with other django project with different version
poetry provides the version control file, this link will help you to configure poetry with django project poetry Cheatsheet
hope it helps
Answer: "Django is not importable in this environment" is probably the decisive error message. The causes for it seem to vary, but many are treated here: Pycharm error Django is not importable in this environment

Virtualenv django package unresolved


What is it about the 9th that gets used so much over minor triads by songwriters?

Question: I have come across an uncanny amount of examples in song analysis where the 9th (or 2nd) is used over a minor triad in an important way. I don't just mean as a passing tone but as a, beginning notes, a climax "money" note and even as an ending note over a minor chord. Here is an example by Coldplay, "Green Eyes", where the song ends on the Bm chord with the C# note as the final note.

I really like the sound of the note but when I play the chord at the end of the Coldplay song on piano with the vocal melody note it sounds quite dissonant against the min3rd of the B chord (D).
Is there something special about this note or indeed a min9th chord that makes it get used so much?
Comment: Regarding the dissonance, a minor 9th chord can potentially be dissonant if the 9 and 3 are adjacent to each other. That creates a m2 cluster, but some people like that sound (I do) especially within a voicing. The thing to look out for with a m9 chord is in what octave the notes are. If the 3rd is an octave above the 9th you will have a m9 interval between them which is more dissonant than a m2. That's the case here between the D in the guitar and the C# in the vocal. This is something you're typically supposed to avoid but they either liked the sound of it or it didn't bother them.
Answer: Who knows why it's used "so much". How much? How much is it used where? In all genres and cultures? Or just some? Is it used much on American country & western songs? Elbonian polka songs? The note is most probably used in some very speficic genres and cultures where people like and tolerate what it does.
Here are my personal and subjective reasons to use the 9th / 2nd scale note over minor chords:

It adds a bit of texture and harmonic thickness without creating tension or pushing towards another chord. You can add it anywhere and it kind of seems to do something without doing anything "functional".
It sounds slightly unexpected and jazzy in some contexts, but not too weird to alienate most people. If you add the 9th in a song that's usually not played like that, it makes it sound "different".
In a melody or solo it can add melancholic feeling, because it's away from home. Not too close like a flat 9th would be (which not only demands harmonic motion but also adds plain "sensory dissonance"), but somehow close enough that you could stay there just as well as move.
When added over a minor chord on the 3rd scale degree (of the major scale, e.g. C#m in your example song), a 9th adds a bit of "outside" or modal alteration feel, but very lightly and temporarily.
In a melody or solo you can safely add a 9th over any minor chord, to create the effects mentioned above, so it's good for soloing. It doesn't add anything functional, so it won't disturb or distract the harmonic progression.
A minor chord's 9th is the same note as the relative major's maj7, and it seems to bring a bit of the same effect. For example in Am vs C, the B note is Am's 9th, but C's maj7. Let the B ring, it can be a glue note.

I think a lot of the above could also be said about adding a 9th to major chords as well.
And almost the same applies to adding an 11th to minor chords. It sits there nicely, adding texture without doing much. For major chords, it can clash a bit with the third, but for minor chords it doesn't.
Here's a nice chord progression that uses some of the stuff above.

Additional notes create texture and melancholic feeling, but it's still just F Dm Bb  C. (By the way, the added 11th on the C chord doesn't seem to clash with the third at all. IMO)
Answer: There is a lot of opinion based comment driving this question.  I am not sure there is anything "special" about the minor 9th chord in contrast to the Maj 9th, or the 9th.  Why do you think there is?  If I do a quick search through my library of scores, real books, and other song books I see a fair amount of -9, M9, and 9 all over.  In fact I'd say there are more occurrences of the 9 and #9 showing up in classic rock, blues and Jazz than -9 across the genres.
One thing that comes to mind is that the 9th (or 2nd to be more precise) is used to create a suspended resolution in a minor key.  In a major key one often encounters the progression V7 --> Isus --> I where Isus refers to a sus4.  In a minor key one encounters V7 --> isus(2) --> i.  Leaving the 2 in the chord while introducing the -3 creates the -9 chord.
This device is used a lot in classical music and it does seem that the sus chords (both 4th and 2nd) enter the spot light in modern music.  I recall seeing an interview with Ruth Underwood where she commented on Frank Zappa using sus2 chords all over the place in his compositions.  He just loved that chord.  As mentioned by other answers this chord has a lot in common with the relative major 7th chord and many guitarists will replace one with the other.  This is more true of the Maj6 and the relative -7 chords as they are identical, not just slightly overlapping.  From a composition perspective using such chords allows one to create a sense of key ambiguity and move seamlessly between the minor and relative major keys without a modulation chord sequence (although I prefer to hear such sequences as depicted in Max Reger's text).  But really, this is speculation on my part.  The only way to make objective sense of this question is to show some statistics that prove that the -9 chord is "common" by some measure and then issue a survey to songwriters to try and understand their reasoning.


Suppose $M$ is a module and $K = \{(m, m) : m \in M\} \subset M \oplus M$. Show $K$ is a submodule of $M\oplus M$ which is a direct summand.

Question: I'd like to have some clarification and help on this problem.
Suppose $M$ is a module and $K = \{(m, m) : m \in M\} \subset M \oplus M$. Show $K$ is a submodule of $M\oplus M$ which is a direct summand.
Showing $K$ to be a submodule in $M \times M$ should just follow from definition. But I'm a bit unsure of what a summand is so I'm not sure how to show this last bit that $M \oplus M$ is a summand (or is it asking whether $K$ is a summand?)
Comment: Actually, you should not merely show $P\oplus K\cong M\oplus M$, but rather $P\oplus K=M\oplus M$. Note that $\cong$ is trivial as $K\cong M$ (as you may have noted). We are talking of "internal direct sum" here. So you need to show that $P+K=M\oplus M$ and $P\cap K=0$.
Comment: You need to show there exists another module $P$ such that $P \oplus K \cong M \oplus M$. To further clarify the terminology: this shows that $K$ is a summand of $M \oplus M$.
Comment: That's true. $P$ and $K$ aren't just abstract modules; they're concrete submodules of $M \oplus M$.
Comment: Then would we simply choose a $P$ such that $P \cap K = 0$? The only situation in which $P \cap K \ne 0$ is if $ x = (a, a) \in L$, but we can remove this from P since it is contained in $K$?. i.e. $K = M \oplus M - P$

And so we can construct any $x \in M \oplus M$ from $P + K \{p + k : p \in P, k \in K\}$ ?

It seems like everything sort of follows from construction or definition?
Answer: You can take $P=\{0\}\oplus M$ or $P=M\oplus \{0\}$. Both satisfy the two conditions: $P\cap K=\{(0,0)\}$ and $P+K=M\oplus M$.


User Creation Flow via API

Question: I'm creating a user in 2 parts; firstly without creds and and then when the user clicks on an email link (with code) we then get them to put in the password and recover q&a. I'm then using the APIs to finish and activate the user in this order:
setPassword
setRecoveryQuestion
activateUser
When i check the user they're ACTIVE but when i try and log in the UI challenges me to select a picture, recovery answer etc.
What's the correct order/way to complete a user created w/o credentials so that they only need to use their username and password?
Comment: Can you provide the example API calls you are making.
Comment: Thomas,

the calls i'm using are these (via the java API):

client.setRecoveryQuestion(userId, question, answer);

then

client.setPassword(userId, userPassword);

then finally

client.activateUser(userId);

All straightforward but for some reason when i then login to the OKTA dashboard it presents me with a screen requesting the answer to the security question and to select a picture.
Answer: You may have to configure the MFA policy to not require security image/picture.

User Creation Flow via API


Use hook to remove height from img tag?

Question: The theme I am building is responsive and so many images have max-width:100%; applied in CSS. Can I use a hook in template.php to strip the height attribute from img tags because it is causing lots of distortion issues, and how would I go about this?
Thanks for your time!
Answer: Assuming that your images are being built by theme('image',...) you can override its default...
function theme_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '';

}
...in your template.php file along the lines of this:
function YOURTHEME_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  foreach (array('alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '';

}
and now those pesky height=s and width=s should be gone.
Comment: just flush caches after doing this to make sure the theme registry is rebuilt and it sees it
Answer: Rather than editing Drupal behavior can also just set img CSS to height:auto

Use hook to remove height from img tag?


Swift: Return class constrained with generic type

Question: I have a basic generic class:
class SharedClass<T> {}

And a builder for it:
class SharedClassBuilder {
    func build<T>() -> SharedClass<T>? {
        return ...
    }
}

What I want to be able to do, is return an instance that inherits SharedClass, and conforms to T. For example:
protocol MyObject {
    func doIt()
}

var result: SharedClass<MyObject>? = SharedClassBuilder().build()
result?.doIt()

Unfortunately, the Swift compiler complains that the returned type does not have a member named doIt.
Is there a way to achieve what I'm looking for?
Answer: I suspect it's not so much that you want the returned class to be constrained by the generic type, as you're asking the returned class to be an instance of the constrained type. In your snippet, you're expecting the unwrapped result to conform to MyObject. Taking this a step further, it means that the conformance of SharedClass is determined entirely from how it was constructed. As far as I know this isn't supported in Swift.
However, there's nothing stopping you having a member of SharedClass that is a T. Something along the lines of:
class SharedClass<T>  {
    var v : T?
}

class SharedClassBuilder {
    func build<T>() -> SharedClass<T>? {
        return SharedClass()
    }
}

protocol MyObject {
    func doIt()
}

var result: SharedClass<MyObject>? = SharedClassBuilder().build()
result?.v?.doIt()

Comment: That might be a decent option, thanks! Essentially what I'm after is the ability to return some kind of dynamic proxy object that conforms to `T`, probably based off of `NSProxy`. Swift doesn't like the idea of returning `T` directly, probably because it can't be instantiated.
Comment: Indeed. Swift likes to know the type of everything at compile time, to provide more guarantees about code safety. However, if you're willing to restrict yourself to classes that inherit from `NSObject`, then you can implement this fine (essentially as `NSProxy` does). You'll lose a some of the static guarantees, but you might not care.

You could also consider losing the `SharedClass`, and having the builder just return a `T`. Especially if you just use protocol type `T`s, everything will work out fine statically.
Comment: Yeah, I had thought of that, the issue with using classes instead of protocols for `T` is you'll have to implement stubbed methods the whole way down, so it becomes a bit strange to implement, whereas if they could pass in a protocol it'd make a bit more sense. If Swift had support for abstract classes this wouldn't be as much of an issue.


prove that f is continuous on $\mathbb{R}$

Question: Let, $f:\mathbb{R}$ $\rightarrow$ $\mathbb{R}$ be a function satisfying $f(x+y)=f(x)f(y)$.
Given that, $f$ is continuous a $x=0$. Prove that, f is continuous on $\mathbb{R}$.
Comment: did you try anything at all?
Comment: @ABC We can not move forward, understand mathematics and improve our skills if we don't try: it isn't waste of time and all who do mathematics know this.
Comment: @ABC Ok but at same time there's another who think to post a question without trying in it and by seeing this question he know that he must do some effort.
Comment: Notice that you can translate a point $a$ to the origin by using $f(x+a)$, but because of the given property the function looks again at the origin since $f(x+a)=f(a)f(x)$. Notice that $f(a)$ is a constant and $f(x)$ is at the origin.
Comment: I'd just like to point out that it is absolutely false that the only reason to ask if someone has tried anything is the belief that solving someone's homework is a bad thing.  The answer to that question can be very useful in determining how someone's thinking about a problem, why that thinking has been unfruitful or led then astray, and what exactly needs to be explained in order for them to understand.
Comment: Assuming that every time someone asks that question they're just being snobby about making someone do their homework is every bit as snobby and unhelpful as what you've assumed the other person is doing.
Comment: Don't worry about bad professors making you waste your time asking if you have tried it. Shame on them.
Comment: After seeing how this problem was solved, pay attention on what features of the property $f(x+y)=f(x)f(y)$ made it possible for the technique used in the solution to work. You can try then similar-looking problems. For example, replace in your problem the given equation by $f(x+y)=f(x)+f(y)$.
Comment: It is a waste of time asking it here. You can imagine that after every post saying "did you try" there is another saying "yes, but I didn't know what to do". After all, the OP already went out of his/her way to find a solution. Part of the learning process is also seeing solutions.
Comment: The only reason people ask "did you try it" is because they feel they may be solving someone's homework, and they have the false believe that that is a bad thing, that homework should be individual.
Comment: Sure. "did you eat enough vegetables today?". It is equally important. I believe more that the intention is encouraging effort, when a hint is given. Those that ask for showing effort have other intentions (bossing, trying to prevent people from getting homework answers). I don't hold any of those in high esteem.
Comment: @ABC I saw your profile where you have also written on this subject, ok it is a  point of view that I respect and  even I can  understand it.
Comment: can you tell me what is the geometry of this type of function $f(x+y)=f(x)f(y)$
Comment: @Mathematics What do you mean by the geometry of this type of function?
Comment: I mean is there any geometrical behaviour of this type of functions? @ Sami Ben Romdhane
Comment: We can prove that the functions that satisfy this functional equality are either the zero function or the exponential functions.
Comment: how can we prove? @ Sami Ben Romdhane
Comment: @Mathematics Ask this question for the benefit be for everyone.
Comment: Please make it clear how to do..I am  not being able to do this @ Sami Ben Romdhane
Answer: The function $f$ is continuous at $0$ means that
$$\lim_{y\to0}f(y)=f(0)$$
Now let $x\in\mathbb R$ then
$$\lim_{t\to x}f(t)=_{(y=t-x)}\lim_{y\to0}f(y+x)=\lim_{y\to0}f(x)f(y)=f(x)f(0)=f(x+0)=f(x)$$
hence $f$ is continuous at $x$.
Answer: Hint:
$$f(x) - f(y) = f(y)[f(x - y) - f(0)]$$


Removing Convert.ToDecimal Dependency (Dependency Injection)

Question: I am currently learning dependency injection to create more maintainable code with MVC. I am already injecting a model and a calculator service to my controller instead of having a to new up dependency.
I have a few Convert.ToDecimal calls in my constructor, and didn't know if I needed to worry about using dependency injection to remove the static method call which is a DI design smell. Is removing that going too far?
private readonly ICalculationService _calculation;
private readonly ICalculatorModelService _calculatormodel;

public CalculatorController(ICalculationService calculation,
    ICalculatorModelService calculatormodel) {
    _calculation = calculation;
    _calculatormodel = calculatormodel;
}

public ActionResult Index() {
    var model = _calculatormodel;
    return View(model);
}

public PartialViewResult Calculate(string submit, string txtValue,
    string value1) {
    var model = _calculatormodel;
    if (submit == "+")
    {
        if (Session["value1"] == null)
            Session.Add("value1",Convert.ToDecimal(txtValue));
        else
            Session["value1"] = value1;
    }
    else if (submit == "=")
    {
        if (Session["value1"] == null)
        Session.Add("value1", 0);

        model.Result = _calculation.Calculate(Convert
            .ToDecimal(Session["value1"]), Convert.ToDecimal(txtValue));
    }

    return PartialView("_Calculator", model);
}

Comment: What you are thinking about dependencies on types `string`, `decimal`?
Comment: It mainly depends on how easy the code will be to test and maintain based on the dependency.  If it's easy to test and maintain while calling the static function, there is not much gain injecting it.  But if it is hard to test and maintain, you should inject the dependency because then you can stub it in tests.
Comment: Read about the difference between [stable and volatile dependencies](https://blogs.msdn.com/b/ploeh/archive/2006/08/24/718828.aspx).
Comment: I don't quite understand your question. Currently the code has a dependency on the Convert .Net class.
Comment: Thank you for the response Caleb. It was helpful. I am happy to be learning!
Answer: If I understand the question, you are worried about the static call of Convert and you ask if this class should also be injected.
If that's the case, you don't have too. Same goes for similar static calls like Math. methods etc.
The rule I follow for such .NET helper calls is, if the call is deterministic, i.e. always returning same output for the same input, then go ahead call it (anyway you depend on .NET framework, right?). But if the call is non deterministic, like Datetime.Now or use of Random class, then I inject these dependencies (which makes code more testable, of course)
Comment: That makes complete sense to me. Thank you for breaking it down. I like your answer!


Remove tokenized string from URL and return

Question: Code I'm implementing is trying to modify a URL by removing series of numbers and letters if available. What am I missing?
function removeToken() {
      let tokenUrl = "https://www.example.com/pathone/pathtwo/8943d932fee15d8be922d1f51f68c0bf3f929824fd48cda8299144861d214c3e/summary";
      let regex = new RegExp("/(?:\d+[a-z]|[a-z]+\d)[a-z\d]*");// if url matches anything like 8943d932fee15d8be922d1f51f68c0bf3f929824fd48cda8299144861d214c3e
      if (regex.test(tokenUrl)) {
          tokenUrl = tokenUrl.replace("/(?:\d+[a-z]|[a-z]+\d)[a-z\d]*", ''); //remove anything like /8943d932fee15d8be922d1f51f68c0bf3f929824fd48cda8299144861d214c3e from URL
          return tokenUrl; // desired return https://www.example.com/pathone/pathtwo/summary
      } else {
          return tokenUrl;
      }
    }

Comment: For starters, what are you getting instead?
Comment: @caTS i'm getting undefined
Comment: How are you using it? It should not be able to return undefined.
Comment: @caTS Nothing returns or prints to the console. I did get undefined in some online code tester but JSfiddle and codepen returns nothing.
Comment: Really? I get something [with jsfiddle](https://jsfiddle.net/j0nurLo8/).
Comment: @caTS you're right. I had some additional code interference
Comment: Your regex is inside of a string
Answer: Defining the regex directly without the class constructor works for me
function removeToken() {
let tokenUrl = "https://www.example.com/pathone/pathtwo/8943d932fee15d8be922d1f51f68c0bf3f929824fd48cda8299144861d214c3e/summary";
let regex = /\/(?:\d+[a-z]|[a-z]+\d)[a-z\d]*/  // if url matches anything like 8943d932fee15d8be922d1f51f68c0bf3f929824fd48cda8299144861d214c3e
if (regex.test(tokenUrl)) {
    tokenUrl = tokenUrl.replace(regex, ''); //remove anything like /8943d932fee15d8be922d1f51f68c0bf3f929824fd48cda8299144861d214c3e from URL
    return tokenUrl; // desired return https://www.example.com/pathone/pathtwo/summary
} else {
    return tokenUrl;
}
}

You can also make it a bit more dry
function removeToken() {
    let tokenUrl = "https://www.example.com/pathone/pathtwo/8943d932fee15d8be922d1f51f68c0bf3f929824fd48cda8299144861d214c3e/summary";
    let regex = /\/(?:\d+[a-z]|[a-z]+\d)[a-z\d]*/
    return tokenUrl.replace(regex, '');
}

Answer: It looks like a mistake most people make, I do it alot too.
You put the regex /(?:\d+[a-z]|[a-z]+\d)[a-z\d]* inside a string, and also forgot a /.
I've also cleaned the code, removed unnecessary code, and fixed a couple other mistakes.
Here's the fixed code:

function removeToken() {
  let tokenUrl = "https://www.example.com/pathone/pathtwo/8943d932fee15d8be922d1f51f68c0bf3f929824fd48cda8299144861d214c3e/summary";
  let regex = new RegExp(/(?:\d+[a-z]|[a-z]+\d)[a-z\d\/]*/gi);
  if (regex.test(tokenUrl)) {
    tokenUrl = tokenUrl.replace(/(?:\d+[a-z]|[a-z]+\d)[a-z\d\/]*/gi, 'summary');
    return tokenUrl;
  }
  return tokenUrl;
}
console.log(removeToken());


Can I use the Use Case Diagram in SCRUM?

Question: I'm starting a project with a team and we're using SCRUM as methodology. It's my first time with SCRUM. We have listed our functionalities and we made our stories, (user stories and technical stories as well as their tasks).
I've a tight UML approach to start any dev project and for me, after listing all the functionalities, the next step is to make the User Cases Diagram to let everybody see what's the application going to do and who's gonna interact with it. But my team said that there's no interest in using UML in SCRUM.
Can I use the User Diagram of UML to represent the User Stories in SCRUM? Which other diagrams can be used in SCRUM? (It could be a stupid question 'cause I cannot imagine an application without a class Diagram or a Sequence Diagram, but I really wanna see the advice from the experts in SCRUM)
Thanks.
Comment: I'm voting to close this question as off-topic because it is not about programming.
Answer:
Can I use the User Diagram of UML to represent the User Stories in SCRUM?

A use case diagram would be helpful, because it is pretty straightforward, and gives a high level idea what the project is about.
However I won't recommend to use any other UML diagram in scrum. I agree with the others that in an agile project the code changes so frequently that your diagrams will be obsolete after several days. In this case you have to redraw them, which is a waste.
For example if you are using eclipse for development, a simple refactoring step can ruin your class diagram :-(

Which other diagrams can be used in SCRUM?

I would suggest to use mindmaps. Recently we started to create our own user stories with drawing large mindmaps and put them on the office walls.
We have a feature in the middle, and we connect sub user stories to it - and sub-sub user stories to them -, and every available information we have at the moment. With this approach we have everything in one place: user stories, technical informations, questions, etc.
Of course the mindmap grows day by day, and we know more and more about the feature we have to implement.
Actually we are doing something similar described in this agile dzone article, but since you are using scrum not xp+kanban I talked about user stories not MMFs.
Comment: I see _use cases_ as features or small features. A feature consists of different _user stories_. So a use case is a bunch of user stories for me
Comment: I like your answer. Only thing to add would be to stress the difference between use cases and user stories.
Comment: +1 interessting insight
Comment: @Zsolt your suggestion is interesting. I wonder if you have any simple real world example of using mind mapping for user stories?
Answer: You can use whatever you like in Scrum that helps your team communicate effectively.  Scrum makes no decisions, judgements, or guidance on what tools are effective for that team.  It only asks that you reflect on the tools and practices used in executing a Sprint and make adjustments accordingly.  This is the inspect and adapt loop.
Being open and honest in discussing the benefit of the tools and techniques used to deliver value requires a lot of effort and willingness by the individual members to be open to change.
Answer: What I've been told from people who've been using Scrum for a while (ie: this is opinion) is that doing UML diagrams can be a bit time consuming because as your development methodology is agile, your requirements could very easily radically change after the first sprint's show-and-tell, which means you could be doing fairly big redesigns.
Of course, do scratch up how you will tackle your tasks in the sprint backlog - you could certainly document as you go, but maintaining a central repository of class diagrams, etc. could be a slight waste in resources.
Answer: I'm not sure what's your role in the project, I'm supposing you are the PO. In that case, use additional documentation if it makes sense. Consider a user story as a reminder for the team to have a conversation with the PO about it.
If you think the user case diagram will clarify the functionality you are asking for, the it's ok. In fact, place it on the wall beside the scrumboard and burndown chart.
In my experience it is sufficient to specify for each story a "how to test" scenario. For example, suppose I have a story for Stackoverflow:
"As a user I can post a new question"
The "how to test" scenario could be:
"Click on a 'Ask Question' button, a form is displayed with a textarea for the question text and a textfield for tags. After the user enters both -they are mandatory- the user is redirected to the question list. The user can see the question title in the list, along with the tags"
So maybe a use case diagram is not really needed. I would recommend to try the "how to test" and see how it goes. It is very useful for the team because they know what you are expecting from the story, from a functional point of view. And you won't be doing documentation for every story.
If you don't like it, the go with the use case diagram, but it is a good idea to give the team something more than the story description.
Now, about the technical stories you mention. What are they? Why is a technical requirement mixed with the functional requirements? Maybe it IS a real requirement for the project, but usually it is not, and can be rewritten as a functional story. Unless your product is something like a framework or library.
For example, the technical story "create indices for the 'get questions' query" could be rewritten as "speed up the questions list page".
Comment: Thanks for your answer. Good to know the "How to test thing". Talking about the technical stories, in our projet we have to make a special algorithm to give some results. We have consider this as technical. Is this a technical story? I think that this part is involved in a user story as a part of its development, so I see it as a task... but I'm not sure. :S
Comment: Yes, in that case you probably have no choice but to specify it in technical terms. About the "how to test thing", you can also use it as a guideline for the demo at the end of sprint, and mark the story as "validated" if the test goes ok. And your team will also know what you expect at the demo.
Comment: Another question... at the end of a sprint, do we have to finish a story, or just some tasks of a story?? Gracias.
Comment: The whole story. From the point of view of the Product Owner, he got nothing if the whole story is not finished. If your story is too large to be done in a sprint, split it. Download this free PDF, it is very insightful and will give you many answers http://www.infoq.com/minibooks/scrum-xp-from-the-trenches
Answer: I only use class and sequence diagrams with Scrum because these two diagrams are live synchronized with the java code.
I certainly don't create UseCase or other diagrams or even try to generate code from diagram (e.g. MDD)  because as soon as something is changed in my project and my code it is really too painful to update my diagrams. Diagrams should be automatically updated without any human intervention. I did many project with Omondo EclipseUML and it worked really well.
Comment: If diagrams are mirrors of the code, why not look at the code instead? Diagrams make the programs no simpler. Modeling is for abstracting details, not for being happy about some pictures.
Comment: The code needs abstraction which is formalized and UML is the solution I use in my company. Don't forget that UML goal is to gives views of your architecture in which you can hide the not needed information. You can also add notes, comments and even constraints. What I do in my projects is to extract an UML model from the code, then keep going modeling at UML level, validate it and then put back it into the project. It means that I can manipulate my model without any code and decide what time to merge it. This is really marvelous and add real value to the code.
Answer: SCRUM is a application lifecycle management framework, not a methodology as you stated. Please refer to scrum.org
Use Cases are abstracted. If they help your team during refinement, then great. BUT once your team has committed to the story, change is welcomed and there is little point maintaining them once the story is done. The goal is always user acceptable working software!
Answer: UML state machine diagrams are useful in Scrum for projects focused on redesigning UI while retaining business logic:

State machine modeling is a dynamic modeling technique, one that focuses on identifying the behavior within your system-in this case, behavior specific to the instances of a single class. My style is to draw one or more state machine diagrams when a class exhibits different behavior depending on its state. For example, the Address class is fairly simple, representing data you will display and manipulate in your system. Seminar objects, on the other hand, are fairly complex, and therefore it makes sense to create a state machine diagram for them.

References

UML 2 State Machine Diagrams: An Agile Introduction


Should all files/folders in an installation be owned by the web server user?

Question: As in the title, should all files/folders in a Drupal 8 installation be owned by the web server user, e.g. the default www-data user for Apache?
As far as I know, the answer is yes at least in principle, so that all files/folders should have www-data as both owner and group, and more so because of logistics/minimalism/ease of management.
Is that correct or are there other considerations?
Comment: http://drupal.stackexchange.com/questions/373/what-are-the-recommended-directory-permissions is sort of the Drupal 7 version of this, slightly different angle of course as you're asking specifically about ownership. Be aware there's actually no right or wrong answer to what you're asking, posix (and beyond) permissions give you a lot of options to manage ownership/access to files. There are general good practices to follow though
Answer: Securing file permissions and ownership is the canonical reference for this topic, and is still relevant for Drupal 8.
If we are going under the assumption where we are talking about who owns these files, then we can also assume you have root on the machine and configure the entire environment the way you need.
Having "www-data" (or equivalent) own the entire DOCROOT of any website is an unnecessary security attack surface.  If there is a security breach (either through code or the webserver), then an attacker can change code on the site.
If you have root, then you don't need to explicitly use the UI for uploading or updating modules.  This is the only real reason to have www-data own the site.
The linked article has all of the details, but I always recommend

A normal user owns everything in DOCROOT, except for sites/default/files (or wherever your files are for your sites), the private, and tmp directories (and if possible private and tmp outside of DOCROOT).
Apache runs with a proper umask so that group write is on for files
The data directories have 2775 permission on them, so group ownership is retained
Your normal users is also in the www-data group, so drush / drupal console work as expected

The script in the linked article handles most of this; I usually create custom ones for my sites that do the same thing.


How to read this DMARC report? Why does Yahoo still reject mails from my server?

Question: I've got hMailServer set up on my server, which bulks-mails a newsletter to an opt-in subscriber base. I have set up DKIM signing, a SPF record explicitly giving my server permission to send email on behalf of my domain, and even a reverse DNS record. My senderscore.org rating is 97. And my mail is delivered happily to all my subscribers, except for the ones with Yahoo or Rocketmail addresses. Every email I send to these addresses gets rejected with the following message:

Remote server replied: 421 4.7.0 [TSS04] Messages from 23.102.x.x temporarily deferred due to user complaints - 220.127.116.11; see https://help.yahoo.com/kb/postmaster/SLN3434.html

This message is 100% false and misleading. Nobody has complained about mails from this server, because for the past week I have stopped sending to any Yahoo/Rocketmail addresses. And there's nothing temporary about it: this situation has been the same for about two weeks now. Every day or two I send a single probe mail to see if they've removed my server from their blacklist, but alas! Same bounce message. And there is literally nobody to talk to at Yahoo; they don't have any kind of customer service, let alone tech support.
So I figured I'd sign up for DMARC notifications, to see what Yahoo is getting upset about. Here's my most recent report:
<?xml version="1.0"?>
<feedback>
  <report_metadata>
    <org_name>Yahoo! Inc.</org_name>
    <email>email@example.com</email>
    <report_id>1562461153.62437</report_id>
    <date_range>
      <begin>1562371200</begin>
      <end>1562457599</end>
    </date_range>
  </report_metadata>
  <policy_published>
    <domain>mydomain.com</domain>
    <adkim>r</adkim>
    <aspf>r</aspf>

none

    <pct>100</pct>
  </policy_published>
  <record>
    <row>
      <source_ip>220.127.116.11</source_ip>
      <count>1</count>
      <policy_evaluated>
        <disposition>none</disposition>
        <dkim>pass</dkim>
        <spf>fail</spf>
      </policy_evaluated>
    </row>
    <identifiers>
      <header_from>mydomain.com</header_from>
    </identifiers>
    <auth_results>
      <dkim>
        <domain>mydomain.com</domain>
        <result>pass</result>
      </dkim>
      <spf>
        <domain>mydomain.com</domain>
        <result>softfail</result>
      </spf>
    </auth_results>
  </record>
  <record>
    <row>
      <source_ip>126.96.36.199</source_ip>
      <count>1</count>
      <policy_evaluated>
        <disposition>none</disposition>
        <dkim>pass</dkim>
        <spf>fail</spf>
      </policy_evaluated>
    </row>
    <identifiers>
      <header_from>mydomain.com</header_from>
    </identifiers>
    <auth_results>
      <dkim>
        <domain>mydomain.com</domain>
        <result>pass</result>
      </dkim>
      <spf>
        <domain>mydomain.com</domain>
        <result>softfail</result>
      </spf>
    </auth_results>
  </record>
  <record>
    <row>
      <source_ip>22.214.171.124</source_ip>
      <count>1</count>
      <policy_evaluated>
        <disposition>none</disposition>
        <dkim>pass</dkim>
        <spf>fail</spf>
      </policy_evaluated>
    </row>
    <identifiers>
      <header_from>mydomain.com</header_from>
    </identifiers>
    <auth_results>
      <dkim>
        <domain>mydomain.com</domain>
        <result>pass</result>
      </dkim>
      <spf>
        <domain>gmail.com</domain>
        <result>pass</result>
      </spf>
    </auth_results>
  </record>
  <record>
    <row>
      <source_ip>126.96.36.199</source_ip>
      <count>1</count>
      <policy_evaluated>
        <disposition>none</disposition>
        <dkim>pass</dkim>
        <spf>fail</spf>
      </policy_evaluated>
    </row>
    <identifiers>
      <header_from>mydomain.com</header_from>
    </identifiers>
    <auth_results>
      <dkim>
        <domain>mydomain.com</domain>
        <result>pass</result>
      </dkim>
      <spf>
        <domain>gmail.com</domain>
        <result>pass</result>
      </spf>
    </auth_results>
  </record>
  <record>
    <row>
      <source_ip>22.214.171.124</source_ip>
      <count>1</count>
      <policy_evaluated>
        <disposition>none</disposition>
        <dkim>pass</dkim>
        <spf>fail</spf>
      </policy_evaluated>
    </row>
    <identifiers>
      <header_from>mydomain.com</header_from>
    </identifiers>
    <auth_results>
      <dkim>
        <domain>mydomain.com</domain>
        <result>pass</result>
      </dkim>
      <spf>
        <domain>gmail.com</domain>
        <result>pass</result>
      </spf>
    </auth_results>
  </record>
  <record>
    <row>
      <source_ip>22.214.171.124</source_ip>
      <count>4</count>
      <policy_evaluated>
        <disposition>none</disposition>
        <dkim>pass</dkim>
        <spf>fail</spf>
      </policy_evaluated>
    </row>
    <identifiers>
      <header_from>mydomain.com</header_from>
    </identifiers>
    <auth_results>
      <dkim>
        <domain>mydomain.com</domain>
        <result>pass</result>
      </dkim>
      <spf>
        <domain>gmail.com</domain>
        <result>pass</result>
      </spf>
    </auth_results>
  </record>
  <record>
    <row>
      <source_ip>184.108.40.206</source_ip>
      <count>1</count>
      <policy_evaluated>
        <disposition>none</disposition>
        <dkim>pass</dkim>
        <spf>fail</spf>
      </policy_evaluated>
    </row>
    <identifiers>
      <header_from>mydomain.com</header_from>
    </identifiers>
    <auth_results>
      <dkim>
        <domain>mydomain.com</domain>
        <result>pass</result>
      </dkim>
      <spf>
        <domain>gmail.com</domain>
        <result>pass</result>
      </spf>
    </auth_results>
  </record>
  <record>
    <row>
      <source_ip>18.104.22.168</source_ip>
      <count>2</count>
      <policy_evaluated>
        <disposition>none</disposition>
        <dkim>pass</dkim>
        <spf>fail</spf>
      </policy_evaluated>
    </row>
    <identifiers>
      <header_from>mydomain.com</header_from>
    </identifiers>
    <auth_results>
      <dkim>
        <domain>mydomain.com</domain>
        <result>pass</result>
      </dkim>
      <spf>
        <domain>gmail.com</domain>
        <result>pass</result>
      </spf>
    </auth_results>
  </record>
  <record>
    <row>
      <source_ip>18.104.22.168</source_ip>
      <count>1</count>
      <policy_evaluated>
        <disposition>none</disposition>
        <dkim>pass</dkim>
        <spf>fail</spf>
      </policy_evaluated>
    </row>
    <identifiers>
      <header_from>mydomain.com</header_from>
    </identifiers>
    <auth_results>
      <dkim>
        <domain>mydomain.com</domain>
        <result>pass</result>
      </dkim>
      <spf>
        <domain>gmail.com</domain>
        <result>pass</result>
      </spf>
    </auth_results>
  </record>
  <record>
    <row>
      <source_ip>22.214.171.124</source_ip>
      <count>1</count>
      <policy_evaluated>
        <disposition>none</disposition>
        <dkim>pass</dkim>
        <spf>fail</spf>
      </policy_evaluated>
    </row>
    <identifiers>
      <header_from>mydomain.com</header_from>
    </identifiers>
    <auth_results>
      <dkim>
        <domain>mydomain.com</domain>
        <result>pass</result>
      </dkim>
      <spf>
        <domain>gmail.com</domain>
        <result>pass</result>
      </spf>
    </auth_results>
  </record>
  <record>
    <row>
      <source_ip>126.96.36.199</source_ip>
      <count>1</count>
      <policy_evaluated>
        <disposition>none</disposition>
        <dkim>pass</dkim>
        <spf>fail</spf>
      </policy_evaluated>
    </row>
    <identifiers>
      <header_from>mydomain.com</header_from>
    </identifiers>
    <auth_results>
      <dkim>
        <domain>mydomain.com</domain>
        <result>pass</result>
      </dkim>
      <spf>
        <domain>mydomain.com</domain>
        <result>softfail</result>
      </spf>
    </auth_results>
  </record>
  <record>
    <row>
      <source_ip>22.214.171.124</source_ip>
      <count>1</count>
      <policy_evaluated>
        <disposition>none</disposition>
        <dkim>pass</dkim>
        <spf>fail</spf>
      </policy_evaluated>
    </row>
    <identifiers>
      <header_from>mydomain.com</header_from>
    </identifiers>
    <auth_results>
      <dkim>
        <domain>mydomain.com</domain>
        <result>pass</result>
      </dkim>
      <spf>
        <domain>mydomain.com</domain>
        <result>softfail</result>
      </spf>
    </auth_results>
  </record>
</feedback>

The first thing I will draw your attention to is that there is no mention at all of my server's IP (23.102.x.x). I have no idea what these other servers (e.g. 184.108.40.206) are, or why they would be causing my server to be blacklisted. What is the meaning of this report? How can I get Yahoo to stop bouncing my mails?
UPDATE: fortunately, some teeny tiny little domain somewhere sent back a rejection message, telling me that I don't have a reverse DNS record. And there I thought I did! Turns out I followed the wrong advice from an Azure support agent, who told me to set up my own DNS zone for x.102.23.in-addr.arpa, and then to add a record there for the last quartet representing my server's IP address. In hindsight, I realized that obviously that doesn't make sense, because then I would effectively be controlling the PTR records for 255 other possible servers. So I reopened my support ticket with Azure, asking them to set up the PTR record. If that works, I'll post this as an answer.
UPDATE 2: I got support from Azure, and they helped me set up the reverse DNS record. So now when I run the following from a Linux prompt, I get the result as expected:

$ host 23.102.x.x
x.x.102.23.in-addr.arpa domain name pointer mail.mydomain.com

Unfortunately, Yahoo is still rejecting mails from my server. I have signed up for their feedback loop, and not received a single mail from them. But all my mails to yahoo address still bounce back with the same false and misleading error message. Is there anything else to be done?
Comment: You'll have to wait for the (negative) DNS TTL to expire before your changed DNS records are available everywhere.
Comment: @MichaelHampton The TTL of my SOA record is 3600. Refresh = 3600, Retry = 300, Expire = 2419200. So by now, they really should have refreshed...but apparently they haven't. At this writing, yahoo is *still* rejecting my mails.
Comment: What are your actual IP address, domain, SPF & DMARC records?
Comment: @MichaelHampton is that TTL a global standard, or does it depend on the recipient? Any idea how long that TTL is?
Comment: It's defined in your SOA record. Since you didn't specify what your domain is, you'll have to look up your own SOA record.
Answer: It is not unusual to find a number of freemail providers in your DMARC report.
For example, people receiving mail from you at their google address may choose to forward your mail to yahoo, leading yahoo to report those receipts back to you. The report actually includes a clue - saying SPF check passed for gmail.com. If the report did not include that information, you could still guess based on the whois information for the IP address - it is allocated to Google.
The "Nobody has complained" part makes me suspect that you have not setup a feedback loop with yahoo - they will only tell you about complaints after you sign your mail and explicitly opt in. You would know this if you had fully read the help pages referred to in the error message, so chances are Yahoo is deferring your message based on some other item in their "best practices" list. So this is your best bet at resolving the problem - verifying you have understood & implemented every single item on that list.
Comment: You were right; I had done everything on their "best practices" list, other than signing up for the feedback loop. So I signed up for the feedback loop, and I have not heard from them since. But they are *still* blocking mails from my server. :-( Any other ideas?
Comment: Please see updates to my question
Answer: So, the happy ending to my story is that a couple weeks after setting up my reverse PTR record correctly (with help from Azure support), Yahoo started getting the message. It wasn't instantaneous, mind you; it started with a handful of subscribers reporting that their email service had resumed. But still, the bulk of mails were rejected. Then slowly, slowly, the percentage of successful deliveries increased, until after a transition period of about two days, the bounces stopped altogether.
In summary, the answer was to set up the reverse DNS record...and wait.


Need help choosing languague for this project

Question: first of all, sorry for bad english. Please correct me if I write something wrong!
I'm a "noob" in the programing scene, so I need some help. I want to help my mom to automate a process at her bussines. The core thing I need to do are this:
I need to extract info from a webpage (it's an php webpage), and compare the products that arrive with the one's displayed in the webpage. I want to do that scanning the bar codes of the products (I've a database of all the products barcodes). Then I need to save the comparission in a file just to make sure that everything is ok. I want to know wich languague is better for my case. (Then I will try to do it, fail, learn from my mistakes and then have some "stable" program to do this)
TL;DR: I recive products, I check if everything arrived in a website. I want to do that using bar codes and "automate" the process. I want to know wich languague is better for my case.
Thank you!!
Comment: You'll never get a straight answer for "which language is best" - it all comes down to personal taste and experience. SO is aimed at asking questions with specific answers, not opinions.
Comment: the "best" language is always the one you can use the best.
Answer: As others pointed out in the coments, there is not best language, you need to chose the one that fits you.
But let me give you some recommendations on what might work.
You said that the site is already in PHP, that's the backend language. You should keep using it since a part of the site is already built with it. Other options are JavaScript using NodeJS, Python, Java, Ruby.
You can do almost everything you need in the backend (server side) using PHP, but some things might be better to solve them in the client side (front end) using JavaScript, is the default language that runs on the browsers.
Usually you use the backend language to serve pages, interact with a database, send data to the client. And the front end (JavaScript) to add dynamic functionality to your website.
Web apps used to depend a lot on the backend, reloading the page for every action, sending a lot of information back and forth.
The modern aproach to build web apps (like yours) is a bit more dependant on JavaScript. You load the page once and then just do AJAX (Asynchronous JavaScript and XML) requests to the server asking just for the information you need and showing it dynamicly with out reloading and having to load the HTML/CSS all over again. Many frameworks like Angular, React (with its whole ecosystem), help you a lot with it.
Read more about it here.
EDIT: just to clirify, I answered with some recommendations and opinions because it is what the question asks for.
Comment: Thank you man! That was what I wanted. Sorry if I did something wrong! Thankss


Most efficient coding style for forms with multiple radio buttons

Question: I am have a form that look something like this:

I want the input.variable I am going to throw into localStorage based on the number of boxes filled out and the radio boxes checked. It would apply as follows:
-Radio Buttons-
One Name Typed in:
na :  Name
F: Name and friend
F+ Name and friends
Two Names typed in:
na:  Name and Name
F:   Name, Name and friend
F+:  Name, Name and friends
Three Names typed in:
na: Name, Name and Name
F:  Name, Name Name and friend
F+: Name, Name, Name and friends
Four Names typed in:
na: Name, Name, Name and Name
F:  Name, Name, Name, Name and friend
F+: Name, Name, Name, Name and friends
What would be the best way to approach this? I am trying to think of the most efficient way to write this beyond multiple if/then/else statements.
Thanks
Comment: The best approach is thinking of a couple of ways to do what you want, and try them... what have you tried?
Comment: I am working on a mess of if/then statements that is turning into a nested nightmare. I was hoping there was a bit cleaner way to arrange the data.
Comment: if you want a clean way to arrange data, use an object literal. If you're dealing with a wash of `if elseif elseif` statements, consider using a `switch`, if all conditionals check a different value, just use `switch (true)`
Comment: +1 to you Elias.I just read up on switch, much appreciated.
Answer: Ok, since my comment seems to have pointed you in the right direction, I'm pasting it here as an answer:
if you want a clean way to arrange data, use an object literal. If you're dealing with a wash of if elseif elseif statements, consider using a switch, if all conditionals check a different value, just use switch (true)


Which variables do I need to export with Strongarm?

Question: I have a theme based on adaptivetheme, which uses the color selector tool to allow one to edit the theme's color scheme through the UI.
When exporting a feature using the theme, the following variables are available:

color_themename_files
color_themename_logo
color_themename_palette (gives the list of colors)
color_themename_stylesheets

If exporting color_themename_files, an array of files like the following is exported:
array(
  0 => 'public://color/omtheme-58e01b40/bullet-round.png',
  1 => 'public://color/omtheme-58e01b40/bullet-sm-arrow-right.png',
  2 => 'public://color/omtheme-58e01b40/bullet-sm-arrow-down.png',
  3 => 'public://color/omtheme-58e01b40/button.gif',
  4 => 'public://color/omtheme-58e01b40/button-o.gif',
);

Similarly, color_themename_logo gives:
array('value' => 'public://color/themename-5cbf1601/logo.png');

I know I want to export color_themename_palette since that's the list of colors.  Is there any reason to export the other three variables?
Answer: Yes if the paths match up exactly on the other setup.
No if the paths don't.
Ideally you want to avoid putting platform specific options into features/code as they might not be the same across multiple environments.
Answer: Searching the color module for variable_get reveals that color_themename_stylesheets is used in function _color_html_alter(), which is called by themes that can use the color module. Moreover, the value of that variable is not recreated automatically, when _color_html_alter() is called. This also holds for the other three variables.
So you have to export these variables if you want to have the theme properly colored out of the box. Of course you also have to make sure that the referenced files are in the correct place.


Form based Authentication based on Role in MVC

Question: I want to create Authentication based on Role using Form Authentication. Please Find my controller code below:-
<code>[HttpPost]
    public ActionResult Login(tblUser user)
    {
        DataClasses1DataContext dbcontext = new DataClasses1DataContext();
        List<Mvc4API.linqtosql.tblUser> lstuser = dbcontext.tblUsers.ToList();
        string message = string.Empty;
        bool userlogin = lstuser.Exists(x => x.UserName == user.UserName && x.Password == user.Password);

        if (userlogin)
        {
            FormsAuthentication.SetAuthCookie(user.UserName, true);
            //role = "BB";
            string Role = GetRoles(user.UserName);
            return RedirectToAction("InsertProduct", "Product");
        }
        else
        {
            message = "Invalid User";
        }
        ViewBag.Message = message;
        return View(user);
    }

    private string GetRoles(string UserName)
    {
        UserEntities userEntities = new Mvc4API.UserEntities();
        List<tblUser> lstuser = userEntities.tblUsers.ToList();
        List<tblRole> lstrole = userEntities.tblRoles.ToList();
        var role = from u in lstuser
                   join r in lstrole on u.RoleId equals r.Id
                   where u.UserName == UserName
                   select r.RoleName.ToString();
        string roletype = "";
        foreach (var item in role)
        {
            roletype = item.ToString();
        }

        return roletype;
    }
</code>
While redirecting my code as follows:-
<code>      [Authorize(Users="B,Test")] // This is working
    //[Authorize(Roles="Admin")] This is not working
    public ActionResult InsertProduct()
    {
        return View();
    }
</code>
Authentication based on Users is working but when I do it on Roles it is not working.
Please tell the changes I have to make in my code so that it can work.
Thanks,
Rahul
Comment: BTW you'd better delete all that code and never use it, not even as a demo. Storing unencrypted passwords is a **serious** security breach and a career-limiting snippet. MVC has its own well tested authentication and authorization mechanism. Create a new MVC application, select `Individual Accounts` in the `Change Authentication` dialog box and check how the login pages work
Comment: You never set any role. `string Role = GetRoles(user.UserName);` just stores a string in an unused variable
Comment: Thanks for replying, please tell how can I set a Role
Comment: Did you read the docs? Try any courses? SO isn't a discussion or a tutorial site. I'ts a Q&A site about specific questions. Did you try something and where is the code?
Comment: I am new to it, trying to develop test MVC application for practice
Answer: Found an answer, Just added the following code in Global.asax.cs
<code>protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
    {
        string rolename = string.Empty;
        if (FormsAuthentication.CookiesSupported == true)
        {
            if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
            {
                try
                {
                    string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                    string roles = string.Empty;

                    using (UserEntities entities = new UserEntities())
                    {
                        var roleid = entities.tblUsers.Where(u => u.UserName == username).Select(u => u.RoleId);

                        int role = 0;
                        foreach (int i in roleid)
                        {
                            role = i;
                        }

                        rolename = entities.tblRoles.Where(r => r.Id == role).Select(r=>r.RoleName).First().ToString();
                    }
                    e.User = new System.Security.Principal.GenericPrincipal(//, rolename.Split(';')); for more than one role
                       new System.Security.Principal.GenericIdentity(username, "Forms"),new String[] { rolename});
                }
                catch (Exception)
                {
                    //somehting went wrong
                }
            }
        }
    }
</code>


Inserting XML nodes using PLPGSQL

Question: I am using PLPGSQL to process a XML column called XMLland.
I have a column filled with information on land that I am not able to change but I can add to.
As part of a loop that I am aware is functoning, due to other statements, I am looking to insert some additional XML nodes. However I am not familiar with PLPGSQL specific functions. I am using REC to loop through the table.
An example of the current XML is
<area>
    <type>
        mixed
    </type>
    <population>
        10,000
    </population>
</area>

I am looking to insert a new node into
<tree>
    <height>
        20m
    </height>
    <density>
        6
    </density>
</tree>

Here is the update statement I am using
UPDATE "dbLand".tbl_duration
SET XMLland.modify('
insert <tree><height>rec.height</height><density>rec.density</density>    </tree> as first
into (/area)[1]')
WHERE referee = 'abc'

I am getting the error
    syntax error at or near "(" SET oidetails.modify('
Is this a syntax issue, or is not possible to use .modify() in PLPGSQL
Help greatly appreciated
Answer: It is whole wrong - You cannot to modify some parts of XML document with UPDATE statement - this statement can be used for modification of some column value of some table.
UPDATE table SET field WHERE constrains

XML documents in PostgreSQL are immutable - that means, you cannot to edit document, you have to create new changed document and old document should be replaced by new document. More - XML document in PostgreSQL is +/- string - you can modify XML like string.
postgres=# SELECT * FROM data;
┌───────────────────┐
│         d         │
╞═══════════════════╡
│ <area>           ↵│
│     <type>       ↵│
│         mixed    ↵│
│     </type>      ↵│
│     <population> ↵│
│         10,000   ↵│
│     </population>↵│
│ </area>           │
└───────────────────┘
(1 row)

postgres=# UPDATE data SET d = replace(d::text, '</area>',
'    <height>
       20m
    </height>
    <density>
       6
    </density>
 </area>')::xml;
UPDATE 1

postgres=# SELECT d FROM data;
┌───────────────────┐
│         d         │
╞═══════════════════╡
│ <area>           ↵│
│     <type>       ↵│
│         mixed    ↵│
│     </type>      ↵│
│     <population> ↵│
│         10,000   ↵│
│     </population>↵│
│     <height>     ↵│
│         20m      ↵│
│     </height>    ↵│
│     <density>    ↵│
│         6        ↵│
│     </density>   ↵│
│ </area>           │
└───────────────────┘
(1 row)

The PostgreSQL has not any special functions for any updates of XML functions. If you need it, then you can install plv8 - javascript engine for stored functions, and you can use any related functionality of javascript.

Inserting XML nodes using PLPGSQL


Problema criando SLUG no codeIgniter

Question: Olha só eu estou desenvolvendo o portal do meu selo musical, e estou tendo um problema bem chatinho.
Eu estou registrando as notícias, nomes de albums, nomes de artistas e por ai vai.
Quando registro no BD eu jogo em um campo o nome original do artista e no outro campo o nome para URL utilizando a função url_title.
O problema é que quando o nome do artista tem acentos especiais por exemplo: á ê ô í ú à, etc, ele salva o nome sem esse caractere, porém sem substituir por a e o i u, então o campo fica vazio e o nome incompleto, a URL não fica nada amigável.
Já tentei usar o str_replace porém não tive sucesso, ele substituiu os caracteres de formas erradas também.
Alguém pode me dar uma luz ou alguma solução?
Comment: Xim nes, tem como postar o código que já tem? assim fica mais fácil para quem for ajudar, já ter uma ideia do que você pretende fazer.
Answer: Consegui resolver rapaziada.
convert_accented_characters() é a função que não sabia que executa isso.
Abraços
Comment: Ótimo que conseguiu resolver, quando possível marque a sua resposta como aceita. =)
Comment: Recomendo concatenar seu slug gerado com um numero caso seu post se repita (caso esteja armazenado no banco de dados): ex `www.seusite.com/postagem/bolos-em-sao-paulo` `www.seusite.com/postagem/bolos-em-sao-paulo-2`
Comment: Valeu Mesmo a todos.E Jhonatan, eu to usando assim sim, só que essa sessão do site, seria nome de cds, então não teria um nome igual sacou? hehe
Answer: Obrigado pelas dicas! Resolvi um problema do nosso tema com essa dica!
Troquei a linha 85 - $slug =  $premium['slug']; que sempre dava erro de "Illegal string offset 'version'" por $slug =  convert_accented_characters($premium['slug']); no arquivo: class/Util/ValidateLicense.php
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Problema criando SLUG no codeIgniter


Qual a utilidade / razão da existência de new Object();?

Question: Enquanto estudava um pouco mais sobre objetos, me deparei com coisas como new String , new Number, etc.
Fiquei curioso, e fui aprender. Entendi o funcionamento, apesar de ter minhas dúvidas sobre a utilidade dos mesmos, haja visto que meu conhecimento ainda não é muito grande. Mas até aí, tudo bem.
Então me deparei com o new Object(). Fiquei confuso. Pensei que se ele existe, deve haver uma diferença ao invés de declarar com um simples {}, mas ao que parece, não há.
Se não há diferenças entre fazer um e fazer outro, qual a utilidade da sintaxe mais longa? Qual a razão pela qual esse construtor foi criado?
Comment: Nessa própria pergunta, a resposta aceita diz que usar `new Object()` era "coisa de dinossauros pedantes". Se é algo "inútil", por que existe?
Comment: Relacionada (SOen): [What is the difference between `new Object()` and object literal notation?](https://stackoverflow.com/q/4597926/1452488)
Comment: Eu já li essa pergunta, e não creio que seja uma duplicata. Sei a diferença entre Object.create e new Object, estou perguntando a diferença entre `x = {}` e `x = new Object();`. Aliás, a pergunta seria, se não há diferença entre os dois, por que existe o `new Object();`.
Comment: Relacionado: [Qual é o significado desta definição de valores](https://pt.stackoverflow.com/questions/68668/qual-é-o-significado-desta-definição-de-valores/68681#68681)
Answer: A pergunta deveria ser "por que não deveria ter new Object()?".
Ao contrário do que muita gente pensa (mesmo que diga que não pensa assim), a construção da linguagem segue uma lógica, tem uma gramática.
Isso é bom para o programador (de verdade) aprender mais facilmente e poder usar a intuição (com muito cuidado) para entender tudo como funciona nela, e pode ser mais fácil usar. É o mesmo de aprender uma língua normal (eu sei que muitos só decoram palavras e frases, mas muitos vão evoluindo o conhecimento de forma natural e progressiva, sempre entendendo o que está falando, o que faz com que ela entenda o todo, o conceito e não apenas as palavras, afinal se não for assim é uma forma de analfabetismo funcional), salvo regras de exceção necessárias por algum motivo as construções seguem uma lógica.
Também é bom para a construção do compilador que precisa tratar tudo de forma consistente e linear, ou seja, não precisa ficar inventando regras fora do normal sem necessidade.
Então se você pode usar o construtor para diversos objetos específicos para outros tipos, porque não deveria poder usar para o objeto genérico? Pra que fazer a exceção disso? Toda exceção precisa ser justificada. Criaram o construtor, não o construtor de Object.
Lembrando que pode (ou não) passar um parâmetro para esta função construtora. Em outros tipos é bastante comum que tenha parâmetros e faz muito mais sentido. Aliás, o literal dos outros tipos é justamente new <Tipo>([param]). Novamente, pra que esconder o construtor de um tipo específico? Então nem sempre são idênticos.
Não deveria, mas alguém poderia sobrepor o Object padrão em alguma situação anormal. E tem diferença pra uso normal. Se não tivesse nada diferente alguém poderia argumentar para não usar algo que é claramente pior (e aparentemente é pior até em performance, pelo menos em alguma implementação e situação específica), mas seria ideologia.
Vendo uma resposta aqui que diz que ambos são equivalentes, significa ser semanticamente equivalente, não que dê o mesmo resultado (isso até dá) e da mesma forma.
É uma questão de simetria. A construção de linguagens, especialmente de programação, precisam ser pragmáticas, você ganhou ele "de graça" e para não ter haverá um custo, então melhor deixar ali. Vai que alguém acha um motivo pra usar, ou arrumem uma otimização ou função que não muda a semântica do seu uso padrão e legado porém fornecendo alguma vantagem?
Existe por pragmatismo. Retirá-lo seria ideologia.
Coloquei no GitHub para referência futura.


Ubercart - different payment gateway settings per product

Question: i want to be able to set one product as UC_CREDIT_AUTH_ONLY, meaning no charge will be made now. in the admin i can only change this setting globally, meaning that all my products will be charged UC_CREDIT_AUTH_ONLY. How can i get this to work only for one?
currently i'm using paypal website pro as gateway, but if i have to, i'll switch to athorize.net.
using drupal 6 + ubercart 2
Thank you.
Answer: There is a sandbox project for multiple gateways. I attempted to contact the developer a few days ago, but haven't heard back.
http://drupal.org/node/1106004
you select the profile in the product edit. Its not complete but close.


Debug a flawed solution to a problem on independence and orthogonality

Question: From Exercise $24$ in Tao's note: https://terrytao.wordpress.com/2015/10/12/275a-notes-2-product-measures-and-independence/comment-page-2/#comment-682699
Let ${X}$ be a random variable taking values in ${{\bf R}^n}$ with the Gaussian distribution, in the sense that
$\displaystyle \mathop{\bf P}( X \in S ) = \int_S \frac{1}{(2\pi)^{n/2}} e^{-|x|^2/2}\ dx$
(where ${|x|}$ denotes the Euclidean norm on ${{\bf R}^n})$, and let ${v_1,\dots,v_m}$ be vectors in ${{\bf R}^n}$. Show that the random variables ${X \cdot v_1, \dots, X \cdot v_m}$ (with ${\cdot}$ denoting the Euclidean inner product) are jointly independent if and only if the ${v_1,\dots,v_m}$ are pairwise orthogonal.
Attempt: For fixed Borel subsets $S_1, \dots, S_m \subset {\bf R}$, and $V = \begin{pmatrix} v_1 \\ \vdots \\ v_m \end{pmatrix} \in M_{m \times n}(\bf R)$, the unsigned r.v $\prod_{i=1}^m 1_{S_i}(X \cdot v_i)$ equals the unsigned r.v $1_{\prod_{i=1}^m S_i}(VX)$ (in the sense that two functions are equal), so their expectations should match:
$E\prod_{i=1}^m 1_{S_i}(X \cdot v_i) = E1_{\prod_{i=1}^m S_i}(VX)$.
By the change of variables formula, RHS $= \int_{{\bf R}^m} 1_{\prod_{i=1}^m S_i}(x)\ d\mu_{VX}(x) = \mu_{VX}(\prod_{i=1}^m S_i)$, and similarly by Fubini and Tonelli  LHS $= \prod_{i=1}^m E1_{S_i}(X \cdot v_i) = \prod_{i=1}^m \int_{\bf R} 1_{S_i}(x)\ \mu_{X \cdot v_i}(x) = \prod_{i=1}^m \mu_{X \cdot v_i}(S_i)$, where $\mu_{VX}, \mu_{X \cdot v_i}$ are the laws of the r.v $VX$ and $X \cdot v_i$, respectively, and thus we get independence.
This argument is clearly false as it completely ignores the orthogonality condition and the distribution of $X$, can someone points out where it went wrong, and possibly suggests a further direction without the use of things like covariance matrix? (the notion of variance is not even introduced at this point in the original context).
Comment: For the left-hand side, you switched the order of $E$ and $\prod_{i=1}^m$. How do you justify this?
Comment: @angryavian: By Fubini and Tonelli theorem, if ${X}$ and ${Y}$ are random variables taking values in ranges ${R, R'}$ respectively, then

$\displaystyle {\bf E} F(X) G(Y) = ({\bf E} F(X)) ({\bf E} G(Y))$

for any scalar functions ${F,G}$ on ${R,R'}$ respectively, provided that ${F(X)}$ and ${G(Y)}$ are either both unsigned, or both absolutely integrable.
Comment: I see you are quoting from Equation (8) in Tao's blog post. I believe the sentence should read "if $X$ and $Y$ are *independent* random variables..."; notice in the next sentence he mentions "the converse is not true; (8) does not necessarily imply independence" [paraphrasing]. Going back to (8), it might be that the independence of $X$ and $Y$ was established in the previous paragraphs, but I agree it is written ambiguously.
Comment: @angryavian: Thanks for the feedback. Do you have any suggestion then on the correct direction to try?
Answer: I'll assume the $v_i$ are nonzero to avoid some annoying edge cases.

Suppose $v_i$ are pairwise orthogonal. Then $m \ne n$. Let $u_i := v_i / \|v_i\|$. Extend $u_1, \ldots, u_m$ to an orthonormal basis $u_1, \ldots, u_m, \ldots, u_n$ for $\mathbb{R}^n$. Let $U$ be the $n \times n$ orthogonal matrix with columns $u_1, \ldots, u_n$. Let $Y = U^\top X$. Then using rotational invariance of the standard Gaussian distribution, we have
\begin{align}
P(Y \in S) &= P(U^\top X \in S)
\\
&= \int_{\{x : U^\top x \in S\}} (2\pi)^{-n/2} e^{-\|x\|^2/2} \, dx
\\
&= \int_S (2\pi)^{-n/2} e^{-\|Uy\|^2/2} \, dy
& y=U^\top x
\\
&= \int_S (2\pi)^{-n/2} e^{-\|y\|^2/2} \, dy
& \|Uy\|^2 = \|y\|^2
\\
&= P(X \in S).
\end{align}
For measurable sets $S_1, \ldots, S_m \subseteq \mathbb{R}$,
\begin{align}
&P\left(\bigwedge_{i=1}^m \{X \cdot v_i \in S_i\}\right)
\\
&= P\left(\bigwedge_{i=1}^m \{X \cdot u_i \in S_i / \|v_i\|\}\right)
\\
&= P\left(\bigwedge_{i=1}^m \{Y_i \in S_i / \|v_i\|\}\right)
\\
&= \int_{\{y : y_i \in S_i / \|v_i\|\}} (2\pi)^{-n/2} e^{-\|y\|^2/2} \, dy
\\
&= \prod_{i=1}^m \left(\int_{S_i / \|v_i\|} (2\pi)^{-1/2} e^{-y_i^2/2} \, dy_i\right)
\cdot \prod_{i=m+1}^n \underbrace{\left(\int_{\mathbb{R}} (2\pi)^{-1/2} e^{-y_i^2/2} \, dy_i\right)}_{=1}
\\
&= \prod_{i=1}^m P(Y_i \in S_i / \|v\|_i)
\\
&= \prod_{i=1}^m P(X \cdot u_i \in S_i / \|v\|_i)
\\
&= \prod_{i=1}^m P(X \cdot v_i \in S_i)
\end{align}

Sketch for the converse:
Suppose $X \cdot v_1$ and $X \cdot v_2$ are independent. Again let $u_i := v_i / \|v_i\|$. Using a similar rotation argument as above, you can show that $X \cdot u_i$ are each standard univariate Gaussian. Then
\begin{align}
&P(X \cdot v_1 \in S_1)P(X \cdot v_2 \in S_2)
\\
&= P(X \cdot u_1 \in S_1 / \|v_1\|)P(X \cdot u_2 \in S_2 / \|v_2\|)
\\
&= \left(\int_{S_1 / \|v_1\|} (2\pi)^{-1/2} e^{-y_1^2/2} \, dy_1\right)
\left(\int_{S_2 / \|v_2\|} (2\pi)^{-1/2} e^{-y_2^2/2} \, dy_2\right).
\tag{$*$}
%\\
%&= \iint_{(S_1 / \|v_1\|) \times (S_2 / \|v_2\|)} (2\pi)^{-1} e^{-(y_1^2+y_2^2)/2} \, dy_1 \, dy_2.
\end{align}
However, by a similar rotation argument as above, you can without loss of generality assume $u_1 = (1, 0, \ldots, 0)$ and $u_2 = (\cos \theta, \sin \theta, 0, \ldots, 0)$ for $\cos \theta = u_1 \cdot u_2$. Then,
\begin{align}
&P(\{X \cdot v_1 \in S_1\} \land \{X \cdot v_2 \in S_2\})
\\
&= P(\{X \cdot u_1 \in S_1 / \|v_1\|\} \land \{X \cdot u_2 \in S_2 / \|v_2\|\})
\\
&= \iint_{\{(x_1, x_2) : x_1 \in S_1 / \|v_1\|, x_1 \cos \theta + x_2 \sin \theta \in S_2 / \|v_2\|} (2\pi)^{-1} e^{-(x_1^2+x_2^2)/2} \, dx_1 \, dx_2
\\
&= \int_{S_1 / \|v_1\|}
(2\pi)^{-1/2} e^{-y_1^2/2}
\int_{S_2 / \|v_2\|}
(2\pi \sin^2 \theta)^{-1/2} e^{-((y_2 - y_1 \cos \theta)/\sin \theta)^2/2}
\, dy_2 \, dy_1
& (y_1 = x_1, y_2 = x_1 \cos \theta + x_2 \sin \theta)
\end{align}
This equals ($*$) above only when $\cos \theta = 0$, i.e. when $v_1$ and $v_2$ are orthogonal.
Comment: Does the split of the integral over product space into product of integrals follow from Fubini and Tonelli?


Is there a safe way to force an IIS log file rollover on a production web server?

Question: I often have to look at problems on live web servers, would like to know if there is a safe way to force an IIS log file rollover on a production server.
Answer: You could try temporarily changing the log file rollover settings, as described here:
http://technet.microsoft.com/en-us/library/cc754615(WS.10).aspx
Once the logs have rolled over, revert to your previous settings.
Answer: Are you sure about this, I've been supporting IIS web farms for years and had no issues with copying the current IIS log file to get all entries up to that point....(IIS 4,5,6 and 7)
How are you copying them?
Comment: I often use Symantect pcAnywhere to copy the files, so perhaps it's something peculiar to that program that's causing me problems.  I'll edit the question slightly but I'd still like to know if there's a way to force a log file rollover, this sort of functionality is common in the UNIX world and SQL Server also has it.
Answer: If you have the ability to take the server out of rotation, or you're working on a test server, then one option is to rename the current log file. IIS will then create a new one. For example, if you want to capture logs for one hour without having to filter them out of a larger file:

Take server out of rotation and stop IIS
Rename the latest log file
Start IIS, put server back into rotation
IIS creates a new log file
Wait one hour
Copy the latest log file, and you have a file with one hour of log data


Enviar varios files em um form

Question: como fazer para esse codigo enviar mais de uma imagem em diferentes inputs
<form name="myForm" method="POST" action="back_img.php" enctype="multipart/form-data">
                    <input type="hidden" name="id" id="id" value="<?php echo $result['id'];?>">
                    <input name="arquivo" id="arquivo" type="file">
<input name="arquivo1" id="arquivo" type="file">

                        Alterar

<?php
include '../conexao_banco.php';
// verifica se foi enviado um arquivo
if(isset($_FILES['arquivo']['name']) && $_FILES["arquivo"]["error"] == 0)
{

    echo "Este arquivo é do tipo: " . $_FILES['arquivo']['type'] . "
";

    $arquivo_tmp = $_FILES['arquivo']['tmp_name'];
    $nome = $_FILES['arquivo']['name'];

    // Pega a extensao
    $extensao = strrchr($nome, '.');

    // Converte a extensao para mimusculo
    $extensao = strtolower($extensao);

    // Somente imagens, .jpg;.jpeg;.gif;.png
    // Aqui eu enfilero as extesões permitidas e separo por ';'
    // Isso server apenas para eu poder pesquisar dentro desta String
    if(strstr('.jpg;.jpeg;.gif;.png', $extensao))
    {
        // Cria um nome único para esta imagem
        // Evita que duplique as imagens no servidor.
        $novoNome = md5(microtime()) . '.' . $extensao;

        // Concatena a pasta com o nome
        $destino = '../img_usuario/' . $novoNome;

        // tenta mover o arquivo para o destino
        if( @move_uploaded_file( $arquivo_tmp, $destino  ))
        {
            echo "Arquivo salvo com sucesso em : " . $destino . "
";
            echo "";

          try {
            $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
            // set the PDO error mode to exception
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            // prepare sql and bind parameters
            $stmt = $conn->prepare("UPDATE user SET arquivo=:arquivo WHERE id=:id;");

            $stmt->bindParam(':arquivo', $novoNome);
            $stmt->bindParam(':id', $_POST['id']);
            $stmt->execute();

            echo '';
            exit;
            }
        catch(PDOException $e)
            {
            echo "Ops... Erro no servidor: ".$e->getMessage();
            }

        }
        else
            echo "Erro ao salvar o arquivo. Aparentemente você não tem permissão de escrita.
";
    }
    else
        echo "Você poderá enviar apenas arquivos \"*.jpg;*.jpeg;*.gif;*.png\"
";
}
else
{
    header('Location: pag_user.php');
}

?>

Answer: Você pode acessar aos vários uploads através de um foreach, ou então, se preferir, acessar manualmente (Exemplo: $_FILES['arquivo'], $_FILES['arquivo1']...)
Caso queira fazer um foreach, pode fazer algo parecido com:
    foreach ($_FILES as $file) {
         $arquivo_tmp = $file['tmp_name']; // equivale a $_FILES['arquivo']['tmp_name'];
    //resto do código

    }

Answer: Você pode colocar o atributo multiple no seu input para selecionar mais de um arquivo em um único input, ficando assim
<form name="myForm" method="POST" action="back_img.php" enctype="multipart/form-data">
                    <input type="hidden" name="id" id="id" value="<?php echo $result['id'];?>">
                    <input name="arquivo" id="arquivo" type="file" multiple>

Desta forma você pode selecionar mais de um arquivo em um mesmo input. Só tome cuidado com o tamanho dos arquivos a serem enviados para não ultrapassar o valor permitido de acordo com sua hospedagem.

Enviar varios files em um form


Data save for an android app after it uninstall or force data clear from settings

Question: I want to give the user some point when they first install the app (but I want it to device specific). It means if he uninstalls and re-installs he will not get that point again. I have found below methods:

Keep device previous data in shared preferences which will be deleted if I release an updates of the app
Store previous data in sql database but if user clears data from settings it will be lost
Create a file in SDcard store data, saving that file in a folder with <code>.foldername</code> and check the file value, problem is that the user can delete it
Every time the user opens the app it sends device id to server, server will check it is previously stored or not before giving point. Problem is that server maintenance should be  avoided.

Other than these 3 methods is there any other method?
Can you suggest me any other way,
or can you please tell me if there is no other method which would be better for 3 and 4?
Answer: Variation of 4.
using Google's backup servers, however the user can delete the data through his system settings.
Comment: @KishorDgupta is it working for your need? i am also having same use case?
Comment: nope :/ had to go with option 4. no other way works better


Magento Admin Questions

Question: Which is the right tag for asking questions that are related to adminhtml programming and configuration questions?
Answer: This is a very good question. To my mind:

backend question should be related to backend programming, not admin interface
adminhtml should be related to admin interface modifications
administration or configuration should refer to admin interface howto's.
Answer: I believe the tag backend would be right for the backend interface and adminhtml should be used for anything regarding backend coding.
This way you have a clear distinction between backend coding and backend interface like System -> Configuration and Catalog -> Manage Products questions

Magento Admin Questions