SQL Server not showing correct week numbers for given date

Question: SQL Server is showing week 53 for first week of 2011 except 1th of January, and needs to be week 1.
Below is the query and output:
declare @T table (dt datetime)
insert into @T values
('2010-12-26'),
('2010-12-27'),
('2010-12-28'),
('2010-12-29'),
('2010-12-30'),
('2010-12-31'),
('2011-01-01'),
('2011-01-02'),
('2011-01-03'),
('2011-01-04'),
('2011-01-05'),
('2011-01-06'),
('2011-01-07'),
('2011-01-08')
select dt,DATEPART(wk,dt) from @T

Output:
2010-12-26 00:00:00.000 53
2010-12-27 00:00:00.000 53
2010-12-28 00:00:00.000 53
2010-12-29 00:00:00.000 53
2010-12-30 00:00:00.000 53
2010-12-31 00:00:00.000 53
2011-01-01 00:00:00.000 1
2011-01-02 00:00:00.000 2
2011-01-03 00:00:00.000 2
2011-01-04 00:00:00.000 2
2011-01-05 00:00:00.000 2
2011-01-06 00:00:00.000 2
2011-01-07 00:00:00.000 2
2011-01-08 00:00:00.000 2

I want SQL Server to show week 1 from Dec 26th - Jan 1th. Does anybody know how to accomplish this?
Thanks and regards,
Aschwin.
Answer: It was alot harder than I first expected. I am comparing the end of last year to see if it is qualified to be part of the new year. If so i set the week as 1, otherwise i just use the normal week.
declare @T table (dt datetime)
insert into @T values
('2010-12-25'),
('2010-12-26'),
('2010-12-27'),
('2010-12-28'),
('2010-12-29'),
('2010-12-30'),
('2010-12-31'),
('2011-01-01'),
('2011-01-02'),
('2011-01-03'),
('2011-01-04'),
('2011-01-05'),
('2011-01-06'),
('2011-01-07'),
('2011-01-08'),
('2011-12-31'),
('2012-01-01')

select dt,
week = case when dt + 6 - datediff(day, -1, dt) % 7 = dateadd(year, datediff(year,-1, dt), 0)
then 1 else datepart(week, dt) end from @t

Proof:
https://data.stackexchange.com/stackoverflow/q/110527/
Answer: I am not sure it holds for all years (but it looks like it) but you could solve this using a CASE statement.
SELECT  dt
        , CASE  WHEN DATEPART(wk, dt) <> 53
                THEN DATEPART(wk, dt)
                ELSE 1
          END
FROM    @T

The new ISO_WEEK datepart doesn't apply to your requested output.
Answer: I Created 2 functions to deal with this issue
1) to get First or last day of the week
2) to get the week number or year
function 1
    CREATE FUNCTION [dbo].[fn_GetDayOf]
(
    @Date datetime,
    --@FirstDayOfWeek int = 7,
    @Mode int =1
)
/*
    Mode 1: First Day Of Week
    Mode 2: Last Day Of Week
*/

RETURNS datetime
WITH EXECUTE AS CALLER
BEGIN
    Declare @Return datetime

    --SET DATEFIRST @FirstDayOfWeek

    IF @Mode = 1
    BEGIN
        select @Return = dateadd(day,-(datepart(weekday,@date)-1),convert(date,@date))
    END
    ELSE IF @Mode = 2
    BEGIN
        select @Return = dateadd(SECOND,-1,convert(datetime,dateadd(day,(datepart(weekday,@date)),convert(date,@date))))
    END
    ELSE
    BEGIN
        SET @Return = @Date
    END
    --SET DATEFIRST 7

    RETURN @Return
END

Function 2
    CREATE FUNCTION [dbo].[fn_GetYearWeek]
(
    @Date datetime,
    --@FirstDayOfWeek int = 7,
    @Mode int =1
)
/*
    Mode 1 = Week Number
    Mode 2 = Year
*/
RETURNS INT
BEGIN
    declare @Return int
    IF @Mode = 1
    BEGIN
        select @Return = case when  datepart(week,[dbo].[fn_GetDayOf] (@Date,1)) <> datepart(week,[dbo].[fn_GetDayOf] (@Date,2)) then datepart(week,[dbo].[fn_GetDayOf] (@Date,1)) else datepart(week,[dbo].[fn_GetDayOf] (@Date,2)) end
    END
    ELSE IF @Mode = 2
    BEGIN
        select @Return = case when  datepart(WEEK,[dbo].[fn_GetDayOf] (@Date,1)) <> datepart(week,[dbo].[fn_GetDayOf] (@Date,2)) then datepart(YEAR,[dbo].[fn_GetDayOf] (@Date,1)) else datepart(YEAR,[dbo].[fn_GetDayOf] (@Date,2)) end
    END
    ELSE
    BEGIN
        SET @Return = -1
    END

    Return  @Return
END

Running Example
declare @T table (dt datetime)
insert into @T values
('2010-12-25'),
('2010-12-26'),
('2010-12-27'),
('2010-12-28'),
('2010-12-29'),
('2010-12-30'),
('2010-12-31'),
('2011-01-01'),
('2011-01-02'),
('2011-01-03'),
('2011-01-04'),
('2011-01-05'),
('2011-01-06'),
('2011-01-07'),
('2011-01-08'),
('2011-12-31'),
('2012-01-01'),
('2012-01-02'),
('2012-12-31'),
('2013-01-01')

select
    dt,
    datepart(week,dt),
    --case when  datepart(week,[dbo].[fn_GetDayOf] (dt,1)) <> datepart(week,[dbo].[fn_GetDayOf] (dt,2)) then datepart(week,[dbo].[fn_GetDayOf] (dt,1)) else datepart(week,[dbo].[fn_GetDayOf] (dt,2)) end
    [dbo].[fn_GetYearWeek] (dt,1),
    [dbo].[fn_GetYearWeek] (dt,2)
from @T

result:
Answer: Another way to retrieve the total number of weeks in current year:
DECLARE @LASTDAY DATETIME
DECLARE @weeks INT
SET @LASTDAY = DATEADD(ms,-3,DATEADD(yy,0,DATEADD(yy,DATEDIFF(yy,0,GETDATE())+1,0)))
SELECT @weeks = CASE DATEname(dw,@LASTDAY)

    WHEN 'MONDAY' THEN DATEPART(WK, DATEADD(wk,DATEDIFF(wk,7,@LASTDAY),5))
    WHEN 'TUESDAY' THEN DATEPART(WK, DATEADD(wk,DATEDIFF(wk,7,@LASTDAY),5))
    WHEN 'WEDNESDAY' THEN DATEPART(WK, DATEADD(wk,DATEDIFF(wk,7,@LASTDAY),5))
    ELSE DATEPART(WK, @LASTDAY)
END
select @weeks


Add class to pagination previous/next button in view Drupal 8

Question: how to add class to pagination previous/next/first/last button in view Drupal 8. Also how to show
First last next previous button default as default is show next/last
Answer: One way to add a class to Views pagers is to add the class to the template.
You can copy the template file from /web/core/modules/views/templates/ into your theme's templates folder and add the classes however you like.
The mini pager template is views-mini-pager.html.twig.


How to define sample space for discrete random variable

Question: If $S$ is the sample space of some discrete random variable $X$, what is usually given as its superset? $S \subset \mathbb{R}$ or $S \in \mathbb{Q}$? The $X$'s I have are digitized biomedical data.
Edit
I'm writing an introduction to biomedical data analysis. As a part of it, I must provide some introduction to statistics. The reason I came to ask this is that I don't know statistics very well myself. Anyway, I was assigned to write this up so I'm trying to do it the right way, and learn something myself too.
So, like I wrote the situation is that I have some digitized biomedical data. There was some continuous signal that was sampled (thus its discrete in time) and then quantized (after which the signal may have only certain discrete values).
My sample space is the set of values the signal may take. Usually one sample is presented with 16 bits, so there's 65536 possible values. However, the sample values are not presented as integers but decimal values like 0.101 or 0.521.
The confusion came from that in principal there the one-to-one mapping like you have written but clearly 0.101 is not an integer.
I don't have very strong mathematical / statistical background, so I'm pretty much learning the basics still (for the data I have I am just the "end user").
Comment: What definition of "sample space" are you using?  Why would the answer to this question matter in your application?
Comment: For something to be discrete, it must be in one-to-one correspondence with a subset of $\mathbb{Z}$. Taking your question at face value, I think that's your answer. But, like whuber, I'm unsure whether that's what you're asking (and, if so, why?).
Comment: Please, visit our [help page](http://stats.stackexchange.com/contact/user-merge) in order to merge and register your accounts.
Comment: Most people would not think of a "signal" that has $2^{16}$ possible values as discrete. As far as the sample space goes, it may be more fruitful to think of your sample space as being the set of all possible (discretized) *signal patterns* over time. That's a huge set, potentially infinite (if you allow unbounded lengths of time). You need to be *very* clear that a "random variable"--your $X$--is a *numeric property* of elements in the sample space. *E.g.*, $X$ could be the amplitude of a particular Fourier coefficient of a signal.
Comment: You also might find it helpful conceptually to construct a sample space of *idealized* (not digitized) signals. These might be real-valued functions of specified time intervals. The process of obtaining and digitizing the signal can be thought of as *measurement* of the true underlying signal. This invites you to analyze your situation into stages we can schematize as (underlying physico-mathematical model)-->(set of possible measurements)-->(values of a random variable)-->(data). Statistics is a rational process of going back along this chain to draw conclusions about its earlier stages.
Answer: If it is actually discrete, then it should be possible to place your sample space in one-to-one correspondence with (some subset of) $\mathbb{Z}$. That's more or less the definition of discrete.
However, the actual values a discrete random variable takes can come from anywhere. The sample space for the roll of a dice is $S = \{1,2,3,4,5,6\}$ and the individual values are obviously integers too. On the other hand, suppose you bin circular data into four quadrants. The centers of your bins might be at $S = \{45^{\circ}, 135^{\circ}, 225^{\circ}, 315^{\circ}\}$, which are also in $\mathbb{Z}$. If you convert them to radians, then $S = \{ \frac{\pi}{4}, \frac{3\pi}{4},  \frac{5\pi}{4} \frac{7\pi}{4} \}$, which are clearly in $\mathbb{R}$, but not $\mathbb{Z}$ or $\mathbb{Q}$, but it is pretty easy to map them back onto $\mathbb{Z}$--just divide by $\frac{\pi}{4}$.
I can't think of a situation where you would care too much about what set $S$ was a subset of, but the correspondence might be useful if you need to show that something is discrete.
Comment: We need to be careful with definitions. To illustrate (with an important practical example): let the sample space $S$ be the set of all countable binary sequences and let $X:S\to\mathbb{Z}$ be the number of initial zeros. Endow $S$ with a probability measure in the usual way (by thinking of its elements as outcomes of iid coin flips). Although the *random variable* $X$ is discrete, the *sample space* has cardinality $\aleph_1$ which is not in one-to-one correspondence with $\mathbb{Z}$.
Comment: The domain of a RV (as a formal function) is, by definition, the sample space itself. Associated with an RV $X$ is its *distribution,* which is a measure on the Real line. By definition, $X$ is discrete when its distribution is the sum of at most a countable infinity of "atoms" ("jumps" or "point measures" if you like). The locations of these atoms are the values that $X$ can ["take"](http://www.stat.yale.edu/Courses/1997-98/101/ranvar.htm). One subtlety is that the range of $X$ (as a function) could still be uncountable; *discreteness is partly a property of the probability measure on* $S$.
Comment: Here's a nice example for the space of binary (heads-tails) sequences where H and T have equal and independent probabilities at each step. Let $X$ be the limit superior of the fraction of heads. With probability $1$, $X$ takes the value $1/2$: its distribution is an atom of weight $1$ at $1/2$. (That's the Strong Law of Large Numbers.) However, $X$ (as a function from $S$ into $\mathbb{R}$) attains *all* values between $0$ and $1$ inclusive: an uncountable infinity of possibilities. But the *probability* of any of these values, or of any measurable subset of them, is zero.
Comment: I *think* I follow--it's actually the distribution (which is something like the image?) that has to have a one-to-one correspondence with a subset of integers? That is, there must be a finite/countably infinite number of values with non-zero probability?

Thanks for the explanation (and your patience!)
Comment: Would it be better to say that if a random variable is discrete, then its domain is in bijection with $\mathbb{Z}$? I must confess I'm a little hazy on the difference between sample space and the domain of an r.v.


Blur image with pixastic and set it as background with jquery

Question: i have a problem that is bothering me form 2 days.
I'm developing a little music sharing site and i have a problem making the design for the player.
I want to apply a blurred image background to a div with CSS and with the blur begin applied on the image via JS all with pixastic js library. The problem is that pixastic gives me a HTMLImageElement witch i can't apply to a css with $('.footer').css('background', "url(" + img.toDataURL("image/png")+ ")" }); since toDataURL works only with canvas elements.
How can i do that?
My code so far is:
 var img = new Image();
    img.src = '<?php echo $hd ?>';
    img.onload = function() {
    Pixastic.process(img, "blurfast", {amount:1});
    }

    $('.footer').css('background', "url(" + img.toDataURL("image/png")+ ")" });

The $hd is a http url that points to an album artwork using lastfm API
Answer: I'm not sure about first argument of css method and why you dont use img.src as url of image? Try something like this:

$('.footer').css('background-image', 'url(' + img.src + ')');

Ok I found probably answer on documentation:
var options = {};
Pixastic.process(image, "action", options);
options.resultCanvas; // <- holds new canvas

So in your case it would be:
var img = new Image(),
    options = {};

options.amount = 1
img.src = '<?php echo $hd ?>';
img.onload = function() {
    Pixastic.process(img, "blurfast", options);
    $('.footer').css('background', "url(" + options.resultCanvas.toDataURL("image/png")+ ")" });
}

Comment: The problem is that if i do `img.src` I simply get back the original image url, without the blur effect, i'm asking for a method to get the url of the blurried image if i can, or convert the image to a canvas
Comment: And you can't put put image in background as image, with position absolute z-index -1 etc. to simulate *background*?
Comment: What do you mean? put the blurried canvas (image) on the div and then set it's z-index?
Comment: Umm, I got a `Uncaught TypeError: Cannot call method 'toDataURL' of undefined` error, :/
Comment: I moved line with css method inside `onload` method. Try now. Also look what is it in `options` with `console.log`
Comment: Now options holds {amount:1} but now i get a Uncaught Error: SecurityError: DOM Exception 18, is it related to the fact that the images are not local?
Comment: Well I see here one problem. You need first add `img` to document before using Pixasting add class with `display:none` and put somewhere in document and then use Pixastic and background:)
Comment: Yeah, i now remembered that canvas can only operate with local files and not remote files (:/). P.S. how do I 'src' the image in JS after loaded it in html (as you suggested)?


How to get an Instagram Access Token by calling at URL

Question: Is there any way to get Instagram access Token just by calling at the particular url but without prompting user access permission
Comment: A big NO :( you have ask user for userName and apssword for accesstoken
Answer: No, you need to have WebView to display html from authentication url. Even scraping html won't work - Instagram builds whole Login page using JavaScript.


divergence of a radial vector field

Question: I wanted to calculate a simple example for the integral representation of the divergence
$$\vec\nabla\cdot\vec{A}=\lim\limits_{\Delta V \rightarrow 0}{\frac{1}{\Delta V}}\iint_{\partial(\Delta V)} \vec{A}\cdot d\vec{F}$$ with $\Delta V$ being an infinitesimally small volume.
Thus, I assumed a radial vector field $\vec{A}(\vec{r})=A(r)\vec{e}_r$ and the $\Delta V$ around $0$. The RHS gives you $\lim\limits_{r \rightarrow 0}{\frac{3}{r}}A(r)$, the LHS yields $\left(\frac{2}{r}+\partial_r\right)A(r)$, thus we have
$$\lim\limits_{r \rightarrow 0}{\partial_r A(r)}=\lim\limits_{r \rightarrow 0}{\frac{A(r)}{r}}.$$ How can I see that both sides are equal?
Comment: L'Hopital's Rule?
Comment: @Chappers: aaaaaaah!
Answer: One can do the following:
$$ \lim\limits_{r \rightarrow 0}{\partial_r A(r)}=\lim\limits_{r \rightarrow 0}{\left(\frac{A(r)}{r}-\frac{A(0)}{r}+\frac{A(0)}{r}\right)}\\
\lim\limits_{r \rightarrow 0}{\partial_r A(r)}=\lim\limits_{r \rightarrow 0}{\left(\partial_r A(r)+\frac{A(0)}{r}\right)}
$$
This tells us that $A(0)$ has to be zero. This makes sense one should remember that we started in local coordinates and thus a finite value of the vector field in the origin would end up with an indefinite direction in the coordinate center.

divergence of a radial vector field


How to know that WINDOW.LOCATION load url

Question: I need to check if iPhone Safari support specific url (lppn://playnow - that url will run Texas Poker application if its already installed) if url does not supported i want to run other link (application page in AppStore).
Are WINDOW.LOCATION return false if it can not load uri?
Answer: window.location won't return false, however you can use AJAX for this.
If jQuery is relevant, it's matter of one or two lines of code (AJAX call to the page, handle the onerror event) otherwise you'll have to build it yourself, but it's still possible.
Comment: @Guy ashamed to admit that I didn't research enough before answering.. while it *is* possible with AJAX, it requires server side "proxy" for the cross domain request - still matter of few lines, but can't be done with pure client side script. Up for @Pavel to decide if it's valid option and I can give some example.


Drupal 7: Help me to wrap my head around EVA/reverse node reference

Question: What I wanna do shoult be quite easy but but till now I've been without luck. I've read different approaches but none of them worked for me.
Setting: Drupal7/Views 3.6/References/EVA
We have 2 node types:
"article" (e. g. "How to sleep better" and "What your dreams mean")
"theme week" (e. g. "Sleep")
"theme week" has a node relationship field which points to the "article" node type (i. e. theme week "Sleep" has references to "How to sleep better" and "What your dreams mean").
Now I want to show that referenced articles in my "theme week" node which reffers them. I use EVA to attach a view to my "theme week" node.
Problem: I can't get to set up the view properly; my guess is that I'd use a reverse relationship to my reffering node "theme week", but till now I haven't been lucky with that.
Any advices (step-by-step) would be highly appreciated! Do I have to set up a contextual filter as well? Which fields/filters must use the relationship?
Thanks in advance to everyone
sp
Comment: Can you clarify or edit this: "Now I want to show that referenced articles in my "theme week" node which reffers them. I use EVA to attach a view to my "theme week" node."
Comment: Clarification: the "theme week" node should show a view with the "article" nodes which are chosen on creation of a "theme week" (via node reference).

Edit: I did it, here's how: i did NOT use the reverse reference, but a normal one. Here's how:

- I used a normal relationship to the node type "article"
- I did NOT set "require relationship"
Answer: OK, i did it. Here's how:
Node types:
I've set up 2 node types "article" and "theme week".
"theme week" has a node reference field where nodes of the type "article" can be choosen.
View:
 - I've set up one "EVA" view (requires EVA) Under "advanced", I've
   selected the relationship to my "article" node type.
 - I did NOT set "require relationship".
 - Unter "contextual filter" I've set "Content: Nid", "Provide default value -> Content ID from URL".
 - I've set all my fields and filter criteria to use that relationship
Display Suite/EVA: - I've attached my View as a field in my "theme week" node type (requires Display Suite/DS).
Now when a "theme week" node is viewed, it shows the "article" nodes which have been referenced by "theme week".
I hope this might be useful to someone!


where should I save a complex MVC application UI state?

Question: I've been having a look at several MVC frameworks (like rails, merb, cakephp, codeignitier, and similars...)
All the samples I've seen are basically plain and simple CRUD pages, carrying all the infr needed in the querystring and the posted field values.
I've got a couple of apps made with some sort of framework built with classic asp.
This framework handles some CRUD stuff a little more complex than the examples I found.
Something like master-detail, filtering by example, paging, sorting and similars.
I have a controller class that it's just a finite state machine, that goes thru diferent states (like new, browse, filter, show, etc.), then performs the appropiate action depending on the event raised and finally retrieves the neede info to the calling page.
To achieve this I have several hidden inputs to keep the state of the web page (like current id, filter criterias, order criterias, previous state, previous event, well, you get the idea)
What do you think would be the finnest approach to achieve this kind of funcionality?
hidden inputs built in the view and used from the controller??? (I guess that would be the equivalent of what I'm doing right now in classi asp)
--
(added in response to tvanfosson)
basically, my question refers to the third category, the context-dependent setting (in respect to the other two categories I agree with you) the info I was storing in hidden fields to store them on the querystring, I guess that when you click on the "next page" you include everything you need to save in the querystring, right? so that piece of query string gets appended in each and every link that performns some kind of action...
I'm not sure, what are the advantages and disadvantages of using the querystring instead of hidden inputs???
Comment: What state do you keep that can't be transferred to the URL as path parts?
Answer: I use different strategies depending on the character of the actual data.  Things that are preferences, like default page size, I keep in a Preferences object (table) that is associated with the current logged in user and retrieve from there when needed.
Persistent settings associated with the current logon, like filter settings for a page, are stored in the user's session.  Generally these are things that if a user sets them in the current session they should remain sticky.  I think filter settings and visibility are like this.  If I filter a list, navigate away from it to drill down into a particular item, then come back to the list, I want my filter settings to be reapplied -- so I make it part of the session.
Context-dependent settings -- like the current sort column or page number, are controlled using query parameters.  Paging and sort controls (links) are built with the appropriate query parameters to "do the right thing" when clicked and pass any necessary query parameters to maintain or update the current context of the control.  Using the query parameters allows you to use an HTTP GET, which is bookmarkable, rather than a POST.  Using hidden form parameters makes it much harder for the user to save or enter a URL that takes them directly where they want to go.  This is probably more useful for sorting than it is for paging, but the principle applies equally.


Nuget server sometimes not found package

Question: I have my own nuget repository, hosted localy (nuget.server), and Teamcity with package restore build step.
Sometimes, I found errors, like
<code>[12:10:06]Unable to find version '1.2.0-alfa00243' of package 'ReportsBase'.
</code>
Seems, that package doesn't exists, but it exists! I have checked Packages folder, and checked logs of IIS, and found very strange behavior. First request - OK, package found, second and third - not found, then found.
2014-12-09 08:08:27 192.168.123.101 GET /nuget/nuget/Packages(Id='ReportsBase',Version='1.2.0-alfa00243') - 80
- 192.168.121.188 NuGet+Command+Line/2.8.50506.491+(Microsoft+Windows+NT+6.1.7601+Service+Pack+1)
200 0 0 185
2014-12-09 08:10:06 192.168.123.101 GET /nuget/nuget/Packages(Id='ReportsBase',Version='1.2.0-alfa00243') - 80
- 192.168.121.104 NuGet+Command+Line/2.8.50506.491+(Microsoft+Windows+NT+6.1.7601+Service+Pack+1)
404 0 0 37870
2014-12-09 08:10:06 192.168.123.101 GET /nuget/nuget/Packages(Id='ReportsBase',Version='1.2.0-alfa00243') - 80
- 192.168.121.188 NuGet+Command+Line/2.8.50506.491+(Microsoft+Windows+NT+6.1.7601+Service+Pack+1)
404 0 0 47184
2014-12-09 08:10:11 192.168.123.101 GET /nuget/nuget/Packages(Id='ReportsBase',Version='1.2.0-alfa00243') - 80
- 192.168.121.104 NuGet+Command+Line/2.8.50506.491+(Microsoft+Windows+NT+6.1.7601+Service+Pack+1) 200 0 0 381
This often happens with just added packages. (few seconds ago)
What could be reason for so strange things?
Comment: I have debugged nuget server, and probably found cause. There are about 8k packages in my repo, and after every push of new package cache recreating. Sometimes there are push of 5-10 packages, and cache recreates 5-10 times. It could take significant time, and probably this 404 error happens in case of timeout. So, I have fixed this problem by installing Nuget Gallery, instead of NugetServer and everything works fine.
Comment: The failed requests have a different IP address. What do the addresses resolve to?
Comment: Where are the NuGet packages sourced from? Are you creating new packages in your build process (for Octopus deploy for example?) if so then you should create an dependency on your Team City build step to wait for the version to be published to the NuGet repository.
Answer: The simple NuGet.Server package was not designed for anything but a handful of packages. It uses an in-memory hashtable, and watches the file system for changes. If you have any other usage beyond trivial, you need to get a real private server. These private repositories also have the benefit of being easier to set-up and maintain.
Inedo's ProGet is by far the most popular choice for on-prem NuGet servers, but both JFrog and Sonatype have options as well.
MyGet is by far the most popular choice for a cloud-hosted NuGet servers, but there may be others.
You could also try to spin-up an instance of NuGet.org, but that was never designed for use as a private package repository... just the public NuGet.org for private packages.


Jenkins Bitbucket Build Status Notifier Plugin not showing

Question: I have a problem where the build status from my jenkins server is not showing in Bitbucket. I have followed every step here: Bitbucket Cloud Build Status Notifier Plugin and I have also added the Bitbucket Oauth plugin.
The system log looks like this:
It seems like there is something wrong with the build data. I am not an expert and I have followed all the steps as I should, what could the problem be?
Feel free the ask questions if you need more info!
Answer: I have the same issue after upgrade Jenkins... I don't know where is the problem, the warning message is at:
https://github.com/jenkinsci/bitbucket-build-status-notifier-plugin/blob/master/src/main/java/org/jenkinsci/plugins/bitbucket/scm/GitScmAdapter.java#L59
Update:
Ok I solve the issue after downgrade Git plugin to 3.9.1
Cheers
Comment: What steps did you take to downgrade the Git plugin?
Comment: In Jenkins, go to "Manage Jenkins", then "Manage Plugins", then "Installed" tab, scroll down to the "Git" plugin. I had a "Downgrade to 3.9.1" button, which when pressed, installed the older version. After restarting Jenkins, problem solved!
Comment: I just verified that the 3.10.0 version of the Git plugin also works.


Click element will select option

Question: When you click a certain element, an option will be selected.
For example: you click on a Div element with id="object3", this action will automatically select the Option element "Item 3".
Anyone know a Javascript that can do this?
HTML example

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Click tag will select option</title>

<form action="">

  <fieldset>

        <select id="select_items" name="SelectItems">
          <option value="Item1">Item 1</option>
          <option value="Item2">item 2</option>
          <option value="Item3">Item 3</option>
          <option value="Item4">item 4</option>
        </select>

  </fieldset>

</form>

Comment: Thanks for notifying me, I have corrected the title.
Comment: The title is seriously ambiguous. Moreover, a *tag* cannot be clicked, but an *element* can. A tag is 'a' or 'div' while an element is a complete `b`.
Answer: You can define onclick event handler for each div ( in HTML onclick="doSelect( this )" or by dynamic binds )
function doSelect( el ) {
    var sel_id = el.id.replace( 'object', '' );
    document.getElementById( 'select_items' ).value = 'Item' + sel_id;
}

Version with id's
var relations = { 'object1': 'item-fire', 'object2': 'item-earth', 'object3': 'item-water', 'object4': 'item-wind' };

function doSelect( el ) {
    document.getElementById( relations[ el.id ] ).selected = true;
}

Comment: Thanks for your reply ntvf. What if you use an id in the options instead of a value, and you don't use numbers in that id? Like this: http://jsfiddle.net/EqMh4/
Comment: Sounds weird, using options without values. If you need such way, you can use relation array `var relations = { 'object1': 'item-fire', 'object2': 'item-earth', 'object3': 'item-water', 'object4': 'item-wind' };` format `onclick_element_name: option_id_to_select`. Than after use this code as a function body  `document.getElementById( relations[ el.id ] ).selected = true;`
Comment: Thanks for your reply! I do use options with values, but I thought it would be easier if I left them out of the example, because they cannot be used for the code. Sorry for the confusion and thanks for your help :)

Click element will select option


How to use IPv6 tunnel to allow a dynamic IP in (Windows) firewall

Question: I am frequently changing locations and my client has to update their firewall rules to allow me access to various servers when my IP changes.
I'm looking for a better solution. A couple of things that I'm investigating are:

using a VPN
using a dynamic hostname and a powershell script to update the firewall rules

One intriguing suggestion is to use an IPv6 tunnel. My understanding is that it works similar to a dynamic hostname. I register for the IPv6 address and set up a tunnel to my (current) IPv4 address. My client then adds the IPv6 address to the firewall and viola, I have access.
Does this make sense? If so, can anyone provide a guide on how to configure it?
Thanks!
Answer: Yeah sure it can completely work, if you find a tunnel broker (e.g.: tunnelbroker.net) who support dynamic client IP updates. The methodology is changes with providers, at tunnelborker.net they give you a link, sending a request to this url will update your client IP.
But make sure, your client (where you want to set the firewall up) also has IPv6 access.


Como não fazer nenhuma ação se o ternario caia no falso?

Question: Quero que se o selectedGenre for diferente de vazio ou null ele execute movie.genre === selectedGenre, mas se for nulo ou vazio só saia da função sem retornar nada.
selectedGenre ? movie.genre === selectedGenre :

Comment: O operador ternário não deve ser usado como controle de fluxo.
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo
Answer: Não fazendo um ternário, esse operador foi criado para dar um resultado, se não quer que seja feito um resultado o operador não deve ser usado, claramente é um caso para um if.
Mas se quiser insistir muito nisso, o que reforço ser um erro pode resultar em nulo:

false ? console.log("ok") : null;

Mas não tem como fazer uma função encerrar sem fazer uma gambiarra maior ainda.
Forma correta e mais curta:

if (false) console.log("ok");

E usando em função para dar a saída:

function teste(valor) {
    if (valor) console.log("ok");
    else return;
    console.log("continuou");
}
teste(false);

Coloquei no GitHub para referência futura.
Quando deseja controlar o fluxo de execução o if é o correto. Operadores servem para gerar resultados, não controlar fluxo.
Answer: No JavaScript não existe o tipo void, então a função, explicitamente ou não, irá retornar algo, se não for especificado, será undefined:

function example() {}
console.log(example());

function example2() { return; }
console.log(example2());

const example3 = () => {};
console.log(example3());

Então você pode retornar undefined no terceiro operando do ternário ("else"):

function example(bool) {
    return bool ? 'anything' : undefined;
}
console.log(example(true), example(false));

const example2 = (bool) => bool ? 'anything' : undefined;
console.log(example2(true), example2(false));

Uma outra forma de obter o valor undefined é utilizando a operador void:

function example(bool) {
    return bool ? 'anything' : void 0;
}
console.log(example(true), example(false));

const example2 = (bool) => bool ? 'anything' : void 0;
console.log(example2(true), example2(false));

Ainda sim, concordo com a resposta anterior, o if é melhor pra esse objetivo, porém, em caso de arrow functions com uma única linha, afim de manter a simplicidade, faz sentido e é aceitável seu uso


Lasso Selecting Different Features Depending on Weighting

Question: I am performing a logistic regression with an L1/Lasso penalty.
To exemplify: I am attempting to predict a variable $Y$ as a function of $\vec{X} = [X_1, X_2, X_3]$. Depending on the weight of my penalty Lasso obviously selects a different number of features from $\vec{X}$ to use. What confuses me is that for one penalty weighting the regression might select $X_1$ and for a lower weighting it might select $X_2$ and $X_3$but not $X_1$.
How does this happen that one variable has the most explanatory power when only one variable is selected but is "less useful" when we can select more variables? How does this make sense or shouldn't it?
Answer: This can happen when you have multi-colinearity between your variables.
Imagine $X_1=X_2+X_3$ and $Y=2X_1 + 0.2X_2 + 0.1X_3$. So most of the predictive power is contained in $X_1$ and we can do a pretty good one variable prediction with just $X_1$. However, if we're allowed to have two variables we can do a better job with $X_2$ and $X_3$ since there's further information here that's not contained within $X_1$.
Comment: Thank you, very clear and concise. Makes perfect sense.


What are the differences between MockBackend and HttpTestingController?

Question: When testing Angular services, when might I use HttpTestingController.expectOne(...).flush(...) or similar, and when would it be better to use MockBackend.connections.subscribe(...). Are these just a matter of preference or are there clear use cases that lend themselves to one approach over the other?
Answer: MockBackend was deprecated in Angular 4 and removed in Angular 7 together with the whole HttpModule. HttpTestingController is the new counterpart of MockBackend that comes from the new HttpClientModule.
You can read a more detailed documentation about the new module and it's testing facilities on the official Angular guide.


SumAsync retornar zero

Question: Tenho uma consulta em LINQ onde uso o SumAsync, no entanto quando minha entidade está vazia tenho a exceção:

The cast to value type 'System.Decimal' failed because the
  materialized value is null. Either the result type's generic parameter
  or the query must use a nullable type.

A consulta que estou tentando fazer é a seguinte
var valor = await db.Exemplos.SumAsync(a => a.Valor);

Como posso contornar isso e fazer o SumAsync retornar 0 caso a minha entidade não tenho dados ainda?
Answer: O que acontece é que o Sum está sendo chamado num IQueryable e isso faz com que a execução deste método seja delegada para o provider do Queryable, ou seja — como você já deve imaginar, quem executa o Sum, na verdade, é o SQL Server. Você pode conferir este comportamento no código fonte no referencesource.
O erro estoura justamente porque o SQL Server retorna NULL ao tentar executar um SUM numa "coleção vazia".
Você pode fazer o cast de a.Valor para decimal? (nullable decimal) e usar o operador coalesce no resultado final.
var valor = await db.Exemplos.SumAsync(a => (decimal?) a.Valor) ?? 0;

Comment: Mas será algum tipo de limitação da função SumAsync que ela já não trata esse tipo de situação?
Comment: @PabloTondolodeVargas Editei a resposta pra contemplar isso
Comment: Mas se eu fizer `db.Exemplos.Sum(a => a.Valor)`, teria que fazer o cast como no SumAsync?
Comment: @PabloTondolodeVargas Com certeza. O método ser assíncrono ou não não deve fazer diferença no comportamento.

SumAsync retornar zero


Example of a normal cone, that is not irreducible

Question: For a pair of (irreducible) varieties $W \subset V$ over an algebraically closed field $k$, let $C = C_{W} V$ be the normal cone, i.e.
$$C = \operatorname{Spec}_W \bigoplus_{n\geq 0} I^n / I^{n+1},$$
where $I \subset \mathcal O_V$ is the ideal sheaf defining $W$.
What is an example where $C$ has different irreducible components $C_1, C_2$, both dominant over $W$? Clearly, $W \subset V$ cannot be a regular embedding, because in that case $C$ would be a vector bundle.
For context, I came upon this question when reading Chapter 6.1 of Fulton's Intersection Theory, where he says that the images of the $C_i$, called there distinguished varieties of some intersection, need not be distinct.
Answer: Take $W$ the node on a nodal curve $V$. Then $C_WV$ has two components both supported over $W$, corresponding to the branches of the node. I believe $C_WV$ is actually isomorphic to two $\mathbb{A}^1$'s meeting at a point.
In general $\mathbb{P}(C_WV)$ is the exceptional divisor of $Bl_WV$, which is two points in the case above. If $W$ is nowhere dense in $V$ then $C_WV$ is accordingly the cone over the exceptional divisor. This is the case I usually picture, though for intersection theory the other case matters for excess intersections. Namely if $W$ contains any irreducible components of $V$ then $C_WV$ will have extra components that (I think) are just copies of those components, blown up where they meet the non-dense parts of $W$.
Edit: For the nodal cubic, I think the computation is: let
$$R = \frac{k[x,y]}{(y^2-x^2(x+1))}, \quad I = (x,y)R,$$
and take the Rees algebra
$$\mathrm{Rees}_I(R) = \bigoplus_{n \geq 0} I^n = R[It] \cong \frac{R[T,S]}{(xS-yT, yS - x(x+1)T, S^2 - (x+1)T^2)}$$
where $T = xt$ and $S = yt$. I'm not 100% certain I found all the relations in the presentation of $\mathrm{Rees}_I(R)$ here but I think I have. Now modding out by $I = (x,y)$ gives
$$R/(x,y) \otimes \mathrm{Rees}_I(R) = \frac{R[T,S]}{(x,y) + (\text{relations above})} = \frac{k[T,S]}{(S^2-T^2)},$$
which is two crossing lines.


Two $.getJSON calls for one Google Maps api info window. Scope issue

Question: I am trying to call $.getJSON twice and use the data from both in one info window. This is a mashup to display articles from Google News together with a "fortune" (from an RSS feed) in a Google Maps API infowindow. I put the click event listener and the info window blocks inside the $.getJSON("articles.php") call so this code below works in so far as it will display the articles but I can't figure out the right structure to display the fortune since it's in a separate $.getJSON with it's own scope. Is there a way to make this work?
function addMarker(place)
{

    var image = 'http://maps.google.com/mapfiles/kml/pal2/icon31.png';
    var myLatlng = new google.maps.LatLng(parseFloat(place.latitude), parseFloat(place.longitude));
    //make markers and push to array.
    var marker = new MarkerWithLabel({
    position: myLatlng,
    map: map,
    icon: image,
    labelClass: "labels",
    labelContent: place.place_name,
    labelAnchor: new google.maps.Point(20,0),
    });

    markers.push(marker);

    // getJSON fortune from RSS feed.
    var fortune = [];
    $.getJSON("fortunes.php").done(function(data, textStatus, jqXHR) {
        var content = data;
        var len = data.length;
        if (content.length < 1)
        {
            var fortune = "test";
        }
        else
        {
            fortune = content;
        }

    });
    // getJSON articles from Google News rss feed.
    var query = place.postal_code;
    var articles = "News service currently unavailable.";
    var parameter = { "geo": query };
    $.getJSON("articles.php", parameter).done(function(data, textStatus, jqXHR) {
        var content = data;
        var len = data.length;
        if (content.length < 1)
        {
            articles = "Slow news day."
        }
        else
        {
            articles = "
";
            // put articles in unordered list
            for (var i = 0; i < len; i++) {
                articles += "

 " + data[i].title + "

";
            }
            articles += "

FORTUNE

" + fortune.length + "

";
        }
        // Listener for info window
        google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map,marker);
        });
        // Info window
        var infowindow = new google.maps.InfoWindow({
            content: articles
        });
    });

}

Answer: There are 4 ways to get this done.

Make the AJAX calls sequentially - see code example below or http://jsfiddle.net/xs0oypmd/
Build the marker window content when the user opens it, so move the articles html building code to within the marker click event listener and use the setContent function on the infoWindow. If going with this approach I'd suggest using a flag to indicate the first time the info window is opened so that the articles html is built only once. This approach does have the limitation that you still do not know if fortunes has loaded.
Make the "fortunes" call from within "articles.php" - this assumes ownership over the php scripts. This approach means one AJAX call from the browser.
Use a model binding framework, e.g. knockout, to update the infoWindow content when the data is updated via the json call

Code Example For Option 1
$("#btnGetArticles").on("click", function(){
    var fortunes = "test";

    $.ajax({
        url: "/echo/json/",
        type: 'post',
        dataType: 'json',
        data: {
            json: '"some fortune"'
        }
    }).done(function(data) {
        fortunes = data;

        $.ajax({
            url: "/echo/json/",
            type: 'post',
            dataType: 'json',
            data: {
                json: '[{"link": "link/to/first/article", "title" : "first article"},{"link": "link/to/second/article", "title" : "second article"},{"link": "link/to/third/article", "title" : "third article"}]'
            }
        }).done(function(articles) {
            var articlesList = $("
");
            $.each(articles, function(i, v) {
                articlesList.append($("
").html(v.title + ' ' + fortunes.length));
            });

            $("#output").append(articlesList);
        });
    });
});

Comment: I'm so new to coding. I'm trying to figure out how to use this. Should I not use $.getJSON()? I get my articles from my php file which gets the data from google. Same situation for my fortunes.php file.
Comment: I see that your code works but I'm trying to figure how to put that into my info window. Any more suggestions would be great. Thank you for your help!
Comment: The code sample uses the echo service from jsfiddler and requires the code to be a certain way, so you can use `.getJSON` instead. Follow the structure of the example and move your code around, perhaps update your question with the changes so it can be reviewed.
Comment: Totally worked! I went with Option 1. Thanks again, Jonathan!!! Dude, I'm so noob I can't even up-vote this but rest assured I will as soon as I can.


Calcululate the limit of a function of several variables by using the squeeze theorem.

Question: This is the function
$$\lim_{(x,y )\to (7,3)}(x^2-49)\cos\left(\frac{349}{(x-7)^2+(y-3)^2}\right)$$
I can figure out the ones at it approaches 0, but I can't figure it out whe it approaches any other number.
Comment: Change variables $x'=x-7$, $y'=y-3$ and you have a limit that approaches $(0,0)$.
Comment: "I can figure out the ones at it approaches 0, but I can't figure it out whe it approaches any other number." What does this mean?
Answer: $\cos(f(x,y))$ is a  bounded function so it just doesn't matter. We know $-1\leq \cos(f(x,y))\leq 1$ hence the required limit is $0$.
Comment: Any other number like what
Comment: Sorry, that was a comment for @MMTC.
Comment: okay no problem.
Answer: As an alternate answer, note that most of the techniques introduced in a multivariable calculus course involve multivariate limits of the form
$$\lim_{(x,y) \to (0,0)} f(x,y).$$
These techniques generalize by using to change of coordinates $u=x-a$ and $v=y-b$ to evaluate limits $(x,y) \to (a,b)$:
$$\lim_{(x,y) \to (a,b)} f(x,y) = \lim_{(u,v) \to (0,0)} f(u+a, v+b).$$
For your problem, we let $u= x-7$ and $v=y+3$, giving
\begin{align*}&\lim_{(x,y )\to (7,3)}(x^2-49)\cos\left(\frac{349}{(x-7)^2+(y-3)^2}\right)\\
&= \lim_{(u,v) \to (0,0)} ((u+7)^2 - 49) \cos \left( \frac{349}{(u+7-7)^2 + (v+3-3)^2}   \right) \\
&= \lim_{(u,v) \to (0,0)} (u^2 + 14u) \cos \left( \frac{349}{u^2 + v^2} \right).
\end{align*}
From here, we note that $-1 \leq \cos \left( \frac{349}{u^2 + v^2} \right) \leq 1$ for all $u$ and $v$. Thus
\begin{align*}
\lim_{(u,v) \to (0,0)} (u^2 + 14u) \cdot(-1) &\leq \lim_{(u,v) \to (0,0)} (u^2 + 14u) \cos \left( \frac{349}{u^2 + v^2} \right) \leq \lim_{(u,v) \to (0,0)} (u^2 + 14u)\cdot 1 \\
0 &\leq \lim_{(u,v) \to (0,0)} (u^2 + 14u) \cos \left( \frac{349}{u^2 + v^2} \right) \leq 0
\end{align*}
and we conclude by the squeeze theorem that
$$\lim_{(u,v) \to (0,0)} (u^2 + 14u) \cos \left( \frac{349}{u^2 + v^2} \right) =0 $$
and so
$$\lim_{(x,y )\to (7,3)}(x^2-49)\cos\left(\frac{349}{(x-7)^2+(y-3)^2}\right) =0.$$


Question on inequalities

Question: I have this question and its really proving stubborn to crack.
Question: For how many $$a,b,c \ge 0$$ do we have such that $a+b+c=n$ and $a-c= k$. Here we fix $k\ge 0$ and $n\in \mathbb{N}$.
Any ideas please?
Comment: If $nk$?
Comment: Since $b+2c+k=n$, it should be $n<k$.
Answer: First, lets deal with $a-c = k$ we know that $n \geq a \geq k \geq 0$
because from the conditions we know that $a \geq 0$ also if $a > n$ then the second equation will be always false $a+b+c=n$ thirdly if $a < c$ then $a -c $ will be negative which will break the condition that $k \geq 0$.
now we have $n-k+1$ choices for $a$ because $a $ can be equal to $n$ and then $c$ will have to be equal to $n-k$ or $a=n-1$ and $c=n-k+1$ and so on. every value that is valid for $a$ is between $n$ and $k$ so $a$ have $n-k+1$ valid choices.
if we pick a value for $a$ then $c$ is forced to a fixed value to fulfill this $a-c=k$ equation.
and now we have fixed values $a,c$ so b will be forced to a fixed value to fulfill this $a+b+c=n$ equation. so there are $n-k+1$ solution that fulfill your conditions and satisfy the equation but we need to make sure that $a+c \leq n$ so add to the first equation we get $a+a+c-c \leq n+k$  thus $2a \leq n+k$ which means that $a$ have to start from $\left\lfloor \frac{k+n}{2}\right\rfloor $ which the argument above apply to it.
so finally we have $\left\lfloor \frac{k+n}{2}\right\rfloor -k +1$ solutions.
as special cases :
1- when $k>n$ the above formula produce negative or zero answer which means that there is no solution.
2- when $k=n$ the above formula produce 1 as an answer which means that there is one solution namely $a=n ,b=0 , c=0$
3- when $k<n $ it's according to the above formula.
note : $\lfloor x\rfloor $ is called the floor function and gives the nearest lower integer to the $x$ for example $\lfloor \pi \rfloor = 3$
Answer: $a = c+k$
$c+k + b+c = n \Rightarrow b = n - k - 2c$
$b = n-k - 2c \geq 0 \Rightarrow c \leq \frac{ n-k}{2}$
If $n > k$, you have $0$ solutions.
If $n = k$, you have 1 solution.
If $n < k$, you have infinite solutions.

Question on inequalities


In which file is the list of the installed modules saved?

Question: I am trying to synchronize some config data, and I'm getting the following error:
X depends on modules (examples here) that will not be installed after import.

Now I'm fine with adding the setting that they'll be enabled after synchronization, but I cannot for the life of me find any documentation or where in the config files this lives.
Does anyone have any information?
Answer: You are looking for core.extension.yml. Directory for configuration synchronization is set up in settings.php with variable $config_directories.
Here is the documentation, but it's not full.
Comment: Yep, this is right. Figured it out shortly after posting and going through all sorts of config files. Thank you for the link!


Como gerar um valor por extenso em português no MS Office Excel?

Question: Numa planilha do Excel, tendo uma célula com um valor numérico, como calcular seu valor por extenso?
Por exemplo, na célula A1 tenho o valor R$ 587,32.
Preciso de uma função que passada a célula como parâmetro, retorne o texto:
Quinhentos e oitenta e sete reais, trinta e dois centavos
Comment: Vê se isso resolve é uma biblioteca desenvolvida em C#: https://github.com/DiegoGeronimoOnofre/PorExtensoPTBR No repositório do Github diz sobre a biblioteca: *A biblioteca PorExtensoPTBR. foi criada para facilitar a conversão de valores numéricos binários (ulong) por extenso em português (PT-BR). Na versão atual esta biblioteca suporta converter valores de até `- ulong.MaxValue`, o que significa dizer que é possível converter valores maiores que 18 quintilhões.*
Answer: Segue abaixo uma função VBA que retorna o valor por extenso de um número passado como parâmetro, além de permitir algumas configurações do retorno.
' Função que retorna valores por extenso
' Params:
'    Num (Double) : valor numérico a ser calculado seu valor por extenso
'    Opcional FraçTipo (Integer) : opção de como representar a parte fracionária
'        1 ou 5 - Lê fração em centavos ou cêntimos. Ideal para Moeda.
'        2 - Lê a vírgula decimal, cada zero e o número restante como inteiro. Ideal para percentual.
'        3 - Lê a fração de décimo a bilionésimo. Ideal para número puro.
'        4 - Não lê a fração mas escreve como fração com um denominador de 100, 1000, 1000000... Ideal para moeda com fração de milésimo
'    Opcional UndNomeSing (String) : Nome da unidade monetária, no singular.
'    Opcional UndNomePlur (String) : Nome da unidade monetária, no plural.
'    Opcional UndMasc (Boolean - default True) : Unidade é do gênero masculino.
'    Opcional UmMil (Boolean - default True) : Não omitir o "UM" em "UM MIL".
'    Opcional VirgEntrMilh (Boolean - default False) : Usar vírgula entre milhares.
'    Opcional CaixaAlta (Long - default 1) : Estilo de capitalização do texto
'        1 - Todo o texto em minúsculo.
'        2 - Apenas a primeira letra do texto em Maiúsculo, o restante em minúsculo.
'        3 - Capitaliza A Primeira Letra de Cada Palavra, Com Exceção da Conjunção "e".
'        4 - Todo o texto em MAIÚSCULO.
Function fExtenso(Num As Double, Optional FraçTipo As Integer, Optional UndNomeSing As String, _
        Optional UndNomePlur As String, Optional UndMasc As Boolean = True, _
        Optional UmMil As Boolean = True, Optional VirgEntrMilh As Boolean = False, _
        Optional CaixaAlta As Long = 1) As String
    Dim ExtensInt As String
    Dim ExtensFrac As String
    Dim UndNome As String
    Dim FracNome As String
    Dim Signif As Long
    Dim NumText As String

    If Num > 999999999999.99 Or Num < 0 Then
        fExtenso = "Erro! (Valores válidos: >=0 e < 1 trilhão)"
        Exit Function
    End If

    'Preparando nome da unidade, singular e plural
    If UndNomePlur = "" Then UndNomePlur = IIf(UndNomeSing = "", "", Pluralizar(UndNomeSing))
    'Se a função Pluralizar falhar palavras estrangeiras ou em exceções portuguesas, o argumento UndNomePlur pode ser usado.

    'Extenso parte inteira
    ExtensInt = fExtensoInt(Int(CDec(Num)), UndMasc, UmMil, VirgEntrMilh)

    'Extenso parte fracionária
    If FraçTipo = 0 And UndNomeSing = "" Then FraçTipo = 3
    If FraçTipo = 0 And UndNomeSing <> "" Then FraçTipo = 1
    Select Case FraçTipo
    Case 1, 5   'Lê fração em centavos ou cêntimos. Ideal para Moeda
        Num = Format(Num, "0.00") * 1   'Round(Num,2)
        ExtensFrac = fExtensoInt((Num - Int(CDec(Num))) * 100, True, UmMil, VirgEntrMilh)
        If ExtensInt = "" And ExtensFrac = "" Then ExtensInt = "zero"

        'Nome da unidade no singular ou plural
        UndNome = IIf(Num < 1, IIf(Num = 0, " " & UndNomePlur, ""), IIf(UndNomeSing = "" Or Right(ExtensInt, 1) = " ", "", " ") & IIf(Int(CDec(Num)) = 1, UndNomeSing, UndNomePlur) & IIf(Num = Int(CDec(Num)), "", " e "))
        'Nome da fração no singular ou plural
        FracNome = IIf(Num = Int(CDec(Num)), "", IIf(Int(CDec(Num * 100)) - Int(CDec(Num)) * 100 = 1, IIf(FraçTipo = 5, " cêntimo", " centavo"), IIf(FraçTipo = 5, " cêntimos", " centavos")))

        fExtenso = ExtensInt & UndNome & ExtensFrac & FracNome

    Case 2    'Lê a vírgula decimal, cada zero e o número restante como inteiro. Ideal para percentual.
        ExtensFrac = Num - Int(CDec(Num))
        If ExtensFrac = 0 Then
            fExtenso = ExtensInt
        Else
            ExtensFrac = Format(ExtensFrac, "0.############")
            ExtensFrac = Mid(ExtensFrac, 3, 15)
            fExtenso = IIf(ExtensInt = "", "zero", ExtensInt) & " vírgula"
            Do While Left(ExtensFrac, 1) = "0"
                fExtenso = fExtenso & " zero"
                ExtensFrac = Mid(ExtensFrac, 2, 15)
            Loop
            fExtenso = fExtenso & " " & fExtensoInt(ExtensFrac * 1, UndMasc, UmMil, VirgEntrMilh)
        End If

        If fExtenso = "" Then fExtenso = "zero"

        fExtenso = fExtenso & IIf(UndNomeSing <> "", " ", "") & IIf(Num = 1, UndNomeSing, UndNomePlur)

    Case 3    'Lê a fração de décimo a bilionésimo. Ideal para número puro.
        ExtensFrac = Num - Int(CDec(Num))
        If ExtensFrac = 0 Then
            ExtensFrac = ""
        Else
            ExtensFrac = Format(ExtensFrac, "0.############")
            Signif = Len(ExtensFrac) - 2
            If Signif > 3 And Signif <> 6 And Signif <> 9 And Signif <> 12 Then Signif = Int(CDec(Signif / 3)) * 3 + 3
            If Signif > 0 Then
                ExtensFrac = Format(ExtensFrac, "0.000000000000")
                ExtensFrac = fExtensoInt(Mid(ExtensFrac, 3, Signif) * 1, True, UmMil, VirgEntrMilh)
                FracNome = Choose(Signif, "décimo", "centésimo", "milésimo", , , "milionésimo", , , "bilionésimo", , , "trilionésimo")
                FracNome = " " & FracNome & IIf(ExtensFrac = "um", "", "s")
            Else
                ExtensFrac = ""
            End If
        End If

        If ExtensInt = "" And ExtensFrac = "" Then ExtensInt = "zero"

        If UndNomeSing = "" Then
            fExtenso = ExtensInt & IIf(ExtensInt <> "" And ExtensFrac <> "", ", e ", "") & ExtensFrac & FracNome
        Else
            'Nome da unidade no singular ou plural
            UndNome = IIf(Num < 1, IIf(Num = 0, " " & UndNomePlur, ""), IIf(UndNomeSing = "" Or Right(ExtensInt, 1) = " ", "", " ") & IIf(Int(CDec(Num)) = 1, UndNomeSing, UndNomePlur) & IIf(Num = Int(CDec(Num)), "", " e "))
            'Nome da fração no singular ou plural
            FracNome = IIf(Num = Int(CDec(Num)), "", FracNome & " de " & UndNomeSing)

            fExtenso = ExtensInt & UndNome & ExtensFrac & FracNome
        End If

    Case 4    'Não lê a fração mas escreve como fração com um denominador de 100, 1000, 1000000... Ideal para moeda com fração de milésimo
        ExtensFrac = Num - Int(CDec(Num))
        If ExtensFrac = 0 Then
            ExtensFrac = "nenhum/100"
        Else
            ExtensFrac = Format(ExtensFrac, "0.############")
            Signif = Len(ExtensFrac) - 2
            If Signif > 3 And Signif <> 6 And Signif <> 9 And Signif <> 12 Then Signif = Int(CDec(Signif / 3)) * 3 + 3
            If Signif > 1 Then
                ExtensFrac = (Num - Int(CDec(Num))) * 10 ^ Signif
                ExtensFrac = ExtensFrac & "/" & 10 ^ Signif
            Else
                ExtensFrac = (Num - Int(CDec(Num))) * 10 ^ 2
                ExtensFrac = ExtensFrac & "/100"
            End If
        End If

        If ExtensInt = "" Then ExtensInt = "zero"

        'Nome da unidade no singular ou plural
        UndNome = IIf(Int(CDec(Num)) = 1, UndNomeSing, UndNomePlur)

        fExtenso = ExtensInt & " " & UndNome & " e " & ExtensFrac
    End Select

    Select Case CaixaAlta
    Case 1
        fExtenso = LCase(fExtenso)
    Case 2
        fExtenso = UCase(Left(fExtenso, 1)) & Mid(fExtenso, 2)
    Case 3
        fExtenso = StrConv(fExtenso, vbProperCase)
        fExtenso = MyReplace(fExtenso, " E ", " e ")
    Case 4
        fExtenso = StrConv(fExtenso, vbUpperCase)
    End Select

    'Preservar caixa alta de letra antes de ponto em UndNome
    Dim lPos As Long
    Dim lPos1 As Long
    Do While InStr(lPos + 1, UndNome, ".") > 1
        lPos = InStr(lPos + 1, UndNome, ".")
        lPos1 = InStr(lPos1 + 1, fExtenso, ".")
        fExtenso = Left(fExtenso, lPos1 - 2) & Mid(UndNome, lPos - 1, 1) & Mid(fExtenso, lPos1)
    Loop
End Function

Private Function fExtensoInt(Num As Double, UndMasc As Boolean, UmMil As Boolean, VirgEntrMilh As Boolean) As String
'Gramática portuguesa:
'Regra Geral: Não se intercala a conjunção 'e' e nem vírgula entre posições de milhar.
'Exceção: Se a milhar posterior for menor que 100 ou for centena inteira (100,200,300...)
'Alguns gramáticos não aceitam essa exceção e outros já aceitam a vírgula.
'A variável ConjExc ativa/desativa a exceção
'A variável VirgEntrMilh usa vírgula entre milhares

   Dim NumText As String
   Dim Ce As String
   Dim Ma As String
   Dim Mõ As String
   Dim Bi As String
   Dim f As String
   Dim ConjExc As Boolean
   ConjExc = True
   If VirgEntrMilh Then ConjExc = False

   If Num = 0 Then
      fExtensoInt = ""
      Exit Function
   End If

   NumText = Format(Num, "000,000,000,000")

   '1º Posição de milhar, Centenas
   Ce = Mid(NumText, 13, 3)
   '2º Posição de milhar, Milhares
   Ma = Mid(NumText, 9, 3)
   '3º Posição de milhar, Milhões
   Mõ = Mid(NumText, 5, 3)
   '4º Posição de milhar, Bilhões
   Bi = Mid(NumText, 1, 3)

   f = fMilharText(Bi, UndMasc) & IIf(Bi > 0, IIf(Bi > 1, " bilhões", " bilhão"), "")

   f = f & IIf(VirgEntrMilh And Bi > 0 And Mõ > 0, ", ", IIf(Bi > 0 And Mõ > 0, " ", ""))
   f = f & IIf(ConjExc And Bi > 0 And Mõ > 0 And (Mõ < 100 Or Right(Mõ, 2) = "00"), "e ", "")

   f = f & fMilharText(Mõ, UndMasc) & IIf(Mõ > 0, IIf(Mõ > 1, " milhões", " milhão"), "")

   f = f & IIf(VirgEntrMilh And Bi + Mõ > 0 And Ma > 0, ", ", IIf(Bi + Mõ > 0 And Ma > 0, " ", ""))
   f = f & IIf(ConjExc And Bi + Mõ > 0 And Ma > 0 And (Ma < 100 Or Right(Ma, 2) = "00"), "e ", "")

   f = f & fMilharText(Ma, UndMasc) & IIf(Ma > 0, IIf(Ma > 1, " mil", " mil"), "")
   If Not UmMil Then If f = "um mil" Then f = "mil"  'Omitir 'um' em 'um mil'

   f = f & IIf(VirgEntrMilh And Bi + Mõ + Ma > 0 And Ce > 0, ", ", IIf(Bi + Mõ + Ma > 0 And Ce > 0, " ", ""))
   f = f & IIf(ConjExc And Bi + Mõ + Ma > 0 And Ce > 0 And (Ce < 100 Or Right(Ce, 2) = "00"), "e ", "")

   f = f & fMilharText(Ce, UndMasc) & IIf(Ce > 0, ",", "")

   f = IIf(Right(f, 1) = ",", Mid(f, 1, Len(f) - 1), f)
   f = IIf(Right(f, 2) = "ão", f & " de", f)
   f = IIf(Right(f, 3) = "ões", f & " de", f)
   fExtensoInt = f
End Function

Private Function fMilharText(NumText As String, UndMasc As Boolean)
'Gramática portuguesa:
'Regra Geral: Intercala-se a conjunção 'e' entre centenas, dezenas e unidades

   Dim UndText As String
   Dim DezenaText As String
   Dim CentenaText As String
   Const ConjDez_Un = " e "   'Conjunção entre Dezena e Unidade
   Const ConjCen_Dez = " e "   'Conjunção entre Centena e Unidade

   '  Unidade texto
   If Mid(NumText, 2, 1) <> "1" Then
      UndText = Choose(Mid(NumText, 3, 1) + 1, "", IIf(UndMasc, "um", "uma"), _
            IIf(UndMasc, "dois", "duas"), "três", "quatro", "cinco", "seis", _
            "sete", "oito", "nove")
   Else
      UndText = ""
   End If

   'Dezena texto
   If Mid(NumText, 2, 1) <> "1" Then
      DezenaText = Choose(Mid(NumText, 2, 1) + 1, "", "dez", "vinte", _
            "trinta", "quarenta", "cinqüenta", "sessenta", "setenta", _
            "oitenta", "noventa")
   Else
      DezenaText = Choose(Mid(NumText, 3, 1) + 1, "dez", "onze", _
            "doze", "treze", "quatorze", "quinze", "dezesseis", _
            "dezessete", "dezoito", "dezenove")
   End If

   'Centena texto
   If UndMasc Then
      CentenaText = Choose(Mid(NumText, 1, 1) + 1, "", "cento", "duzentos", _
            "trezentos", "quatrocentos", "quinhentos", "seiscentos", _
            "setecentos", "oitocentos", "novecentos")
   Else
      CentenaText = Choose(Mid(NumText, 1, 1) + 1, "", "cento", "duzentas", _
            "trezentas", "quatrocentas", "quinhentas", "seiscentas", _
            "setecentas", "oitocentas", "novecentas")
   End If
   If Mid(NumText, 1, 1) = "1" And Mid(NumText, 2, 2) = "00" Then CentenaText = "cem"

   'Milhar texto
   fMilharText = CentenaText & IIf(Mid(NumText, 2, 2) * 1 > 0 And CentenaText <> "", ConjCen_Dez, "") _
         & DezenaText & IIf(Mid(NumText, 2, 2) * 1 <= 19 Or Right(NumText, 1) = "0", "", ConjDez_Un) _
         & UndText
End Function

Function Pluralizar(Sing As String) As String
   Dim e As String

   Dim IsLCase As Boolean

   IsLCase = Right(Sing, 1) = LCase(Right(Sing, 1))

   'Regra geral:
   Pluralizar = IIf(Sing = "", "", Sing & IIf(IsLCase, "s", "S"))

   'Exceções: (Quase todas)
   ' Nomes terminados em al, el, ol, ul, il
   e = LCase(Right(Sing, 2))
   If e = "al" Or e = "el" Or e = "ol" Or e = "ul" Or e = "il" Then Pluralizar = Left(Sing, Len(Sing) - 1) & IIf(IsLCase, "is", "IS")
   'Nomes terminados em il
   If e = "il" Then Pluralizar = Left(Sing, Len(Sing) - 2) & IIf(IsLCase, "is", "IS")
   ' Nomes terminados em r, s, z
   e = LCase(Right(Sing, 1))
   If e = "r" Or e = "s" Or e = "z" Then Pluralizar = Sing & IIf(IsLCase, "es", "ES")
   ' Nomes terminados em m
   If e = "m" Then Pluralizar = Left(Sing, Len(Sing) - 1) & IIf(IsLCase, "ns", "NS")
   ' Nomes terminados em x
   If e = "x" Then Pluralizar = Sing
End Function

Private Function MyReplace(vText As String, vTxtFind As String, vTxtRep As String)
'Word 6.0 VBA doesn't have Replace function
    Dim lPos As Long
    lPos = 1 - Len(vTxtRep)
vStart:
    lPos = InStr(lPos + Len(vTxtRep), vText, vTxtFind)
    If lPos = 0 Or vTxtFind = "" Then
        MyReplace = vText
        Exit Function
    End If
    vText = Left(vText, lPos - 1) & vTxtRep & Right(vText, Len(vText) - lPos - Len(vTxtFind) + 1)
    GoTo vStart
End Function

Modo de uso:
Na célula onde quer o valor por extenso, digitar a seguinte fórmula:
=fExtenso(A1; 1; "real"; "reais"), onde:

A1 - nome da célula com o valor a ser transcrito;
1 - Lê fração em centavos;
"real" - nome da unidade monetária no singular;
"reais" - nome da unidade monetária no plural;
Comment: Macro muito boa!! Valeu gênio!


What this Visual Basic 6.0 code do?

Question: What does this Visual Basic 6.0 code below do? However it has been used for a search function, I'm not clear with it. So please explain what it does.
Private Sub cmdSearch_Click()
    Dim key As Integer, str As String
    key = InputBox("Enter the Employee No whose details u want to know: ")
    Set rs = Nothing
    str = "select * from emp where e_no=" & key
    rs.Open str, adoconn, adOpenForwardOnly, adLockReadOnly
    txtNo.Text = rs(0)
    txtName.Text = rs(1)
    txtCity.Text = rs(2)
    txtDob.Text = rs(4)
    txtPhone.Text = rs(3)
    Set rs = Nothing
    str = "select * from emp"
    rs.Open str, adoconn, adOpenDynamic, adLockPessimistic
End Sub

Comment: I'm wondering about rs. It is set to nothing just before a method is called on it. I know that is legal, but it is normally frowned upon.
Comment: Ya that's the point i too got stucked!
Answer: The point no one yet has explicitly said is rs must be declared As New RecordSet so that the Set rs = Nothing just means effectively the same as Set rs = New RecordSet.
Comment: Maybe less of a gotcha than a "knowing what your coding is doing and why."  I can see this burning copy/paste coders pretty badly though.
Comment: @Bob By "gotcha", I mean it's an issue of "understanding your code and your language" that frequently traps less experienced VB6 programmers, so Ant's shouldn't necessarily feel stupid for missing this. You are correct to emphasise that anyone who's caught by this needs to do some learning (unless they don't want to continue to develop as a VB6 programmer).
Answer: Private Sub cmdSearch_Click()
    Dim key As Integer, str As String
    key = InputBox("Enter the Employee No whose details u want to know: ") ''// query the user for a name
    Set rs = Nothing
    str = "select * from emp where e_no=" & key ''//create sql query on the fly
    rs.Open str, adoconn, adOpenForwardOnly, adLockReadOnly ''// create a connection to an sql database
    txtNo.Text = rs(0) ''//assign the results of the query to input fields or labels
    txtName.Text = rs(1)
    txtCity.Text = rs(2)
    txtDob.Text = rs(4)
    txtPhone.Text = rs(3)
    Set rs = Nothing
    str = "select * from emp"
    rs.Open str, adoconn, adOpenDynamic, adLockPessimistic ''// creates a new sql connection and load the whole emp table
End Sub

Short summary: Ask the user for a name and display the data of the user in labels or textboxes.
Comment: @Anto Aravinth: `txtNo.Text = rs(0)` is a contraction of `txtNo.Text = rs.Fields.Item(0).Value` because the default property of a `Recordset` is object is `Fields` (of type `Collection`), the default property of a `Collection` is `Item` (of type `Field`), and the default property of a `Field` is object is `Value`.
Comment: no, it is an instance variable declared outside the method. It simply resets the content to reuse it.
Comment: and whats the reason rs have been declared as nothing ??is that must??
Comment: Then how does this line of code works? "txtNo.Text = rs(0)" , how it displays the emp_no correctly if it has been found?
Comment: `rs(0)` is the first field in the sql query. it works under the assumption that the first field in the emp table in the database is the employee number.
Comment: "[`Set rs = Nothing`] simply resets the content to reuse it" -- well, this is VB6 (your comment characters `//` are wrong :) so it simply reduces the reference count by one, therefore it will only "resets the content" if the reference count was one to begin with.
Answer: It makes two searches against the database. The result of the first search is used to populate some text boxes. The results of the second search... well I have no idea what they are doing with it.
Answer: It looks up data from a database based on a column called e_no, loads information from the found row into TextBox controls, and then re-queries the database for all emp rows.
Comment: Then how does this line of code works? "txtNo.Text = rs(0)" , how it displays the emp_no correctly if it has been found?

What this Visual Basic 6.0 code do?


runners on base and line out

Question: We had runners on 1st and 3rd with 1 out.  While stealing second, the ball was lined to 2b.  The second baseman did not touch the runner who is now standing on second.  They slowly walk over to tag the runner.  The runner on third was tagged up and decided to take home.  He scored before the out was recorded at second.  It was counted a run and I believe that was the right call but looking for thoughts.  50 years old and never saw that one before.
Comment: To clarify, is this baseball or softball? It may not make a difference, but it would helpful for tagging reasons.
Answer: When the ball was caught (on the fly) by 2B, the batter was out.  This means there is no force.  (Even though 1R can be put out by tagging first base).
This is then a time play and the run counts if plate is reached before the third out is recorded.
This play is very similar to one of the approved rulings for 5.08(b), which covers scoring.

APPROVED RULING: One out, Jones on third, Smith on first, and Brown
flies out to right field. Two outs. Jones tags up and scores after the
catch. Smith attempted to return to first but the right fielder's
throw beat him to the base. Three outs. But Jones scored before the
throw to catch Smith reached first base, hence Jones' run counts. It
was not a force play.

runners on base and line out


Where is the benefit in using the Strategy Pattern?

Question: I've looked at this explanation on Wikipedia, specifically the C++ sample, and fail to recognize the difference between just defining 3 classes, creating instances and calling them, and that example. What I saw was just placing two other classes into the process and cannot see where there would be a benefit. Now I'm sure I'm missing something obvious (wood for the trees) - could someone please explain it using a definitive real-world example?

What I can make from the answers so far, it seems to me to be just a more complex way of doing this:
have an abstract class: MoveAlong with a virtual method: DoIt()
have class Car inherit from MoveAlong,
     implementing DoIt() { ..start-car-and-drive..}
have class HorseCart inherit from MoveAlong,
     implementing DoIt() { ..hit-horse..}
have class Bicycle inherit from MoveAlong,
     implementing DoIt() { ..pedal..}
now I can call any function taking MoveAlong as parm
passing any of the three classes and call DoIt
Isn't this what Strategy intents? (just simpler?)

[Edit-update]
The function I refer to above is replaced with another class in which MoveAlong would be attribute which is set according to need based on the algorithm implemented in this new class. (Similar to what is demonstrated in the accepted answer.)

[Edit-update] Conclusion
The Strategy Pattern has it's uses, but I am a strong believer in KISS, and would tend to more straightforward and less obfuscatory techniques. Mostly since I want to pass on easily maintainable code (and 'cos I'll most likely be the one who have to make the changes!).
Comment: "Isn't this what Strategy intents? (just simpler?)" <-- pretty much, except that you give a reference to your class and let the other class call it when it needs to while the other class only knows that it has a MoveAlong. It's one of those things thats more useful in a team situation.
Comment: Hi gerald I think your example is a bad example of strategy pattern. yes its a strategy but in your case it would be better to have subclasses than implement strategy pattern. Im pretty sure martian clock would have different behaviour than earth clock, hence its worth subclassing the clock class.
Comment: lol... I just saw this comment. I suppose if you are expecting to have clients on Mars, that it might be worth worrying about a Martian clock in your designs. But since 100% of most peoples clients are going to be humans on Earth, with a universal time data representation, I think it's fairly safe to ignore that edge case, unless it's for a video game.
Comment: But strategy pattern is quite straightforward even if you are only maintaining the code
Answer: The point is to separate algorithms into classes that can be plugged in at runtime. For instance, let's say you have an application that includes a clock. There are many different ways that you can draw a clock, but for the most part the underlying functionality is the same. So you can create a clock display interface:
class IClockDisplay
{
    public:
       virtual void Display( int hour, int minute, int second ) = 0;
};

Then you have your Clock class that is hooked up to a timer and updates the clock display once per second. So you would have something like:
class Clock
{
   protected:
      IClockDisplay* mDisplay;
      int mHour;
      int mMinute;
      int mSecond;

   public:
      Clock( IClockDisplay* display )
      {
          mDisplay = display;
      }

      void Start(); // initiate the timer

      void OnTimer()
      {
         mDisplay->Display( mHour, mMinute, mSecond );
      }

      void ChangeDisplay( IClockDisplay* display )
      {
          mDisplay = display;
      }
};

Then at runtime you instantiate your clock with the proper display class. i.e. you could have ClockDisplayDigital, ClockDisplayAnalog, ClockDisplayMartian all implementing the IClockDisplay interface.
So you can later add any type of new clock display by creating a new class without having to mess with your Clock class, and without having to override methods which can be messy to maintain and debug.
Comment: So in my idea-code in the question, the function that takes MoveAlong as parm is substituted with the equivalent of your Clock-class?
Comment: It just just struck me how similar this is to the Command Pattern where you pass in an Action on the Command's constructor.
Comment: passing an Action object to a Command *is* using the strategy pattern.
Answer: In Java you use a cipher input stream to decrypt like so:
String path = ... ;
InputStream = new CipherInputStream(new FileInputStream(path), ???);

But the cipher stream has no knowledge of what encryption algorithm you intend to use or the block size, padding strategy etc... New algorithms will be added all the time so hardcoding them is not practical. Instead we pass in a Cipher strategy object to tell it how to perform the decryption...
String path = ... ;
Cipher strategy = ... ;
InputStream = new CipherInputStream(new FileInputStream(path), strategy);

In general you use the strategy pattern any time you have any object that knows what it needs to do but not how to do it. Another good example is layout managers in Swing, although in that case it didnt work out quite as well, see Totally GridBag for an amusing illustration.
NB: There are two patterns at work here, as the wrapping of streams in streams is an example of Decorator.
Comment: just watched the 'Totally GridBag' bit - I can relate to it. lol
Answer: There is a difference between strategy and decision/choice. Most of the time a we would be handling decisions/choices in our code, and realise them using if()/switch() constructs. Strategy pattern is useful when there is a need to decouple the logic/algorithm from usage.
As an example, Think of a polling mechanism, where different users would check for resources/updates. Now we may want some of the priveliged users to be notified with a quicker turnaround time or with more details. Essentailly the logic being used changes based on user roles. Strategy makes sense from a design/architecture view point, at lower levels of granularity it should always be questioned.
Answer: The strategy pattern allows you to exploit polimorphism without extending your main class. In essence, you are putting all variable parts in the strategy interface and implementations and the main class delegates to them. If your main object uses only one strategy, it's almost the same as having an abstract (pure virtual) method and different implementations in each subclass.
The strategy approach offers some benefits:

you can change strategy at runtime - compare this to changing the class type at runtime, which is much more difficult, compiler specific and impossible for non-virtual methods
one main class can use more than one strategies which allows you to recombine them in multiple ways. Consider a class that walks a tree and evaluates a function based on each node and the current result. You can have a walking strategy  (depth-first or breadth-first) and calculation strategy (some functor - i.e. 'count positive numbers' or 'sum'). If you do not use strategies, you will need to implement subclass for each combination of walking/calculation.
code is easier to maintain as modifying or understanding strategy does not require you to understand the whole main object

The drawback is that in many cases, the strategy pattern is an overkill - the switch/case operator is there for a reason. Consider starting with simple control flow statements (switch/case or if) then only if necessary move to class hierarchy and if you have more than one dimensions of variability, extract strategies out of it. Function pointers fall somewhere in the middle of this continuum.
Recommended reading:

http://www.industriallogic.com/xp/refactoring/
http://www.refactoring.com/
Answer: This design pattern allows to encapsulate algorithms in classes.
The class that uses the strategy, the client class, is decoupled from the algorithm implementation. You can change the algorithms implementation, or add new algorithm without having to modify the client. This can also be done dynamically: the client can choose the algorithm he will use.
For an example, imagine an application that needs to save an image to a file ; the image can be saved in different formats (PNG, JPG ...). The encoding algorithms will all be implemented in different classes sharing the same interface. The client class will choose one depending on the user preference.
Answer: One way to look at this is when you have a variety of actions you want to execute and those actions are determined at runtime.  If you create a hashtable or dictionary of strategies, you could retrieve those strategies that correspond to command values or parameters.  Once your subset is selected, you can simply iterate the list of strategies and execute in succession.
One concrete example would be calculation the total of an order.  Your parameters or commands would be base price, local tax, city tax, state tax, ground shipping and coupon discount.  The flexibility come into play when you handle the variation of orders - some states will not have sales tax, while other orders will need to apply a coupon.  You can dynamically assign the order of calculations.  As long as you have accounted for all your calculations, you can accommodate all combinations without re-compiling.
Answer: In the Wikipedia example, those instances can be passed into a function that doesn't have to care which class those instances belong to. The function just calls execute on the object passed, and know that the Right Thing will happen.
A typical example of the Strategy Pattern is how files work in Unix. Given a file descriptor, you can read from it, write to it, poll it, seek on it, send ioctls to it, etc., without having to know whether you're dealing with a file, directory, pipe, socket, device, etc. (Of course some operations, like seek, don't work on pipes and sockets. But reads and writes will work just fine in these cases.)
That means you can write generic code to handle all these different types of "files", without having to write separate code to deal with files versus directories, etc. The Unix kernel takes care of delegating the calls to the right code.
Now, this is Strategy Pattern as used in kernel code, but you didn't specify that it had to be user code, just a real world example. :-)
Comment: It _is_ virtual functions. Strategy Pattern, in my understanding, is just a very specific use of virtual functions, namely using interfaces (in the Java sense) to access functionality rather than concrete classes.
Comment: "passed into a function that doesn't have to care which class those instances belong to" - feels like you added more trees ;-) . How's this differ from virtual functions/polymorphism/generic methods classes ?
Answer: Strategy pattern works on simple idea i.e. "Favor Composition over Inheritance" so that strategy/algorithm can be changed at run time. To illustrate let's take an example where in we need to encrypt different messages based on its type e.g. MailMessage, ChatMessage etc.
class CEncryptor
{
    virtual void encrypt () = 0;
    virtual void decrypt () = 0;
};
class CMessage
{
private:
    shared_ptr<CEncryptor> m_pcEncryptor;
public:
    virtual void send() = 0;

    virtual void receive() = 0;

    void setEncryptor(cost shared_ptr<Encryptor>& arg_pcEncryptor)
    {
        m_pcEncryptor =  arg_pcEncryptor;
    }

    void performEncryption()
    {
        m_pcEncryptor->encrypt();
    }
};

Now at runtime you can instantiate different Messages inherited from CMessage (like CMailMessage:public CMessage) with different encryptors (like CDESEncryptor:public CEncryptor)
CMessage *ptr = new CMailMessage();
ptr->setEncryptor(new CDESEncrypto());
ptr->performEncryption();


Lower bound for left tail probability

Question: If we consider $X$ to be a non-negative random variable, then can we find a lower bound on the left tail probability, that is $\mathbb{P}(X \leq t) \geq C$ where t and C are two positive constants?
Comment: So you could look at the Markov inequality https://en.wikipedia.org/wiki/Markov%27s_inequality $\displaystyle \mathbb{P}(X \geq t) \leq \frac {\mathbb{E}[X]} {t} \iff \mathbb{P}(X < t) = 1 - \mathbb{P}(X \geq t) \geq 1 - \frac {\mathbb{E}[X]} {t}$ But this bound may not be meaningful as this can be negative.
Comment: Thanks @BGM however I'm looking for a more meaningful bound since as you said the lower bound you've proposed may turn to be negative.
Comment: It's still probably easiest to work with tail probabilities. If $X$ has an mgf, a Chernoff inequality (i.e. Markov's inequality in disguise) will give you much sharper bounds: https://en.wikipedia.org/wiki/Chernoff_bound
Comment: @gogurt: I think we will end up with a similar case to the Markov's inequality since Chernoff bound is attained by applying Markov's inequality to $\exp(t X)$.
Comment: I came across the Paley–Zygmund inequality (https://en.wikipedia.org/wiki/Paley%E2%80%93Zygmund_inequality), however it provides a lower bound for the right tail.
Answer: This is an extremely broad question, and has trivial answers (e.g. take $t>0$ large enough that $C:=\mathbb P(X\le t)>0$). I'm going to interpret your question in the following way:

Given $t>0$, does there exist a positive constant $C=C(t,m)$ such that
  $$\mathbb P(X\le t)\ge C$$
  for every non-negative random variable $X$ such that $\mathbb E[X]=m$?

This is a natural question, since if you reverse the inequalities you get Markov's inequality for $C=\frac{m}t$. (If you ask for higher moments instead of $\mathbb E[X]$, clearly we also have tighter bounds such as Chebyshev or Chernoff; more control of the tails obviously gives you more control in the inequality. I'm going to stick to the first moment.) In fact, as BGM points out in the comments, this immediately gives you
$$\mathbb P(X\le t)\ge1-\frac{m}t.$$
However, this is not very interesting - we are interested in "tail" probabilities after all, and so it makes sense to restrict to the case where $t\le m$ (in which case the above bound is useless).
Unfortunately, it turns out that with such a restriction the answer to the above question is "no". To see this, assume without loss of generality that $m>1$ and let $X_n$ have distribution
$$\mathbb P(X_n=m+a_n)=1-a_n,\quad\mathbb P(X_n=m+1)=\frac{a_n(m-1+a_n)}{m+1},\quad\mathbb P(X_n=0)=\frac{a_n}{m+1}$$
where we assume $1>a_n\to0$. Then $\mathbb E[X_n]=m$ and, for any $t\le m$, $\mathbb P(X\le t)=\frac{a_n}{m+1}\to0$ as $n\to\infty$, so there is no uniform lower bound.
You can probably use similar tricks for the analogous question where $C$ can depend on the second moment or even higher, I haven't checked this.

Lower bound for left tail probability


In Svelte, how to apply a class on hover without the CSS :hover?

Question: In my case, I would like to apply animations on hover but to simplify the CSS I wanted to apply a class with the animations on hover instead of writing new CSS with :hover.
Answer: A solution I found was to combine a variable and functions on hover to dynamically apply the class
<code><script>
  let isHovered = false;
</script>

<div class:class-on-hover={isHovered} on:mouseover={() => isHovered = true} on:mouseout={() => isHovered = false}>
  Hover me!
</div>

<style>
  .class-on-hover {
    color: red;
  }
</style>

</code>
Comment: If you are using `:hover` in CSS anyway, adding the class programmatically seems a bit redundant.
Comment: You are just shifting complexity and doing something in code that is arguably meant to be done in CSS. Don't see the point.
Comment: Thanks but I explicitely wrote in the question "To simplify the CSS I wanted to apply a class with the animations on hover instead of writing new CSS with :hover"


In my logistic regression model one of the independent variables is redundant with the interaction term. How should I deal with it?

Question: In my logistic regression is the dependent variable a dummy variable and I also have two independent variables. One of those is a dummy variable and the other is a metric variable. I also suppose an interaction between those two variables.
I am computing three regressions because I want to explore the influence of the independent variables on the dependent variable in period 1, period 2 and in both periods together.
When I compute the regressions for period 2 and for both periods together, there is no problem.
But when I compute the regression for the period 1, SPSS generated a warning that "because of redundancy the degrees of freedom for at least one variable have been reduced". I actually do not know what that means, but I found out that when I exclude the independent dummy variable from my model for period 1, the interaction term is included in the model. So both variables are somehow identical.
My question is how should I deal with this in my work. Should I just say that for the first period the interaction term and the dummy variable are identical? Or there are some other consequences for the interpretation of my model?
I hope this makes my question a little bit clearer. Thanks again.
Comment: Welcome to the site. You can read the [FAQ here](http://stats.stackexchange.com/faq). What do you mean exactly by "redondant"? If your independent variable and your interaction term always have the same value, you can't put the two of them in a model, because they provide exactly the same information, so any modern statistical package is going to exclude one of the variable from the estimation. But maybe I am misunderstanding what you mean by redondant, in which case you will need to develop your question a bit to make it possible to answer it.
Answer: Software will drop variables when they are collinear.  Understanding this situation amounts to figuring more precisely what that means.
There are three independent variables involved, including the constant term.  Let's represent their values as the constant (column) vector $X_1 = (1, 1, \ldots, 1)$, a vector of ones and zeros for the dummy $X_2 = (1, 1, \ldots, 1, 0, 0,\ldots, 0)$, and a third apparently arbitrary vector $X_3 = (x_1, x_2, \ldots, x_n)$.  (All other valid dummy codings are linear combinations of this particular $X_1$ and $X_2$, so no generality is lost by assuming that this particular binary (0-1) encoding is used.)  I have sorted the data so that all the records where the dummy is $1$ come first; suppose there are $k$ of them.  (We know $k \ge 1$ and $k \lt n$, for otherwise the dummy would be constant and could not be included in any regression with a constant term.)
Collinearity of these three vectors along with the $X_2 X_3$ interaction means (by definition) that there is a nontrivial linear relation
$$0 = \alpha_1 X_1 + \alpha_2 X_2 + \alpha_3 X_3 + \alpha_4 X_2 X_3$$
The first $k$ equations in this linear combination are
$$0 = \alpha_1 + \alpha_2 + \alpha_3 x_i + \alpha_4 x_i,\quad i=1, 2, \ldots, k.$$
The remaining equations are
$$0 = \alpha_1 + \alpha_3 x_i,\quad i = k+1, \ldots, n.$$
The first group of equations informs us that all the $(\alpha_3 + \alpha_4)x_i$ are equal to the constant $-(\alpha_1+\alpha_2)$ for $1 \le i \le k$.  The second group informs us that all the $\alpha_3 x_i$ are equal to the constant $-\alpha_1$ for $k \lt i \le n$.  That first statement does not restrict the $x_i$ for $1 \le i \le k$ provided $\alpha_3 + \alpha_4=0$, but the second one then implies that all the $x_i$ are equal to one another for $i \gt k$.  For if this were not the case, then necessarily $\alpha_3 = 0$, implying either $\alpha_4=0$ or all the $x_i$ are equal to each other for $1\le i \le k$.  If $\alpha_4=0$, these would in turn imply that both $\alpha_1 + \alpha_2=0$ and $\alpha_1=0$, reducing all the $\alpha_i$ to $0$: but that was not the case (the linear relation was nontrivial).
In words, what we have deduced is that the continuous variable $X_3$ exhibits no variation among at least one of the two groups of dummy values.

To confirm this conclusion we may create three examples of such data in R. I have chosen $k=2$ and $n=4$: there are two records for each group of dummy values.  In the first case, assigning random values to $X_3$ virtually guarantees there will be variation within both groups:
> set.seed(17)
> x2 <- c(1, 1, 0, 0) # The dummy (binary) variable, sorted as in the analysis
> x3 <- rnorm(4)      # The continuous independent variable
> y <- rnorm(4)       # The dependent variable may have *any* values
> lm(y ~ x2*x3)
Coefficients:
(Intercept)           x2           x3        x2:x3
     0.6763      -0.9218      -1.2728       0.2703

All variables are retained.  (This is OLS regression, not logistic regression, but that doesn't matter: both methods behave identically concerning treatment of collinear independent variables.)
In the second case, let's set the first two first elements of $X_3$ to the same value:
> x3[1] <- x3[2]; lm(y ~ x2*x3)
Coefficients:
(Intercept)           x2           x3        x2:x3
     0.6763      -0.4745      -1.2728           NA

The interaction is dropped due to the collinearity.
In the third case, let's set the last two elements of $X_3$ to a common value while varying the first two. To do this, I just reverse all the element of $X_3$:
> x3 <- rev(x3); lm(y ~ x2*x3)
Coefficients:
(Intercept)           x2           x3        x2:x3
      1.217       -1.756       -1.605           NA

Once again the interaction is dropped due to collinearity.
It sounds like SPSS behaves in the same way as R in such cases.
Comment: Thank you so much for your detailed explanations.This is really a great explanation! You helped me a lot.
Answer: Sounds like your independent variables are correlated. Likely it is the case that when one is 0, the other is 1, or one of the variables takes only one value. I am not familiar with SPSS, but it could also be an error in your code, so I would advise you to post it up for others to help.
Also, it shouldn't surprise you that the model changes when you remove a term. That does not, however, mean that the interaction term is identical to the removed term. This would only be the case where all of one variable is zero, all of one variable is one, or they are inverse of each other. This is because the interaction var1*var2 is simply var1 times var2 with the only possible values being 1 and 0. The only way your interaction for a record is not zero is if both the other variables are 1.
Comment: No problem. I am curious if you were able to solve the problem after the answers given


A question about a continuous function that satisfies the property $\forall x\in\mathbb{R},\exists x<y\in\mathbb{R},f(x)<f(y)$

Question: I got this question:
Let $f:\mathbb{R}\to\mathbb{R}$ be a continuous function that satisfies the property: forall $x\in\mathbb{R}$ there exists $y \in\mathbb{R}$ such that $x < y$ and $f(x)<f(y)$
I was able to prove (hard proof though) that if $a\in\mathbb{R}$ then forall $0<M$ there exists $M<y$ such that $f(a)<f(y)$ and take this for granted.
Prove that if $lim_{x\to\infty}f(x)=5$ then $\forall x\in\mathbb{R}, f(x)<5$
But I got stuck. Thanks.
Comment: What is this: $\forall 0<M\in\mathbb{R},\exists M<y\in\mathbb{R}$? And this: $\forall x\in\mathbb{R},\exists x<y\in\mathbb{R},f(x)<f(y)$?
Comment: What is the question?
Comment: Now it is understandable? or do I need to write instead of $\forall 0<M\in\mathbb{R},\exists M<y\in\mathbb{R}$ just $\forall 0<M,\exists M<y$ (such that.. etc.)?
Comment: @JohnSaita I finally figured it out. I don't know about other people. I'd never write what you did, though.
Comment: If I will change $\forall 0<M\in\mathbb{R}$ to $\forall 0<M$ it will be more understandable?
Comment: My personal suggestion would be to choose between $\forall x\in \mathbb R\exists y\in \mathbb R(x<y\land f(x)<f(y))$ or $\text{For all }x\in \mathbb R\text{ there exists }y\in \mathbb R\text{ such that }x<y\text{ and }f(x)<f(y)$.
Comment: Now is it clearer?
Answer: Assume that there is an $a$ such that $f(a) > 5$. Let $\epsilon = f(a) - 5 > 0$. If
$$
\lim_{x\to \infty} f(x) = 5
$$
then you would have an $N$ such that if $x  \geq N$ then $\lvert f(x) - 5 \rvert < \epsilon / 2$.
Now $f$ being continuous on $[a, N]$ where $f(a) > f(N)$, $f$ attains a maximum at $x_0$ on $[a, N]$. This is also the maximum on $[a, \infty)$. But this contradicts the existence of a $y > x_0$ such that $f(x_0) < f(y)$.
Comment: Thanks for the answer. I was able to prove the statement rigorously.


How do I get a Link in Body of email from cell - VBA

Question: I have spent 3 days on this particular query so would appreciate any help.
I have created a macro that sends an email to a particular person 30 days before a date in a spreadsheet, puts the title of the document in the Subject and marks up my spreadsheet to mark as email sent. Works perfectly!!! However I would like to put a link into the email from  a link that is in the spreadsheet so email recipient can just click on the link and they go straight to the document for review. Im trying to use the href and HTMLBody functions but with no luck, just a lot of hair pulling. If anyone could give me any help it would be wonderful. I have attached the code I am using. As I say works great up until the point I have used strbody. I just can;t figure out what I am doing wrong here. Many thanks
Sub datesexcelvba()
Dim myApp As Outlook.Application, mymail As Outlook.MailItem
Dim mydate1 As Date
Dim mydate2 As Long
Dim datetoday1 As Date
Dim datetoday2 As Long
Dim strbody As String

Dim x As Long

lastrow = Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
For x = 2 To lastrow

mydate1 = Cells(x, 8).Value
mydate2 = mydate1

Cells(x, 11).Value = mydate2
datetoday1 = Date
datetoday2 = datetoday1

Cells(x, 12).Value = datetoday2

If mydate2 - datetoday2 = 30 Then

Set myApp = New Outlook.Application
Set mymail = myApp.CreateItem(olmailitem)

strbody = "Good Morning" & vbCrLf & _
     "Please be aware that this file is due for review in the next 30 days" & vbCrLf & _
     "Please click "here" &vbCrLF & _
     "Regards" & vbCrLf & _
     "Master Control Document"

mymail.To = Cells(x, 7).Value

With mymail
   .Subject = "Review Reminder " & Cells(x, 4).Value
.HTMLBody = .HTMLBody & strbody

   .Display
'.send
End With
Set myApp = Nothing
Set mymail = Nothing

Cells(x, 9) = "Yes"
Cells(x, 9).Font.ColorIndex = 3
Cells(x, 9).Font.Bold = True

Cells(x, 10).Value = mydate2 - datetoday2

End If
Next
Set myApp = Nothing
Set mymail = Nothing

End Sub

Comment: I'm not familiar with VBA, but shouldn't the following line be more like this:

`"Please click here" & vbCrLF & _`
Comment: You might just be missing the proper double-quote string:  `"Please click ""here"`
Comment: Many thanks to you both!!!! I now have the output I desire...and yes, it was my quotation marks that were the issue. I really appreciate both your answers. All the very best. You've made my day (how very sad! :) )
Answer: The following line of code deals with an HTML document which represents the message body:
.HTMLBody = .HTMLBody & strbody

You need to insert your string between opening  and closing  tags if you want to add something to the existing message body.
Also the following string was not well formed for the HTML markup:
strbody = "Good Morning" & vbCrLf & _
     "Please be aware that this file is due for review in the next 30 days" & vbCrLf & _
     "Please click here" & vbCrLF & _
     "Regards" & vbCrLf & _
     "Master Control Document"

Comment: Thank you Eugene; the quotation marks worked well for me. Which part was not well formed so I can gain some insight?
Comment: Is the issue resolved now?
Comment: It is, thank you,  but can't see how to mark it as resolved?
Comment: There should be a button if you are the post owner.
Comment: No, only things there are are the up and down vote button which I cant use as I'm the poster


Exchange 2013 - Clients can't send emails (outbound/inbound)

Question: I have a problem with the exchange server which shows the following behavior:

It does not send emails from outlook/mobile apps/OWA.
It sends mails coming from applications or from powershell both inbound/outbound. No restrictions on from/to addresses etc.
No trace of emails on delivery reports. It looks like they don't even exist.
This has started to happen after installing August's windows updates (uninstalling them did not help)
There is no change to receive/send connectors.

Any tips?
Comment: You've provided no information other than a vague description of the problem. We can't possibly answer this. You need to provide more details.
Comment: Yes, sorry about that. Even MS specialist wasn't able to find any clue other than a guess that it was the DB.
Answer: I had to call MS about this issue. After working on this for hours going through the exchange settings, time services etc. It turned out to be a corrupt database. I've created a new DB and started to move the mailboxes to the new one and everything started working fine.