.htacess 301 Redirect not working in Firefox

Question: I am using the code below, which works fine in Chrome, but it is not working in Firefox. I have cleared cache and reloaded Firefox many times. It seems if I just type oursite.com it will redirect to https, but once I type www.oursite.com, it does not redirect and on subsequent oursite.com entries, it doesn't redirect while that same window is open.
The goal is to redirect all traffic, no matter what the url typed, to the https.....www.... version of the site.
<code> RewriteEngine On
RewriteCond %{HTTP_HOST} ^oursite\.com [nc]
RewriteRule (.*) https://www.oursite.com/$1 [R=301,L]
</code>
Thanks for any help
Comment: Remove `^` from `^oursite\.com`, or remove the condition entirely.
Comment: That didn't work...it threw a too many redirect errors in both browsers.
Answer: Please try this one:
<code>RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-SSL} !on
RewriteCond %{HTTP_HOST} ^oursite\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.oursite\.com$
RewriteRule ^/?$ "https\:\/\/www\.oursite\.com\/" [R=301,L]
</code>


Update fields dynamically in postgres without using the || operator

Question: I have this function that updates a table accordingly. I have used the pipe (||) operator already to pick the new values or retain the old ones if nothing was supplied in the request body for that field but I realized this method may not be maintainable if the columns are much. Hence, is there a way one can just extract only the fields that are supplied into the request body and then inject them into their respective columns without using the pipe (||)?
<code> static async updateProduct(req, res) {
        const { id } = req.authData.payload;
        const {
          description, category, imageurl, quantity, unitPrice
        } = req.body;

        try {
          const { rows } = await db.query(queryProductAdmin, [req.params.productId, id]);
          if(!rows[0]) {
            return res.status(404).json({
              status: 'Fail',
              message: 'The product is not available'
            });
          }
          **/** Instead of using the pipe, how can something like this be achieved?
            .update(req.body, { fields: Object.keys(req.body) })*/**
          const values = [
            description || rows[0].description,
            category || rows[0].category,
            imageurl || rows[0].imageurl,
            quantity || rows[0].quantity,
            unitPrice || rows[0].unitPrice,
            req.params.productId,
            id
            ];

            const response = await db.query(updateProductQuery, values);
            const updatedProduct = response.rows[0];
            return res.status(200).json({
              message: 'Update was successful',
              updatedProduct
            });

        } catch(error) {
          const { message } = error;
          return res.status(500).json({
            status: 'Fail',
            message
          });
        }
</code>
N.B: The code is working fine. I just need ideas on how to update dynamically.
Answer: You could do something like:
<code>const values = ['description', 'category', 'imageurl', 'unitPrice']
  .map(v => req.body[v] || rows[0][v])
  .push(req.params.productId, id)
</code>
To go a bit further you could get the table fields using postgres API and map those instead depending on whether or not you are showing all the fields in the query array or not
Comment: Would be a SELECT statement
Comment: I have not tried it but will try it out later. I accepted it hoping it will be correct. Thank you.
Comment: pls what do you mean by Postgres API, I am using the node-pg library?
Comment: Right...I don't know it at all but it would have methods to get table fields
Comment: I don't think it does but you can also check it out here [link](https://node-postgres.com/)


How to calculate $\frac{\partial \mathrm{logdet}({X}_{i\times i})}{\partial X}$?

Question: I know that $\frac{\partial \mathrm{logdet}(X)}{\partial X}=(X^{-1})^T$.
Lets denote ${X}_{i\times i}$ which is $i\times i$ matrix that is formed from $X\in\mathbb{R}^{n\times n}$ by removing all columns $i+1,i+2,\ldots,n$ and rows $i+1,i+2,\ldots,n$.
Ex: if $X=\begin{bmatrix}1 & 2  & 3\\4  & 5 &6 \\7  & 8  &9\end{bmatrix}$, then $X_{1\times 1}=1$, $X_{2\times 2}=\begin{bmatrix}1 & 2 \\4  & 5 \end{bmatrix}$.
How to calculate $\frac{\partial \mathrm{logdet}({X}_{i\times i})}{\partial X}$?
Comment: Hint: write your derivative as $\frac{\partial\log(\det(X_{i\times i}))}{\partial X_{i\times i}}\frac{\partial X_{i\times i}}{\partial X}$
Answer: Just note that using the chain rule you get
$
\left(\frac{\partial\log(\det(X_{i\times i}))}{\partial X}\right)_{lg}=
\left(\frac{\partial\log(\det(X_{i\times i}))}{\partial X_{i\times i}}\frac{\partial X_{i\times i}}{\partial X}\right)_{lg}$
It remains to compute $\frac{\partial X_{i\times i}}{\partial X}$ and this is easily done considering that
$\left(\frac{\partial X_{i\times i}}{\partial X}\right)_{lj}=\frac{\partial X_{i\times i}}{\partial X_{lj}}=\begin{cases}1\ \ \text{if}\ l,j\le i\\ 0\end{cases}=\begin{pmatrix} &I_{i}&0_{n-i}\\
&0_{n-i}&0_{i}\end{pmatrix}$
Using the result you state at the start of your question we get:
$\frac{\partial\log(\det(X_{i\times I}))}{\partial X}=\begin{pmatrix} &(X_{i\times i}^{-1})^T&0_{n-i}\\
&0_{n-i}&0_{i}\end{pmatrix}$
This is true in general: whenever you consider a function restricted to $X_{i\times i}$, the derivative is going to be: $\frac{\partial f(X_{i\times i})}{\partial X}=\begin{pmatrix} &f'(X_{i\times i})&0_{n-i}\\
&0_{n-i}&0_{i}\end{pmatrix}$
Comment: thanks Gabriele!
Comment: one question: $f'(X_{i\times i})$ is $i\times i$ matrix, whereas $\begin{pmatrix} &I_{i}&0_{n-i}\\
&0_{n-i}&0_{i}\end{pmatrix}$ is $n\times n$ matrix, how to multiply them?
Comment: @Lee I rewrote my answer to avoid such an abuse of notation, I hope my answer is clear now
Comment: yes, thank you!
Answer: Consider a matrix analog of the first cartesian basis vector.
$$\eqalign{
&E &= \pmatrix{I\\{\tt\large 0}} \in {\mathbb R}^{n\times i}\cr
}$$ where $I\in{\mathbb R}^{i\times i}$ is the identity matrix and
${\tt\large 0}\in{\mathbb R}^{(n-i)\times i}$ is the zero matrix.
This $E$ matrix can be used to extract the leading $(i\times i)$ block-diagonal of the $X$ matrix, i.e.
$$X_{i\times i} = E^TXE \;\doteq\; Y $$
The goal is to calculate the gradient of the function $\,\phi=\log\det(Y)$.
First calculate the differential, then perform a change of variables from $Y\to X$.
$$\eqalign{
\phi &= \log\det(Y) \\
d\phi
 &= (Y^T)^{-1}:dY \\
 &= Y^{-T}:E^TdX\,E \\
 &= E\,Y^{-T}E^T:dX \\
\frac{\partial \phi}{\partial X}
 &= E\,Y^{-T}E^T \\
 &= \pmatrix{Y^{-T}&0\\0&0} \\
}$$
In some of the steps above, a colon is used to denote the matrix inner product, i.e.
$$A:B = {\rm Tr}(A^TB)$$


Delegate method not calling

Question: Apple push notification alert, sound and badge received on iPhone. But not calling:
<code>-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
</code>
This method not calling. What can I do?
Comment: show some more info of your app
Answer: You probably want to use the delegate callback for remote notifications not local notifications
<code>- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
</code>

Delegate method not calling


How to override TimePattern to be 12 hour time?

Question: How do I override the ShortTimePattern and LongTimePattern to always be in 12 hour time?
The following code works well only with en-US, because other cultures have different patterns.
    System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongTimePattern = "h:mm:ss tt"
    System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortTimePattern = "h:mm tt"

Answer: I believe 'HH' means 24 hour time, while 'hh' means 12 hour time.
Try this:
System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortTimePattern = "HH:mm:ss"
System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongTimePattern = "HH:mm:ss"
Answer: The first thing that comes to my mind is: why you ever want to that?
Mind that for non-US people 12-hour time could be hard to understand. There are reasons why most of .Net's classes are locale-aware.
If you ever going to sell your app abroad, you might be forced to change it, so what's the point of doing the same thing twice?
Comment: +1. I agree. For people who don't use 12 hour clock frequently and do not speak English, AM/PM may be very confusing.


Whats the biggest difference in calculating a simple regression model with/without a constant term?

Question: I have calulated an OLS with and without a constant term. However, besides that the values are different I haven`t really found anything valueable?
Therefore my question is:
Whats the biggest difference in calculating a simple regression model with/without a constant term?
I really appreciate your reply!
Comment: Related http://stats.stackexchange.com/q/22329/3277 ?
Comment: [Here's an old post that explains it in detail.][1]

  [1]: http://stats.stackexchange.com/questions/26176/removal-of-statistically-significant-intercept-term-boosts-r2-in-linear-model
Comment: See also:  https://stats.stackexchange.com/questions/7948/when-is-it-ok-to-remove-the-intercept-in-a-linear-regression-model
Answer: Estimating a regression without a constant term is essentially saying "I know the intercept of my model is equal to zero. I don't need to estimate it because I know with certainty what it is." That's a pretty bold claim to make. If you're right, then you can estimate the slope with slightly increased precision. If you're wrong, your estimate of the slope will be biased (often badly). It almost always makes sense to include the constant term in a regression model because the cost of estimating the intercept is so low compared to the huge biases that could result from improperly omitting it.
If you have a categorical variable in your model, omitting the intercept won't change any of the other estimates in your model because the otherwise omitted dummy variable takes the place of the intercept. Omitting the intercept will change the interpretation of the coefficients on the dummy variables.


Getting a confusingly complicated mysql request work

Question: I'm not an expert in SQL but I recently started using sqlite3 module in Python with databases and together with pandas and its read_sql_query() they make a pretty nice tool.
Now, say, I have a database looking something like this (I just really made this up for the demo purposes).
age iq  married
===============
91  77  0
54  124 1
31  124 0
32  95  0
74  34  0
18  56  0
43  42  0
78  56  0
91  77  1

The task is, and this is where it might get slightly confusing. I want to select all the rows (people) with the same IQ as the rows with married=1 (including married people themselves). So I would like the result to look like this:
age iq  married
===============
91  77  0
54  124 1
31  124 0
91  77  1

And even in general, let's say I'm even more restrictive and want to select all the people who have the same iq AND the same age as the married ones. In this case the result would look like this:
age iq  married
===============
54  124 1
91  77  0
91  77  1

There might be tons of other columns that could or could not be ignored.
Now of course I can do that iteratively, by first selecting the married ones, then comparing the tuples of (age,iq), but that's kinda boring. The question is, is there a neat way of doing this in one shot with the pandas.read_sql_query()?
So in short, I'm trying to do something like this (I know this just selects married ones, but it's just an example):
import sqlite3
import pandas as pd

connection = sqlite3.connect('people.db')
mydata = pd.read_sql_query(
                """
                SELECT *
                from People
                    WHERE married=1 ... *some magic here*
                    GROUP BY *foo*
                    HAVING *bar*
                """, connection)

where I can't really come up with any "magic" to make it do what I want (probably because of poor knowledge of all SQL commands and conditions). Maybe there is a way to do this with nested SELECT commands and some things like IN, but I'm not really sure.
I feel like there has to be a simple way (or maybe I'm wrong and it's easier to do it iteratively), so I'm asking the community!
Comment: I suggest you provide an example that's a bit more representative of your actual use case.
Comment: Honestly, it's basically this, but with a few GB in the database and with three criteria I need to compare, instead of one or two. Say, `age`, `iq`, `dob`, it's really not that important I think.
Answer: One approach would be to use an EXISTS condition in the WHERE clause which asserts that a given IQ value matches at least one other married record:
SELECT age, iq, married
FROM People p1
WHERE EXISTS (SELECT 1 FROM People p2 WHERE p1.iq = p2.iq AND p2.married = 1);

Demo
The EXISTS subquery might have much better performance with the following index in place:
CREATE INDEX idx ON People (iq, married);

This would allow rapid lookup of a given iq value in the table, along with checking the married status.m
Comment: That's pretty cool! Works great. Could you explain what this `from People p1` and then `select 1` means? Is that like a kind of a loop like `[x for x in range(10)]`? Or maybe you could just direct me to a proper term to google to know more about this?
Comment: You could starting by reading [this tutorial](https://www.techonthenet.com/sql/exists.php).  The exists logic checks, for each person, if another person can be found with the _same_ IQ, who is also married.  If so, then this record is added to the result set.  Not that `EXISTS` is generally more performant than `WHERE IN`.
Comment: Ok yes, I think I got it. I got the logic of selection and comparison, I just didn't know you can create subsets by nesting `SELECT`-s. Thanks! And thanks for the tutorial, will read more about that :)
Comment: Ooph, this is actually pretty slow on my real data (probably because it's a nested loop). But thanks anyway, as it seems to work )
Comment: Adding an index on `(iq, married)` should help: `CREATE INDEX idx ON People (iq, married)`.
Comment: Actually, what's the best practice of adding `INDEX` in Python? I could do cursor `connection.cursor().execute("CREATE INDEX idx ON People (iq, married);")` but then second time I access the same database and try to create this index again, it says `index already exists`. So I could of course do `try/except`, but I was just wondering if there's a best practice which would not "save" the index?
Comment: You typically would not add an index from your application language, but rather you would do it directly from SQLite.  If you really don't need the index long term, then just delete it.
Answer: Try this query:
select * from People
where iq in (
    select iq from People
    group by iq
    having sum(married) > 0
)

Comment: This is smart. :) But in reality I have a slightly more elaborate data where something like `sum(married)` won't work. Works flawlessly for this case, though.


Replication of Services deployed on Azure Service Fabric Cluster

Question: Is there any way to configure the number of replicas for individual services deployed on Azure Service Fabric Cluster?
The Reliability tier set during provisioning the cluster decides the number of replicas, but what if I need to change the number of replicas for some particular service -some service that needs higher reliability than the rest of the services?
I'm using a Visual Studio  Service Fabric Application, so probably something that can be set in the config files?
Answer: Karthik,
Take a look at the app manifest XML file YouApp/ApplicationPackageRoot/ApplicationManifest.xml, under the DefaultServices node, you will notice all the services referenced for your application.
To change the number of replicas for a Stateful Service, set the TargetReplicaSetSize property.
You can also set the minimum number of replicas by setting the MinReplicaSetSize property.
As a side note, don't confuse Reliability tier for a specific node type of your cluster, it is different from replica size of a service.
A Reliability tier is used to specify the minimum number of replicas of the system services that you want to run in the cluster for a node type.
Let's say you have a node type with a Gold Reliability tier, it will be replicated on 7 different machines or more. If this node type goes under 7 replicas because of a failure for example, it will then be considered as unhealthy.


db4o concerns

Question: I'm interested in using db4o as my persistence mechanism in my Desktop application but I'm concerned about a couple things.
1st concern: Accidentally clipping very complex object graphs.
Say I have a tree with a height of 10 and I fetch the root, how does it handle me storing the root object again?
From my understanding, it doesn't fetch the entire tree it fetches the first 5 referenced layers.
So.. If I make a trivial change to the root and then store it, will it clip away the nodes further down the tree, in essence deleting them.
If not.. how does it handle this?
2nd concern: Extracting subgraphs in a larger object graph
Using my tree example from above... If the database contains 1 massive tree can I query for a single node within it? Since <code>.store</code> was called only once, does my database think it contains only 1 "record"?
Thank you.
Answer: You have to be very careful, because two things can happen:  you can pull whole db into memory, or just partial graph (rest of objects will be null).
In db4o there's notion of Activator and Update depth, which can be configured upon dbv40 configuration, or when objects are fetched. Its the way you tell db40 how deep you want him to go when fetching referenced objects. Check db4o web site, there's documentation about it:
http://developer.db4o.com/Resources/view.aspx/Reference/Object_Lifecycle/Activation
http://developer.db4o.com/Resources/view.aspx/Reference/Object_Lifecycle/Update_Depth
Answer: DB4O's Transparent Activation should resolve most of the fears you've expressed here.

db4o concerns


Dictionary Formatting and defaultdict function

Question: I have a dictionary which is the format of {(a,b):c, (a2,b2):c2 and so on}. From this format, there are more than one key of a2, a and so on and for each a, a2 the b, b2 however occurs only once and the value c,c2 for each item varies. What i need is to make a dictionary of dictionary values and single integer keys in this format: {a:{b:c,b2:c2}} assuming that before, a and a2 are the same value.
Cheers guys (use defaultdict if possible). in PYTHON.
Comment: It's not clear what you are asking for. Do you want the dict to look like `{a:{b:c}, a2:{b2:c2}}` ?
Comment: I find it hard to say for sure what you need. Is it a homework? What is the example input data? What is the expected output for this example input data?
Comment: Can you please give an example input and output?
Comment: So `a` and `a2` are the same, but `b` and `b2` aren't? To get good answers, you might want to work on the clarity of your question.
Comment: you should add the expected input and output to make your question more clear.
Answer: if D is the input dict, then
from collections import defaultdict
res = defaultdict(dict)
for (a,b),c in D.items():
    res[a][b] = c


Loading page to div containing mysql query code when results of query are returned

Question: I have a mySQL database I am using as a search function. The user inputs a query, and the search results are loaded.
My html looks like:

            @using (Html.BeginForm())
            {
                @Html.AntiForgeryToken()

                <fieldset style="border:0;">

@Html.LabelFor(model => model.name, "Search Project Assistant:", htmlAttributes: new { @class = "control-label" })

                            @*
*@
                                @Html.TextBoxFor(model => model.name, new { @class = "form-control" })
                                @Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
                            @*
*@

                    <input type="submit" value="Search Tool"/>
                </fieldset>

            }
            @*Following the structure of cipt*@
            @if (ViewBag.PROJ != null)
            {

Search Results

                foreach (var item in ViewBag.PROJ)
                {
                     @item.name

                }

My controller looks like:
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Training([Bind(Include = "name")] searchlinks searchlinks)
        {
            var q = from obj in db.searchlinks
                    where obj.name.Contains(searchlinks.name)
                    orderby obj.name
                    select new SearchResultsViewModel()
                    { name = obj.name, url = obj.url };
            ViewBag.PROJ = q;

            return View();

When my results load, the page loads to the top of the page. I would like to maintain the position of the page, or if it has to reload, have it do so by moving to the div that the search tool is contained in. (The column it is in is within a row with the id "projectassistant"
I am unsure how to go about doing so. Any insight would be very appreciated. Thank you!!!
Comment: Not sure what you want, so maybe a picture to explain the example may help. But sound like you should use ajax to refresh a `partial view`. Like this [**example**](https://www.youtube.com/watch?v=9JJXZfVrBUs&index=93&list=PL6n9fhu94yhVm6S8I2xd6nYz2ZORd7X2v)
Comment: I think you may be right with the ajax solution. Thank you! If you post your solution as a solution instead of a comment I can mark it as the answer if you want?
Answer: Create a partial View copy this porting into the partial view
 @if (ViewBag.PROJ != null)
        {

Search Results

            foreach (var item in ViewBag.PROJ)
            {
                 @item.name

            }
        }

In Your main view (where you need to load the partial view).

Your controller must return partial view.
return PartialView(data);

Now write an ajax
$("#SearchBtn").click(function () {
       path =  "/controller/Actionmethod";
        $.ajax({
        type: "GET",
        url: path,
        success: function (dataval) {
            $('#loadpartialview').html(dataval);
        }
    });
} else {
    alert("Field Empty");
}
});

Hope this will help.
Answer: Just create a partial view, and use Ajax to load the changes asynchronic
Here is an example. Have other topics related to MVC, just watch the playlist. I learn a lot from there ;)


Ionic with Tomcat - successful login, but no Principal injected

Question: Well, I have a tricky question, but hopefully someone can point me to a simple enough direction as Google was not really helpful...
I have the following architecture:

Server-side: Java Spring MVC server with Tomcat container - FORM authentication (via j_security_check) vs a custom DataSourceRealm, which after successful authentication injects the GenericPrincipal with additional session-specific data (custom Principal class)
Client-side: Ionic hybrid app with AngularJS 1.5 running in Chrome and on Android 5.0 device

(note: there is a different web-app working with the same server, as well, and operating correctly)
The app runs fine when emulated in Chrome with --disable-web-security, but when it runs on the device itself it fails with very peculiar symptoms:

j_security_check logs the user correctly and generates a complete and correct Principal object at the end of the authenticate method
Subsequent requests to the server are routed to the correct Spring controllers, but when inspecting the request object - the Principal object and the the authType parameter of the request are both null (contrasted by the correct values of an instance of GenericPrincipal and "FORM", respectively - when requested from browser or the web-app).

Additional info (searched around for a bit...):

withCredentials=true is set in AngularJS config
CORS filter is set to the Tomcat provided filter (with permissive settings) and origin is set to * in client config: <access origin="*"/>
CSP is set to the permissive settings: <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' 'unsafe-eval'"> and navigation is allowed with permissive configurations: <allow-navigation href="*"/> and cordova-whitelist-plugin is added

Any ideas what may cause the actual login to succeed (so not CORS), content loaded and executed (so not CSP) and requests routed correctly (so not Spring), but nevertheless Tomcat failing to inject the session to the request?
Comment: It's very difficult to understand the exact issue with the theoretical explanation. Secondly, you referred to a device, what does that mean, you have some Android app on which you are having problem? If it's an app, then you will have to send JSESSIONID for each request to the server.
Comment: I'd love to elaborate, tell me what you'd like to know - just trying to be concise, without dumping here all the configs (most are not relevant, probably). And yes, as I've mentioned - Android 5.0 device. JSESSIONID is sent - when simulated in Chrome all the JSESSIONID transitions are correct; when run on device - JSESSIONID  is present, but I am unsure how to check if it the correct one (anyhow - it's HttpOnly, so not something I'm supposed to set manually) - perhaps there is some fault with WebView or with Tomcat, but am unsure how to test it...
Comment: I don't thinkmso there is some issue with Tomcat. Anyways, can you post the code how you are sending the cookie i.e JSESSIONID to server.
Comment: By specifying this in Angular config: `$httpProvider.defaults.withCredentials = true;` No other tampering with the cookies is done - it's not like I have access to HttpOnly cookies, anyhow, AFAIK.
Comment: I am sorry, I fail to understand what you say. I hope someone better helps you out. Good luck.. :-)
Comment: I still think its something to with cookie. Check it out. Enjoy
Comment: @st2rseeker Are aware that Phonegap is not a [webserver or a webbrowser](https://github.com/jessemonroy650/top-phonegap-mistakes/blob/master/new-to-Phonegap.md#005)? Are you aware that both [Google and Apple frown on apps](https://github.com/jessemonroy650/top-phonegap-mistakes/blob/master/new-to-Phonegap.md#005a) that are website wrappers?
Comment: The app is not a website wrapper (dunno what gave you the impression, though - to be clear all the assets are local and the server is used only for authentication and REST API), however it uses (or rather tries to use) a similar method of login, which is based on a JSESSIONID cookie (among other non-relevant things). Are you implying that HttpOnly cookies don't work in webView as well?
Comment: And for your information (straight from your link): "Provide a webview of a website not owned or administered by you (unless you have permission from the website owner/administrator to do so)" - does not apply if the site _is_ administered by me. :)
Comment: Apparently this is _not_ relevant to HttpOnly cookies such as `JSESSIONID`
Answer: Well, after some more prodding and thinking, this issue was that JSESSIONID was not being generated prior to j_security_check authentication call but only after it, thus not having an option to retrieve the original session login was made with - subsequent calls were made with inadequate/incorrect identifier.
This link was very helpful: Under what conditions is a JSESSIONID created?
The TL;DR version is that JSESSIONID is not created automatically by default - you have to do one or more of the following things:

Config your server accordingly
Call request.getSession() or request.getSession(true) manually in server code
Get JSP page (there is an implicit request.getSession() there, unless you direct it to behave otherwise)


Probability: Combination and Permutation in Chess

Question: Question: In a chess match, there are 16 contestants. Every player has to be each other player (like a round-robin). The player with the most wins/points wins the tournament.
a) How many games must be played until there is a victor?
b) If every player has to team up with each other player to play doubles chess. How many games must now be played until one of the teams is a victor?
My Attempt:
a) Each of the 16 player would have to verse 15 other people, but Player 1 vs Player 16 is same as Player 16 vs Player 1. Hence, $(16*15)/2$
b) No idea
Official Answer:
a) ${}^{16}C_2$
b) ${}^{16}C_2/2$
My Problem:
a) ${}^{16}C_2$ is the same as my answer, however I thought combination would mean, how many different ways you can choose 2 people out of 16 people. However the question asks how many games have to played, so how does how many games have to be played mean the same thing as how many ways you can choose 2 people out of 16?
b) No idea
Answer: For the first part for a better clarity begin with some smaller cases.
Let's consider there are 3 people playing the chess.  The what will be the number of matches until a Victor is decided.  Through simple counting we get this as 3( which is simply $\binom {3}{2}$ )
Let's consider 4 people to get a stronger hold over the assumption. Again by simple counting you see that the number of matches would be 6 which is simply $\binom {4}{2}$
While counting these cases you might have noticed that what you are doing is nothing but finding the number of ways you can select two people from $16$ contestants.
For the second part though I have a doubt over the official answer.  If they meant to find the matches between all possible teams among themselves. Then we must form two teams. For the first team we select 2 people out of 16. (ways = $\binom {16}{2}$ ). Now for the second team we select 2 people from remaining 14 people( ways $=\binom {14}{2}$  )
But during this process we do overcounting and allow two same teams compete twice. Hence we divide the answer by 2.
Hence according to me the answer to the second part should be $$\frac {\binom {16}{2}\binom {14}{2}}{2}$$
Answer: a) If I choose any two people there has to be one game between them, so the number of games is the same as the number of ways to choose two people. (The reason you use combination instead of permutation here is that it doesn't matter who is black and who is white.)
b) I can't see how the answer given is plausible for any interpretation of the question.
If the intended meaning was that every player teams up with one other player and a round-robin between the teams is played, there would be $8$ contestants (the teams) and so by the same argument as (a) you need ${}^8C_2={}^{16/2}C_2$ games.
On the other hand, if they really mean all possible teams are competing, there are ${}^{16}C_2$ possible teams, and each has to play each other, so it looks like you need ${}^{{}^{16}C_2}C_2$. However, this includes games where there is one player on both teams, which doesn't make much sense, so perhaps a better interpretation is that every team has to play every other team that neither of its players are on. This would give ${}^{16}C_2\times{}^{14}C_2/2$ games, because for each team there are ${}^{14}C_2$ teams they can play taken from the other $14$ players, and then you can swap the two teams to get the same game.


Is it inefficient to glide in butterfly?

Question: I am trying to learn butterfly better, and I watched some videos on YT explaining the stroke mechanics. For some reason, I find it really difficult to time one of the down leg kicks, near the end of arm underwater, as the training videos show.
For me, the natural thing is:
enter arms and leg kick
keep arms front (glide) and get legs back up
start move arms back, at the same time second leg kick
Essentially, on the training videos, there is no pause with the arms.
Is what comes naturally to me, inefficient? Illegal?
Comment: It might also help to see the video you are referencing.
Answer: As far as legality, other than sacrificing a little bit of speed, as long as your arms move back together and aren't split (like in freestyle), you're ok with a little bit of a glide. For most swimmers there is a bit of a pause (not really a glide though) as the arms enter and grab the water before the pull.
This youtube video by Speedo has a decent breakdown of the stroke. There are two videos that follow it on breathing and kick as well.
Where people get a little mixed up is that while the kick aids in propulsion, one of the main purposes of the kick is to drive the wave motion of the body. You have a strong kick as the arms swing forward and in, and the kick is designed to push the upper body down and forward in the water. As the arms start to finish their stroke, the second kick pushes the torso up and forward. (Side note: There is no requirement on kicks. You can do 1, 2, 3, 5, whatever. As long as they go together and don't separate).
If you think of butterfly as a series of shallow dives into the water it helps. One of the ways that I used to teach kids is to have them stand in shallow water and do a forward dive motion, staying just below the surface of the water. As they start to lose a little momentum, use a kick to pop their head up (Arms at this point stay out front and just guide). Then as they progress, I had them do a kick and a pull with no recovery. And so on and so on.
There are also several good kickboard drills to work on butterfly kick motion and timing. I also really like pull buoys with butterfly because even with the pull buoy to aid the flotation of the hips, you can get almost a full stroke in.
Work on each piece, then work on integrating them. Butterfly is probably the most technical stroke (imo) to learn and be smooth at.


How to transition back and forth between relative major and minor 2-5-1?

Question: I'm experimenting with nicely transitioning between a major and minor 2-5-1, at this point I'm purely interested in harmony.
The 2 progression I'm trying to transition between (technically 1-2-5):
Cmaj7 | Cmaj7 | Dm7 | G7   ->   Am7 | Am7 | Bmin7b5| E7  ->  Cmaj7 ...
                      ^^                             ^^

And I'm curious what are my options in the highlighted positions to transition nicely to the next.
Going from major to minor using the 5 of the following minor chord sounds very solid:
Major to minor:

Cmaj7 | Cmaj7 | Dm7 | E7
                      ^^

But going back from minor to major I can't really find a chord there that works well.
I tried the same strategy as before (using the 5 of the next chord):
Minor to major v1:

Am7 | Am7 | Bmin7b5| G7
                     ^^

And tritone substitution
Minor to major v2:

Am7 | Am7 | Bmin7b5| Db7
                     ^^^

What are the "theoretically correct" options here?
Answer: A couple that spring to mind: V7+ > I, and Io > I.
The first still uses a kind of V>I, but with a little more conviction.
The second, though non-diatonic, sounds quite convincing. Can't see any other 'theoretically correct' options - that sound convincing, anyway.
Comment: You really ought to let the question and answer rest for a few more hours - half the world hasn't had chance to wake up and read them yet.
Comment: Thanks Tim, the augmented one sounds much more interesting than my original V7. The I diminished sound strange to my ear, but I'm going to experiment with the voicing maybe that's the problem.
Answer: The problem here is that the way you have the progression the 2-5's want to go back to the original 1, not 1 of the relative. The reason the G7 works well is because it is both a bVII of Am and it is also a deceptive cadence. The E7 to C is not convincing because the leading tone resolves to the ^6 of C, which is not part of a Cmaj7. Even if you resolve to a C6 it still isn't very satisfying because the ^6 is more of a color note in a C major chord. The E-C root motion also leaves something to be desired.
The most obvious and smooth solution is to precede each chord with its native 2-5.
Cmaj7 |Cmaj7 |Bm7b5 |E7 |Am7 |Am7 |Dm7 |G7 :||
If you want to maintain the ii chords you have then another suggestion is to play Bm7b5 for both of the last 2 bars or replace the E7 in your final bar with a Bo7 for a little voice leading. Both of these have the tritone resolving to the ^1 and ^3 of the Cmaj7. You can even use a B7. A 7th chord built on the ^7 of a major key is sometimes used in chord progressions. The tritone of B7, D# and A, resolves to the 3rd and 5th of the C chord. "Meditation" immediately comes to mind. The first 3 chords are: Cmaj7-B7-Cmaj7.
There are other non-diatonic and colorful options, for example replacing the entire final 2-5 with another, like the sub 2-5, Abm7-Db7 or a 2-5 based on a bVII7, Fm7-Bb7.
In the end I wouldn't concern myself too much with "theoretically correct", a lot of jazz harmony doesn't bother. Just go with something that sounds good to you but every option I offered has some basis in theory.
Answer: The transition G7 -> Am is common and makes for easy voice leading; going to Am7 is a bit more difficult as the previous C chord makes Am7 would a lot like C with an added sixth. Going back from E may be accomplished by using the note E as a pivot (a similar strategy to that in "Delilah_"). A moving bass line can smooth out some things.
I got a version to work, but Stack Exchange doesn't allow the posting of pdfs.
Answer: Like other responders, I find the major-to-minor transition to be the easier one to "solve".  The only additional suggestion I can offer is that you keep the G7 and insert a passing G♯dim7 before the Am7:
Cmaj7 | Cmaj7 | Dm7 | G7 G♯dim7 |  Am7 …
The G♯dim7 differs from the G7 by only one tone, and functions like a rootless E7♭9.
The minor-to-major, on the other hand, is trickier.  I don't have a great theoretical basis for this (and will happily accept one) but I like how it sounds.  It also uses a passing chord, but moving by whole steps downward rather than half steps up:
Am7 | Am7 | Bmin7♭5 | E7 Dm6 | Cmaj7 ...
I guess the Dm6 is just an inversion of the Bmin7♭5, but it could also be considered to function as a rootless G9 so it has some similarity to my other idea.
Hear it.


Views attach block to a field

Question: I want to create a simple websites listing. I have created a content type named Sites and a taxonomy vocab named Sites to handle Sites nodes categorization. i.e every Site node (a content of type Sites) belongs to one term under Sites taxonomy vocab.
In the Views module, I have created a new Page view which has the path /sites-cats-listing and it shows Taxonomy terms of type Sites. The format is Unformatted list and it is only has one field Taxonomy term: Name
It renders a simple list of Taxonomy vocab Sites terms as expected. However, I want to list all of sites titles that belongs to each taxonomy term, so, I will get two levels list something like the following example:
-term1
--Site1
--Site2
--Site3
-term2
--Site4
--SiteA
etc...

Also I need to be able to rewrite the site's title field to make it linked directly to the destination website.
So, I need to know is there any way to attach a block to field which the block takes its contextual filter from the field value? Or is there any other workaround to complete this task? I have tried EVA but I could not able to find what I want to get.
Comment: When editing your view, look for the word SORT, next to it, click on add a field. Search for taxonomy term and click add. I think that should take care of your "Two level" list.
Answer: this can be done with a bit of code in a tpl file or in a preprocess function.
Views has a function views_embed_view that you could use to embed the block into your field output.
print views_embed_view('views_name', 'display_id', $fieldvalue);

https://www.drupal.org/node/1336844

Views attach block to a field


Preenchendo div com informação de um forms

Question: Pessoal estou tentando fazer aparecer um valor em uma div com o resultado de um form sem refresh, porém preciso fazer isso para vários registros que vem direto do php;
Estou usando o código abaixo, porém me retorna o mesmo resultado, necessito de várias divs para cada valor de formulario, ou seja imagino que o jscript tem que me gerar varias divs diferentes....

<input class='input' type='text' href="div1">

<input class='input' type='text' href="div2">

<input class='input' type='text' href="div3">

<input class='input' type='text' href="div4">

Comment: Funcionou amigo ! Obrigado ! Agora uma segunda dúvida, como faço uma operação com este resultado do forms, por exemplo o valor do forms * uma variavel de preço ... exemplo valor digitado*40, dai o resultado seria essa operação ....


Code sharing between small student group

Question: I'm currently in college, and we work in groups of three to create small python projects on a weekly basis.
We code with Eclipse and PyDev but we've got a problem when it comes to sharing our work. We end up sending an infinite stream of emails with compressed projects.
What we need is a way to keep the source code updated and we need to be able to share it between us. (on both Windows and Linux) What do you recommend?
thanks in advance.
Comment: If its only sharing what you're doing maybe you could start using Dropbox.
Comment: Use source control - mercurial, git, subversion.
Comment: To advance the Dropbox idea it may be possible to share a Subversion etc. repository using Dropbox.
Answer: Use Git and Github. This way your code is in version control ( which is a good practice) and it can be shared with other people in your project through github. ( github was built with good git integration).
Answer: I'd suggest using a version control system.
Git might be good for you - it doesn't require a central server and there is also support for Windows these days.
Answer: Use Mercurial in conjunction with Bitbucket.
Comment: i've looked around at all the options and Mercurial looks ok and Bitbucket seems the most appropriate for our goal. We're all in favor of open software, but we'd like to keep the projects private until we hand them over for evaluation just to keep things fair. :)
Answer: What you need is a control version server (SVN for instance). You will be able to commit the changes and update the local version of your code  to the current server version.
It is for free:
http://code.google.com/
You should set up your repo and share your work! :-)
I hope it helps.


batch training with One-Class SVM model

Question: i am working with an anomaly detection problem.
i have a large dataset that i cannot fully load  it in the memory does batch training works with normal ML models ?
does this make sense ????
<code># Initialize the One-Class SVM model
one_class_svm = OneClassSVM(nu=nu, kernel=kernel, gamma=gamma)

# Training in batches
batch_size = 1000

    for batch_data in batch_generator(X, batch_size):
        # Train the one-class SVM on the current batch
        one_class_svm.fit(batch_data)

</code>
Answer: I think this solved my problem with partial fit
https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDOneClassSVM.html

batch training with One-Class SVM model


ASP.NET Core MVC works only with Json-Files with 1 object in it

Question: I am not sure how to explain my problem corectly but I will try my best.
My MVC accepts Json-Files like this one
{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

but not Json-Files with more than one "Object" in it
[
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  },
  {
    "userId": 1,
    "id": 2,
    "title": "quis ut nam facilis et officia qui",
    "completed": false
  },
  {
    "userId": 1,
    "id": 3,
    "title": "fugiat veniam minus",
    "completed": false
  }
]

This is my MVC and this way it works but when I replace the URL (https://jsonplaceholder.typicode.com/todos) to have a Json-File with more than 1 "Object" in it my Webpage gives me an Error.
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ToDo.Models;
using System.Net;

namespace ToDo.Controllers
{
    public class ToDoData : Controller
    {
        public ActionResult ToDoModel()
        {
            var webClient = new WebClient();
            webClient.Headers.Add(HttpRequestHeader.Cookie, "cookievalue");
            var json = webClient.DownloadString(@"https://jsonplaceholder.typicode.com/todos/1");
            ToDoStructure ToDoData = JsonConvert.DeserializeObject<ToDoStructure>(json);

            return View(ToDoData);
        }
    }
}

Can someone help with this problem?

The Error:
JsonSerializationException: Cannot deserialize the current JSON array
(e.g. [1,2,3]) into type 'ToDo.Models.ToDoStructure' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize
correctly. To fix this error either change the JSON to a JSON object
(e.g. {"name":"value"}) or change the deserialized type to an array or
a type that implements a collection interface (e.g. ICollection, IList)
like List<T> that can be deserialized from a JSON array.
JsonArrayAttribute can also be added to the type to force it to
deserialize from a JSON array. Path '', line 1, position 1.

The Razor-Page where I want to display the data as a Table
@model ToDo.Models.ToDoStructure
@{
    ViewBag.Title = "ToDoModel";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

ToDoModel

@{

        userId
        id
        title
        completed

        @Model.userId
        @Model.id
        @Model.title
        @Model.completed

}

Comment: So, `.DeserializeObject>` ?
Comment: And you want to make it so it accepts more than one...right?
Comment: what error are you getting ?
Comment: Yeah I want it to accept more than one
Comment: With this I get an Error in VS:  Error: CS0029 | File: ToDoData.cs | Line: 15| Cannot implicitly convert type 'System.Collections.Generic.List' to 'ToDo.Models.ToDoStructure'
Comment: You will also need to change the type of `ToDoData` to match i.e. `List ToDoData = ...`, or use `var` and the type will change automatically for you.
Comment: I'm not sure if I understand you correctly but with this I don't get an error in VS :`List ToDoData = JsonConvert.DeserializeObject>(json);` but the Webpage has a new one: `InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List``1[ToDo.Models.ToDoStructure]', but this ViewDataDictionary instance requires a model item of type 'ToDo.Models.ToDoStructure'.`
Answer: If you want only two (generic) JSON models, you need use:
var _todoData = JsonConvert.DeserializeObject<List<>>(json)

In this case, _todoData will be a list.
Then, in your view, you need use _todoData, and in your HTML, tr needs a foreach, since you will now be working with a list! (This is what the error is saying.)
Comment: on frontend, when you create table tr you need foreach
Comment: `public class ToDoData : Controller
    {
        public ActionResult ToDoModel()
        {
            var webClient = new WebClient();
            webClient.Headers.Add(HttpRequestHeader.Cookie, "cookievalue");
            var json = webClient.DownloadString(@"https://jsonplaceholder.typicode.com/todos");
            var _toDoData = JsonConvert.DeserializeObject>(json);

            return View(_toDoData);
        }
    }` I did this but what do I need to change in ToDoModel.cshtml
Comment: After I used `@model List` and `@foreach (var t in Model)` everything worked fine. Thank you very much. I would give you an upvoe but I don't have enough reputation.
Answer: Try to receive it into string before deserializing it to the expected list object. follow the below format and revert back:
string responseBody = webClient.DownloadString(urladdress);
JavaScriptSerializer json_serializer = new JavaScriptSerializer();//or json serializer
List items =
json_serializer.Deserialize<List>(responseBody);
foreach (var item in items)
{
//loop through if need be
                }

Answer: you have to use a list
List<ToDoStructure> ToDoData = JsonConvert.DeserializeObject<List<ToDoStructure>>(json);

and fix model too
@model  List<ToDo.Models.ToDoStructure>


Verify that $\alpha(a)\neq2$ for all $a$ where $\alpha(x): (2x + 1)/(x + 2)$

Question:
If $A=  \mathbb{R} \setminus \{-2\}$ and $B = \mathbb{R} \setminus \{2\}$, let $\alpha: A \to B$ by $\alpha(x): (2x + 1)/(x + 2)$. Verify that $\alpha(a)\neq2$ for all $a \in A$.

As a hint, I was told to use contradiction.
If I use contradiction though, I feel as if I didn't do anything. If I say $\alpha(a) = 2$, it's clear that it's a contradiction since $2 \notin B$. Is that it?
Answer: As Ilham said, I think the formatting is a bit off. I believe you meant to say that $\alpha(x) = \frac{2x + 1}{x+2} $. If so assume $\alpha(a) = 2$ is true, then:
$$ \frac{2a + 1}{a+2} = 2 $$
Which implies $ 2a+1 = 2a+ 4$ which is not true $\forall a \in \mathbb{R}$
Answer: By contradiction: Suppose $\alpha(a)=2$. Then
$$
2=\frac{2x+1}{x+2}\Longleftrightarrow 2x+4=2x+1\Longleftrightarrow 4=1,
$$
which is clearly absurd. Hence, $\forall a\in A, \alpha(a)\neq 2$. $\blacksquare$
Comment: I meant $B=\mathbb{R}-\{2\}$, of course--my sloppiness, but I can't edit my comment above. :/
Comment: it does but wouldn't the fact that  2 is in B be a contradiction on itself. we say alpha: A -> to B where B is the reals except 2. I originally did that but I wasn't sure if we even need it to do that
Comment: @curiousmind1995 Yes, that's correct. If you are *given* that $B=\mathbb{R}-2$, then $2$ is not in the codomain for the mapping $\alpha\colon A\to B$. Since $\alpha$ is a mapping that sends an element from $A$ to $B$, and $2\not\in B$, then $\alpha(a)=2$ is *never* possible since you are given that $B=\mathbb{R}-2$. Thus, there is no need for any proof in this instance.


Java - add a space after splitting a String

Question: I need to add a space after splitting a String with a " " delimiter. The reason I need to do this is because a space has not been added at the start of the next String as shown in this example:
"There was nothing so VERY remarkable in that; nor did Alice" +
"think it so VERY much out of the way to hear the Rabbit say to"

My code below only splits the string (and reverses it), but the concatenations produce the following result (Notice where "Alicethink" is joined together):
erehT saw gnihton os YREV elbakramer ni ;taht ron did knihtecilA
ti os YREV hcum tuo fo eht yaw ot raeh eht tibbaR yas

Code:
String[] text = PROBLEM5PARA.split(" ");
String reverseString = "";

for (int i = 0; i < text.length; i++) {

    String word = text[i];
    String reverseWord = "";

    for (int j = word.length()-1; j >= 0; j--) {
        reverseWord += word.charAt(j);
    }

    reverseString += reverseWord + " ";
}

System.out.println(reverseString);

How can I fix it?
EDIT:
Here is the whole String:
private static final String PROBLEM5PARA =
        "  There was nothing so VERY remarkable in that; nor did Alice" +
                "think it so VERY much out of the way to hear the Rabbit say to" +
                "itself, `Oh dear!  Oh dear!  I shall be late!'  (when she thought" +
                "it over afterwards, it occurred to her that she ought to have" +
                "wondered at this, but at the time it all seemed quite natural);" +
                "but when the Rabbit actually TOOK A WATCH OUT OF ITS WAISTCOAT-" +
                "POCKET, and looked at it, and then hurried on, Alice started to" +
                "her feet, for it flashed across her mind that she had never" +
                "before seen a rabbit with either a waistcoat-pocket, or a watch to" +
                "take out of it, and burning with curiosity, she ran across the" +
                "field after it, and fortunately was just in time to see it pop" +
                "down a large rabbit-hole under the hedge.";

Comment: How could you tell which word should be seperated after split ?
Answer: If the original string is
"There was nothing so VERY remarkable in that; nor did Alice" + "think it so VERY much out of the way to hear the Rabbit say to"

that is seen by your code as
"There was nothing so VERY remarkable in that; nor did Alicethink it so VERY much out of the way to hear the Rabbit say to"

After that concatenation (which happens in compilation, I believe), Alicethink is a single word, and there is no way to reverse Alice and think individually.
If this is a homework assignment, I think your code is currently doing what it's supposed to. If there is doubt, ask your instructor.
Comment: Thanks, it is a homework assignment and the task is complete I am asking just out of interest.
Answer: Your original string is also joined Alice" + "think, you need update it to Alice " +"think or Alice" + " think
Comment: I'd like to know if there is a way to do this after the String has been set.
Comment: @JamesB no, there isn't.


How do I change the separator in parameterize for Rails

Question: This seems like a dumb question, but how do I use parameterize in Rails? I've seen this doc: http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize
In my Model I can get string.parameterize to work, but I don't understand how to use the separator param. parameterize(string, separator: '') says I can't use parameterize on main, and string.parameterize(separator: '') says can't implicitly convert from Hash to String
Comment: Pretty sure you use it like in the docs `parameterize("Donald E. Knuth", separator: '_')`. What's your string? What rails version?
Comment: Rails 4.2.6; When I type that line into rails console I get the error `NoMethodError: undefined method `parameterize' for main:Object`
Comment: I think you need to `include ActiveSupport::Inflector` in your console before using it.
Answer: string.parameterize without specifying any character will give you your string separated by words, removing any character that's not a letter, and "joining" them with '-':
string = 'Donald E. Knuth'
string.parameterize
# => "donald-e-knuth"

This way specifying a separator:
string.parameterize(separator: '*')
# => donald*e*knuth

The method acts using the I18n.transliterate method to the passed string, and then applying a destructive gsub! which will check any non-letter character and apply the substitution, is like to do:
# without separator specified
I18n.transliterate(string).gsub!(/[^a-z0-9\-_]+/i, 'separator')
# => Donald-E-Knuth

So this way if there's no separator specified, the method has one already defined as its third parameter:
def parameterize(string, sep = :unused, separator: '-', preserve_case: false)
  ...
end

Note the use is first the string and then the parameterize method call, unlike what the documentation exemplifies.
Note: Tested on ruby 2.3.1 and Rails 5.0.2 it works well, Rails 4.2.5, 4.2.6 (as you say) and 4.2.7 throws this error:
Loading development environment (Rails 4.2.5)
> string  = 'x y z'
# => "x y z"
> string.parameterize(separator: '*')
TypeError: no implicit conversion of Hash into String

In Rails < 5 it must be used as ActiveSupport::Inflector.parameterize(string, separator):
> @item = Item.first
# => #<Item id: 1, name: "new item" ...>
> ActiveSupport::Inflector.parameterize(@item.name, '*')
# => "new*item"

Comment: It seems a problem of version, in ruby 2.3.1 and Rails 5.0.2 it works correctly, [check](https://gifyu.com/image/SXYy)
Comment: `string.parameterize(separator: '*')` is not working for me. `string = 'xyz'`. I am getting the error `TypeError: no implicit conversion of Hash into String` in Rails Console
Comment: Could you add the whole code to try reproduce your problem?
Comment: `rails c`; `string = 'xyz'`; `string.parameterize(separator: '*')`;
Answer: Take a look at this for more info:
parameterize("Donald E. Knuth", separator: '_') # => "donald_e_knuth"
parameterize("^très|Jolie__ ", separator: '_') # => "tres_jolie"

This method comes from the ActiveSupport::Inflector class, so you can do:
ActiveSupport::Inflector.parameterize("Hello World Yeah!", separator: "*")
# => "Hello*World*Yeah!"


Why the same POST request works in POSTMAN but not in browser AJAX (404 Not Found)?

Question: I have created ASP.NET WebAPI with the following POST method:
[HttpPost, Route("")]
public IHttpActionResult Post([FromBody] StudentDto student)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    var maxId = conrollerStudents.Max(x => x.ID);
    student.ID = ++maxId;
    conrollerStudents.Add(student);

    InsertStudentIntoDatabase(student);

    return CreatedAtRoute("GetStudent", new { id = student.ID }, student);
}

WebAPI's config:
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.EnableCors();

        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

This API method works only in POSTMAN where I got 201 as result of the POST request. When I move this request into JavaScript-Jquery-AJAX with the following code (auto-generated by POSTMAN). I get the following error message:
{
    "Message":"No HTTP resource was found that matches the request URI 'http://localhost:59523/api/students'.",
    "MessageDetail":"No action was found on the controller 'Students' that matches the request."
}

This is the auto-generated JavaScript-Jquery-AJAX Code, which happens to do not work:
// ...
var settings = {
    "async": true,
    "crossDomain": true,
    "url": "http://localhost:59523/api/students",
    "method": "POST",
    "headers": {
        "content-type": "application/json"
    },
    "processData": false,
    "data": "{\n  \"FirstName\": \"Sample\",\n  \"LastName\": \"Sample\",\n  \"City\": \"Sample\",\n  \"ListOfCourses\": []\n}"
};

$.ajax(settings).done(function (response) {
    console.log(response);
});
// ...

Any idea why this happens?
Comment: From where do you call this AJAX ?
Comment: It is triggerd by the button click event.
Answer: It looks like you want the method to be the default action on that controller, try setting the default action to Index and renaming your method as Index.
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

Comment: It did not help. Sill 404.
Comment: Can you share the full raw content of the request from Postman?
Comment: Here is the screenshot of the Postman. If this is what you asked for. https://imgur.com/a/j307u
Comment: you've got a header set in postman that I can't see, check that the content types match
Answer: This problem relates to the incorrect WebAPI configuration file: Web.config. I have changed the system.webServer section to:
<system.webServer>
  <handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
    <remove name="TRACEVerbHandler"/>
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH" modules="IsapiModule"
          scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH" type="System.Web.Handlers.TransferRequestHandler"
          preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*"/>
      <add name="Access-Control-Allow-Headers" value="Content-Type"/>
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
    </customHeaders>
  </httpProtocol>
</system.webServer>


Functions from finite field to itself

Question: I have read somewhere that for $F$ a finite field with $q$ elements, any function $F\rightarrow F$ is a polynomial function.
If $A=\{f:F\rightarrow F\}$ is the set of such functions and $B=\{\text{polynomials of degree}\le q-1\}$. Then $|A|$, $|B|$ have both $q^q$ elements.
EDIT: Then it's enough to show that there is an injective map from $B\rightarrow A$ which is immediate from the definition of $A$ and $B$.
Comment: If you have a map between two finite sets of the same size, and you want to show that this map is bijective, it is enough to prove that this map is injective. So you need to show that the map $B \to A$ which maps every polynomial to its respective function is injective. What do you know about polynomials?
Comment: @darijgrinberg Yes, only need the bijection. Thanks. Ok I have done that.
Answer: One can find the coefficients of the polynomial $c_0+c_1t\ldots+c_{q-1}t^{q-1}$ equal to a given function $f:\mathbb{F}\rightarrow\mathbb{F}$ by solving the system $c_0+c_1 e+\ldots+c_{q-1}e^{q-1}=f(e)$ with $e$ running over $\mathbb{F}$. This is a system with $|\mathbb{F}|$ equations and $|\mathbb{F}|$ variables; the coefficients form a Vandermonde matrix, so a solution exists regardless of the values of $f$.

Functions from finite field to itself


Calculate the probability that observarvations are due to cheating and not chance in a Bernoulli trial

Question: I asked players to play a game where the outcome (number of successes) should be based on pure chance. However, players could cheat and increase their number of successes. Cheating is not actually a bad thing in my game, I am just using this word for ease of exposition. For each number of successes, I want to calculate the probability that the players with that number of successes cheated.
I will explain the game. Players chose 1 of 10 numbers for 10 rounds. Every round, only 1 of the 10 numbers means that a player is successful. So in each of the 10 rounds, a player has a 10% probability to be successful. Using Bernoulli's Trial I computed the expected probability of the total number of rounds in which a player will be successful. I post them in the table below.

In the data from the game, I can see that many players manage to be successful in all 10 rounds. Let's say that 20 out of 1,000 (2%) of players succeeded in all 10 rounds although, in expectation, only 0.0000001 players (1000 players * the probability that one player succeeds in all 10 rounds) should have succeeded in all 10 rounds. Can I calculate the probability that 20 out of 1,000 players succeeding in 10 rounds is due to cheating and not due to chance?
I want to calculate this number for each level of success. So, for example, 3 out of 1,000 (0.03%) players succeeded in 5 rounds although, in expectation, only 1.4880348 players (1000 players * the probability that one player succeeds in 5 rounds) should have succeeded in 5 rounds. So in general I want to know, for an actual number of players that succeeded for x rounds, what is the probability that their level of success is due to cheating and not due to chance?
I think I should not use a Binomial Test as presented here (https://www.randomservices.org/random/hypothesis/Bernoulli.html). This test, as I understand it, checks if the mean number of wins across all players is different than the expected mean number of wins.
Any help would be appreciated. Thank you.
Answer: I'm not sure I understand the description of the game,
but the table clearly shows the PDF of $\mathsf{Binom}(10, 0.1).$
Then you ask "Can I calculate the probability that 20 out of 1,000 players succeeding in 10 rounds is due to cheating and not due to chance?"
It seems as if you want to test $H_0: p = (0.1)^{10}$ against $H_0: p > (0.1)^{10},$ at the 5% level
based on results from $n = 1000$ plays of the game
in which $x$ players got a Success (the same number all ten times).
In view of the extreme skewness of this binomial distribution, I think you should use an exact binomial test to get the
P-value for such a test, rather than an approximate
normal test (as in your link).  In R binom.test with only $x = 1$ claim of Success, I get
the result below. The P-value is very nearly $0.$
binom.test(1, 1000, p=(0.1)^10, alt = "g")

        Exact binomial test

data:  1 and 1000
number of successes = 1, number of trials = 1000,
 p-value = 1e-07
alternative hypothesis:
 true probability of success is not equal to 1e-10
95 percent confidence interval:
 2.531749e-05 5.558924e-03
 sample estimates:
probability of success
                 0.001

A direct computation of this P-value is in agreement, except for rounding of a number very near $0.$
So even one claim of Success would be strong evidence of 'cheating'. [If more than $x = 1$ of the 1000 participants
claimed a Success, the P-value would be even smaller.]
1-pbinom(0, 1000, .1^10)
[1] 9.999999e-08    # aprx 1e-07

Note: An analogous, but 'milder', game would
be to roll a fair die five times and to get a
'Success' if all five rolls showed the same face.
dbinom(5, 5, 1/6)
[1] 0.0001286008
(1/6)^5
[1] 0.0001286008

binom.test(1, 100, p=(1/6)^5, alt = "g")

        Exact binomial test

data:  1 and 100
number of successes = 1, number of trials = 100,
 p-value = 0.01278
alternative hypothesis:
 true probability of success is greater than 0.0001286008
95 percent confidence interval:
  0.0005128014 1.0000000000
sample estimates:
 probability of success
                   0.01

For this game only one claim of 'Success' in 100 would
raise suspicions of 'cheating' at the 2% level but not
quite at the 1% level.
Comment: Thank you so much for your help.
Comment: I only need to understand one more thing. In your example, you calculate the probability that all 5 die get a 6. This is part of what I am interested in. However, I want to calculate the p value for all possibilities, not just the possibility where all 5 die show a 6. Let's say I roll the dice 100 times (20 series of 5 dice rolls). I then observe that in 15 of these series of 5 dice rolls, I got 4 die to show a 6. It is clear that 15 series in which 4 die show 6 is unlikely to be due to chance. How can I calculate exactly how unlikely this is? Again, thank you very much for your help so far.
Comment: I showed you a 'direct' method to find the P-value for your original question. Adjust that to get $P(X \ge x)$ for values of $x$ greater than $1$.  E.g. for $P(X\ge 5) = 1 - P(X \le 4).$ Use the binomial formula, software, or (as appropriate) a normal approximation.
Comment: Thank you, I will read up on your solution and will approve it. Sorry I don't know immediately if it is the correct answer.


Debugging & stepping into, dynamic proxies

Question: Does anyone know how to step into the target method of a class that is being managed by (in my case) Spring's AOP mechanism?
If I am stepping through my code and get to e.g. orderDao.FindOrder(orderId), and try and step into that method, I get to the proxy class itself, rather than my OrderDAO.
I understand why that would happen of course. However I'm sure I was able to just step into my method directly at some point (i.e. the debugger is bypassing all the AOP stuff and just going directly to my code.
But it's stopped working, and I have no idea what I could have done to stop it from doing this. A setting in VisualStudio (2010) somewhere perhaps?
I've unchecked and then checked the 'Just my code' option in the debugger to see if that helps, but get the same results.
Thanks
Comment: Look in the Output window.  Does it tell you that it skipped your method intentionally?
Comment: Maybe you could make your question a bit broader than only Spring.NET. Spring.NET AOP uses dynamic proxies, which are also used in other stacks (e.g. NHibernate, Castle, LinFu). So formulating your question in a more general so that it would apply there too would attract a larger audience.
Comment: Cheers, good point, I've done that now.
Comment: Ahhh, I get this for the Spring DLLs: 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\2fb3375e\651711d3\assembly\dl3\4bd45ab3\00a44177_f250cc01\Spring.Web.Mvc3.DLL', Symbols loaded
Comment: And this for the .NET DLLs: 'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Web.Razor\v4.0_220.127.116.11__31bf3856ad364e35\System.Web.Razor.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Comment: So I guess I need to figure where this is configured... Google!
Comment: Found it, you can tell VS only to include your own DLLs when debugging in Tools, Options, Debugging, Symbols. Then set up an include/exclude filter by adding each of your DLLs in the 'specified modules' section. Thanks for the heads up Hans. I'd mark you as the correct answer if I could rate comments!
Comment: You can upvote comments too, but maybe you do not enough rep to do that yet. You can answer your own question and accept the answer. Nice solution you found!
Answer: I answered this in the comments, but just so it's obvious if someone else is looking for a solution...
You can tell VS only to include your own DLLs when debugging in Tools, Options, Debugging, Symbols. Then set up an include/exclude filter by adding each of your DLLs in the 'specified modules' section.
Also, in Tools, Options, Debugging, there is a checkbox called "Just my code". That's probably worth toggling (not sure) but I think it's enabled by default so you might not need to bother with this.


One class representing multiple structs (with different members) safely

Question: I receive input data which contains different message types. For each message I extract the relevant details to a general ReturnObject struct:
void processMessage(const std::byte& bytes, ReturnObject& obj)
{
    switch(msgType)
    {
        // Extract message type 1 fields
        // Extract message type 2 fields
        // etc
    }
}

Lets say message 1 has these fields:
int a;
int b;
char c;
string d;

Message 2 has some overlap:
int a;
string d;
double e;
float f;

(There are about 20 different messages in total)
At the moment ReturnObject contains the superset of the fields:
struct ReturnObject
{
    int a;
    int b;
    char c;
    string d;
    double e;
    float f;
};

I'd like ReturnObject to be type-safe and represent one message at a time. When it represents message 1, only a, b, c and d are accessible. One instance will only represent one message type at a time.
What is the best way to achieve this in C++20?
Comment: Another case for `std::variant`..
Comment: Sounds like you may want a [union](https://en.cppreference.com/w/cpp/language/union).
Comment: @JesperJuhl I was thinking about union but then i wasn't sure if std::optional would be a choice?
Comment: @KamilCuk sorry, I meant variant, not optional!
Comment: `std::variant` would be my starting point.
Comment: you can also change each optional field to `std::optional`, depends on real fields and their overlap between variant, this may be a good way.
Comment: and if applicable, I'd recommend always resolve types as early as possible, like `ProcessMessage(bytes)` (of course only if the type is useful information)
Comment: @appleapple I think I know what you mean, although I don't think it would be within processMessage as at that point I don't know the message type (yet). It's effectively known in the first line (I omitted for brevity)
Answer: I would consider polymorphism. This looks like a factory pattern. Your processMessage could just return a pointer to an appropriate object. No need to control access as the irrelevant members simply are not present.


LMER random effects

Question: I have a question regarding a linear mixed-effects model, specifically the random effects. I have taken one core in each zone (three Zones (U,L,P)) across five transects (T1-T5) and three seasonalities (A, J, O), each core was halved into two Horizons (upper, lower) and analysed separately. My main interestes are how lipid pattern changes across Zone, Season and Horizon.
I would like to run a linear mixed effects model, but I am uncertain how to inform the model of the dependency of my halved cores. I had considered creating a "plotID" from the Zone and Transect factors as a unique identifier and add the horizon as nested within this.
This is the code I have for now:
m3 <- lmer(Bacteria ~ Zone*Season*Horizon + (1 | PlotID)+(1 | Horizon:PlotID),df)

Is this the correct way to identify this for the model?
Thank you in advance for your help
Answer: You have Horizon as both a fixed effect and a random effect. That's almost always not a good idea. It should be either fixed or random, and there are a bunch of competing considerations for when to include things as random such as:

when we don't care about the fixed effect of a factor
when a factor has a large number of levels
when we have sampled from larger population of levels
when we want to generalise the inferences to other levels of the factor that were not in our sample

The reasons for treating a factor as fixed are:

when the research question specifically concerns inference for that factor
when the factor has a relatively few number of levels
when we have the entire population of levels for that factor

In this case it is fairly clear that all these considerations point towards modelling Horizon as fixed:

because the research question involves inference on Horizon
because we have only 2 levels of Horizon
because the 2 levels of horizon are the entire population of horizons
Comment: Hello Robert, thank you very much for your kind reply, this has helped me a lot to identify what is missing in my model. I am now considering using the function: (1|Transect)+(1|PlotID: Transect)
Comment: No problem, you're welcome. Indeed, if plot is nested within transect, this would make sense, but what exactly is "plot" ? From the first paragraph, this is unclear. What is the relationship between plot, transect and zone ?
Comment: Hello Robert, Apologies, I did not make that very clear, the "plotID" is an identifier of each core (I just named it plot), consider it as "coreID". The Transects cut across the three Zones and within each Transect and Zone I took one core and halved it per sampling Season.
Comment: Ahh, OK that makes sense now - so yes I would agree that `(1|Transect)+(1|PlotID: Transect) ` makes sense - the only possible difficulty is that you have only 5 transects that that's rather few for fitting random intercepts. You can still do it, but I would also fit a model with transect as a fixed effect instead, just to compare your inferences.
Comment: Does this answer your question ? If so please consider marking it as the accepted answer. If not, please let us know why. Also, if you haven't already, please consider upvoting it

LMER random effects


The difference between Urysohn's lemma and Tietze Extension Theorem.

Question: Urysohn's lemma says that if $X$ is a normal space, then for every two disjoint closed sets $F_{1},F_{2}\in X$, there exists a continuous function $f:X\to [a,b]\in\Bbb{R}$ such that $f(F_{1})=\{a\}$ and $f(F_{2})=\{b\}$.
Tietze Extension theorem says that for every such $f$, there exists a continuous function $f^*:X\to [a,b]$ such that $f^*|F_{1}$ and $f^*| F_{2}=f$.
I don't understand the difference! Why can't $f^*=f$? And if we assume $f^*\neq f$, are we just saying that there are two such continuous functions of the type mentioned in Urysohn's lemma?
Thanks in advance!
Comment: Then your book is completely wrong; throw it away.
Comment: I don't know where you're getting these statements from, but "every such $f$" is just wrong.
Comment: "every such $f$" as in every such $f$ as constructed in Urysohn's lemma. This has been quoted verbatim.
Answer: One can indeed obtain the result of UL via TET by setting $f|_{F_1} = a$ and $f|_{F_2} = b$. Also, in this Wikipedia article it is explicitly written that TET generalizes UL.
Comment: @AyushKhaitan: Urysohn's lemma uses two *non-empty* disjoint closed sets. What you wrote in your question is just an application of Tietze's extension theorem to two closed sets. But the theorem itself says that each continuous $f$ from a closed set $C$ to $\mathbb R$ can be extended to a continuous $\hat f$ from the entire space $X$ to $\mathbb R$.
Comment: My book gives two proofs. One for Urysohn's lemma, and the other for Tietze Extension theorem. I feel one proof should suffice for both, as both of them pretty much state the same thing! Is this understanding wrong?
Comment: @AyushKhaitan: unfortunately, I don't know which book are you talking about. [Here](http://www.proofwiki.org/wiki/Tietze_Extension_Theorem) the proof of TET is obtained by using UL.
Comment: @Ilya- what I meant was shouldn't the proof for UL directly imply TET, rather than being a component of the machinery used to prove TET? And I am reading "General Topoogy" by Pervin.
Comment: @StefanH.- thanks! I think that spells it out perfectly.


Play Framework: How to serialize raw fields to JSON with nested elements

Question: I need to serialize a String and an Option[Boolean]:
val myWrites = (
  (__ \ "box").write(
    (
      (__ \ "name").write[String] ~
      (__ \ "default").writeNullable[Boolean]
    ).tupled
  )
)

If Option[Boolean] is Some then I'd expect
{
  "box": {
     "name": "John",
     "default": true
  }
}

... while if Option[Boolean] is None I'd expect
{
  "box": {
     "name": "John"
  }
}

Given the following variables...
val name = "John"
val default = Some(true)

... how do I pass them to the Writes? I've tried this:
myWrites.writes(name, defaul)

... but it doesn't compile:
No Json serializer found for type play.api.libs.functional.FunctionalBuilder[play.api.libs.json.OWrites]#CanBuild2[String,Option[Boolean]].
Try to implement an implicit Writes or Format for this type.
[error] (__ \ "box").write(

Comment: Your code works for me. Maybe try `Json.toJson( (name, default) )(myWrites)`. Notice that you should pass `Tuple2` (so parentheses are necessary)
Answer: I think its just a typo in your writes. you have defaul vs default
I was able to use
import play.api.libs.json._
import play.api.libs.functional.syntax._

val myWrites = (
  (__ \ "box").write(
  (
   (__ \ "name").write[String] ~
     (__ \ "default").writeNullable[Boolean]
   ).tupled
)
 )

myWrites.writes("hi",Some(true))

and I got back
res0: play.api.libs.json.JsObject = {"box":{"name":"hi","default":true}}


What are the differences between the various Java plugins for hot class reloading and which one is the most intuitive?

Question: I am currently trying to implement hot class reloading in a Java application, however there are so many plugins to choose from and I cannot find a good comparison between the options. Also the websites of the plugins are not all very clear on what the exact features are and how to use them.
There is also the option of making a custom hot class reloading ClassLoader, but I feel like that is similar to "reinventing the wheel" if there are already so many plugins which can do the job.. do other people agree with this?
The Java plugins I found which I think can do the job:

JRebel
Dynamic Code Evolution Virtual Machine (DCEVM)
Fakereplace
Apache Commons Java Compiler Interace (JCI) FileAlterationMonitor (FAM)
AgentSmith
Feenix
Play Framework
JBoss/WildFly
OSGi

So does anyone happen to know what the differences are between the plugins? And also which plugin is the most intuitive to use?
As a side note: What I actually want to do is reloading a .jar-file dependency of my java application. I have some java code which gets re-compiled automatically very often and then converted to a .jar-file. It's a dependency of my java application, and my application needs to use the newest version of this .jar-file every time.
Comment: Ive used Jrebel and amazed at how well it reloads classes in projects and its dependencies.  Free Social license makes it easy to test out.  JRebel has quite an extensive user base.
Comment: Thanks for your comments. I am already looking into OSGi and JRebel, I haven't decided yet which one would be best for me though. Also, I will add OSGi to the list above.
Comment: Sorry to confused you. I just thought the hot class reloading was a requirement of sort. Thanks for looking it up thou. I took a look and the mechanism has quite interesting caveats and corner cases. I for myself bite the bullet and implement a class reloading mechanism from scratch due most of the options are either closed source or from what I read dislike the implementation or is too complex. So thanks again for looking it up.
Comment: You could look into using OSGI.  It supports reloading bundles at runtime.
Comment: @PJvG Can you share your findings? What did you choose and what were your findings?
Comment: @MartinKersten I decided to switch from Java to Python for the project I was working on two years ago before I was ready to choose a Java plugin for hot class reloading. I'm sorry but I don't have any findings to share.
Comment: Ok. So python has hot class replacement already build in?
Comment: @Martin I never said or implied that, but it seems that Python [has indeed hot class/module reloading build in](https://docs.python.org/2/library/functions.html#reload) (if I understand it correctly). I looked it up for you. I however stepped away from using hot class reloading. It was no longer required for the project. So I don't know how well Python's reload works or if it is applicable to your situation. I don't think I can be of much help to you here. Good luck with whatever you're planning on doing.
Answer: Disclaimer: I'm involved with JRebel development and therefore my answer might look a bit biased, but I'll do my best to explain.
To answer this question I first want to draw your attention to the fact that one main difference among the names you have listed is: some of the solutions require you to change application design, others don't.
Modularization solutions, like OSGi or JBoss Modules provide benefits if you follow the right path and modularize your application. Otherwise, if you deploy one silo bundle, it basically means you're restarting/redeploying the whole application, thus diminishing any benefits gained from this approach.
Play Framework is actually a full-stack framework that has the hot-deployment capabilities. Those capabilities vary depending on which version of the framework you use. But again, same story as with modularity - the framework enforces a certain programming model.
Apache Commons JCI isn't really a solution for hot updating the code. AFAIK, it just compiles and loads the class via new classloader. This also involves changing the application code as in the cases mentioned above. I'm not really sure if it is good or bad. The downside is that you hardly can do any broad integration with the ecosystem in this way. This approach is rather feasible for a self-made framework that would make use of this feature. Myself, I'd rather use a scripting language like Groovy, JRuby or JavaScript to achieve the same. Something like this, for instance.
JRebel, Fakereplace and DCEVM - those guys do not care about the programming model. But the difference is quite big:
DCEVM patches the JVM and its goal is to provide a complete hotswap solution, which it does.
JRebel is a java agent (hooked with -javaagent VM argument), that instruments the application code and loads the new versions of the classes by versioning them. The main value of JRebel is that it provides flexible configuration along with a huge amount of framework specific integrations, so that you can do a lot more than just a hotswap of java classes. For instance, add and autowire new beans in Spring application context, add new EJBs on the fly, and new Struts actions, etc.
Fakereplace is also an instrumenting agent, like JRebel but it has a lot less support for Java code changes (I assume) and the number of supported frameworks isn't as impressive.
Feenix can do as much as the Java Instrumentation API allows it to do. Which basically means it doesn't really add value on top of standard HotSwap of the JVM. Same for AgentSmith
UPDATE: this answer motivated the author of Feenix to come up with a new version - Feenix 2.0 which resembles the way JRebel works with classes. But as the author says himself - Feenix is still vastly inferior to JRebel. There are also a couple of similar solutions, like HotswapAgent and Spring Loaded - those tools also provide similar functionality but limited in their own way.
Now a bit on your specific problem, how it could be solved with JRebel:
Every module of the application should have its own configuration file, rebel.xml. By module, we mean, either the EAR, WAR, or any of the JAR dependencies in WEB-INF/lib (like in your case) or server specific libraries. The configuration file with point to the directory where the compiled classes are and JRebel will load the classes directly from that location. This all means that you do not need to assemble the entire JAR once you make a change to a Java class. Instead, you make a change and compile the source (leverage the IDE, instead of a build script). The compiled class will be reloaded by JRebel once the class is invoked within the application code.
Comment: Thanks for the elaborate answer! It is very helpful. Is there a reason though why you did not mention Apache Commons JCI FAM and AgentSmith in your answer?
Comment: Since ZeroTurnaround is canceling its floating license model I'm looking for JRebel alternatives and found this great answer. In the meantime there's a new kid-on-the-block: https://github.com/spring-projects/spring-loaded . It does have it's limitations but what it does it does well.
Answer: There's a new kid on the block, RelProxy, it is open source, is not so advanced like JRebel but it can be used to freely change a subset of your code in runtime and reload it with almost no performance penalty and no need of context reloading (no session lost) in development and production if you want.


Is there any good website to view running trails in the Bellevue, WA area?

Question: I'm in Bellevue, WA this week and am trying to find some good places to run. I'm sure I can just find a park and do many loops, but I'm looking for some mapped runs of 7-10 miles. I'm sure if a website is mentioned, it would be larger than just this area, but I'm particularly focused on Bellevue.
Comment: I would rephrase the question to have it less localized, which is one of the flagging/closing reason.
Answer: I travel a fair bit and always want to run in the places I visit, so I have the same problem. I usually try the following:

Google for runs using the search terms "running in <your location>" - that will very, very often come up with a site or two for official running clubs in your area. And they usually have a number of suggestions.
For the US, I have successfully used Running in the USA.
On a more global scale, I use MapMyRUN and Endomondo (you must log-in first).

For Bellevue, WA Endomondo returned 200+ routes in and about the city center...
Comment: MapMyRun has a great selection of runs from its users all over the world.
Answer: There are lists of Bellevue trails here:

http://www.bellevuewa.gov/nature_trails.htm
http://www.bellevuewa.gov/pedbike/TrailPlanMap.aspx

I like the Coal Creek Natural Area park, and you can run a good portion of it (though it is a hike for a good part of it more than runnable - too many slippery spots).
Also, I really enjoy the stretch of trail through the wetlands between Factoria and Enatai.  It's more of a biking/walking trail, and it seems like running might get you run down because you'd be in the way of bikers, and less able to hear their bells.  But it is a really nice walk during the summer.  It hooks up to other bits of road that run off into parks with trails, too.  I think the route is close to one side of the Mercer Slough park.
Answer: check out http://www.runmap.net/ and http://www.wandermap.net/


Regex para encontrar ocorrências de uma palavra antes da outra

Question: Preciso encontrar nos fontes do sistema situações onde TAction ocorra depois de TdxBar.
Isso irá acontecer em linhas diferentes, mas dentro do mesmo arquivo, por exemplo:
pnlVisao: TPanel;
tbToolBar: TdxBar;
btnCancelar: TButton;
actAbrir: TAction;

Neste caso a action está declarada depois da toolbar.
Tentei utilizar /(TdxBar)(?=TAction)/g mas não funcionou.
Comment: Em qual linguagem você vai usá-la?
Comment: Ia rodar no sublime ou no atom. É para pesquisar para realizar uma correção
Answer: Pelo que pesquisei tem uma flag para usar no Sublime que faz com que a regex seja multiline.
Tente com a Regex:
(?s)TdxBar.*?TAction

O (?s) diz ao Sublime que a regex é multiline fazendo com que o . também case com quebras de linha.
Fonte:
https://stackoverflow.com/questions/11992596/regex-in-sublime-text-match-any-character-including-newlines

Edit (2018-09-19)
Esbarrei com explicações na internet recentemente e decidi complementar esta resposta.
Este post no fórum do Sublime pergunta sobre uma nova engine para regex implementada no software. O criador do package control responde que a nova engine é utilizada para sintax highlight e lendo o post se descobre que a biblioteca Oniguruma é usada no Sublime Text.
Entrando no repositório, encontrei onde é documentada a flag (?s):
+ ONIG_SYNTAX_PERL and ONIG_SYNTAX_JAVA
    (?s): dot (.) also matches newline
    (?m): ^ matches after newline, $ matches before newline

Comment: Também fiquei surpreso quando descobri na época. Nunca precisei usar, descobri pesquisando para essa pergunta. :D
Comment: Perfeito, obrigado
Comment: cool! +1 ......
Comment: Não sabia que o Sublime suportava o `(?s)`, eu costumava usar a regex [que sugeri abaixo](https://pt.stackoverflow.com/a/396992/112052) :-)
Answer: Se a intenção for encontrar a lista dos ficheiros que contêm o referido padrão
sugeria:
grep  -zPl 'TdxBar(.|\n)*TAction' *

-z O opção -z (null separated records) faz com que o ficheiro seja carregado como
se fosse uma única linha; deste modo as expressões regulares podem ser multilingues
-l diz apenas os nomes dos ficheiros que contêm ocorrências do padrão
-Pexpressões regulares extendidas em sintaxe Perl
Answer: Complementando a resposta do fernandosavio, uma outra alternativa é usar a regex:
TdxBar[\s\S]+TAction

Em vez do ponto, eu uso [\s\S].
Os colchetes definem uma classe de caracteres e correspondem a qualquer caractere que esteja dentro deles. Por exemplo, [ab] significa "a letra a ou a letra b".
No caso, dentro dos colchetes temos:

\s: um atalho que corresponde a espaços, quebra de linha, TAB, etc (a lista exata de caracteres pode variar de acordo com a linguagem/engine utilizada).
\S: qualquer coisa que não seja um \s

Portanto, [\s\S] é "qualquer coisa que seja espaço, quebras de linha, etc, ou qualquer coisa que não seja isso". Resumindo, isso acaba correspondendo a qualquer caractere, incluindo as quebras de linha.
No fim, acaba tendo o mesmo efeito de usar . junto com a flag (?s) (o ponto, por padrão, corresponde a qualquer caractere, exceto quebras de linha, e a flag (?s) muda este comportamento, fazendo com que também corresponda a quebras de linha).
Eu também uso o quantificador +, que significa "uma ou mais ocorrências". Isso faz com que tenha que ter pelo menos um caractere entre "TdxBar" e "TAction".
Se você usar * (zero ou mais ocorrências), a regex também vai considerar os casos em que não tem nada entre eles (ou seja, se tiver "TdxBarTAction" no texto, a regex com * pega, mas a com + não, pois o + exige que haja pelo menos um caractere entre eles).

Por padrão, os quantificadores como * e + são gananciosos e tentam pegar o máximo possível de caracteres. Isso quer dizer que, caso hajam duas ocorrências de "TdxBar" e "TAction", a regex pegará todo o trecho entre o primeiro "TdxBar" e o último "TAction".
Se você sabe que eles só ocorrem no máximo uma vez no texto, e se você só quer saber se um está antes do outro, não há problema. Mas caso queira que a regex pegue todos os trechos isoladamente, basta cancelar a ganância usando um ? depois do +:
TdxBar[\s\S]+?TAction

Assim, o quantificador se torna preguiçoso e tenta pegar o mínimo de caracteres possível. Veja a diferença: aqui o quantificador preguiçoso encontra 2 matches, já aqui a versão gananciosa encontra apenas um match.


BSTR, how to make your own?

Question: I need to interface a Linux app to a server that uses bstr data. Can I "roll" my own code to make a bstr? I know the basics of a bstr, that it has a header with the byte size minus the null terminator and because of the header it can contain nulls in the middle of the string and basically all the rest of the rules that follow a bstr.
I am not sure on byte ordering the header or more intimate details such as do I pass the data on pointing to the header or the 5th byte like com does? Does anyone know where I can get this information or if anyone has written a bstr type class for linux? Or in general where I can find info on bstr details rather than just general overviews based on the Microsoft libs?
Thanks
Comment: This [link show BSTR lenght prefix is 4 bytes](https://msdn.microsoft.com/en-us/library/windows/desktop/ms221069(v=vs.85).aspx). I just view memory and i'ts true.
Answer: This may be interesting for you:
Eric's Complete Guide To BSTR Semantics
EDIT: Some more details, as gleaned from that article:
DISCLAIMER: This is off the top of my head, and my contain serious errors, up to but not limited the destruction of causality and the end of the known universe.
<code>struct BSTR_data {
    short count;
    wchar_t[] data;
};

typedef wchar BSTR;

BSTR * AllocateBSTR(wchar * str) {
    if(str == 0) return 0;

    short len = wstrlen(str);

    BSTR_data * ret = new char[sizeof(short) + (sizeof(wchar_t) + 1) * len];

    ret->count = len;

    memcpy(ret->data, str, sizeof(wchar_t) * 2 * len);

    ret->data[len] = 0;

    return (BSTR *)(ret + sizeof(short));
}

void DeallocateBSTR(BSTR * str) {
    if(str == 0) return;

    BSTR_data * bstr = (BSTR_data*)(str - sizeof(short));

    delete bstr;
}
</code>
This should give you a good idea of what's going on. Note that if cross-comparability with Win32 is important, you need to use SysAllocString, etc instead of this code.
Comment: Thanks, there is actually an article on MSDN that is a mirror of this, don't know who copied who. This helps but I still need lower lever details.
Comment: lol Sorry that is the same article on msdn, I'm burned out today.
Comment: Okay, I pulled some code out of nowhere, and added it to my answer. I make no guarantees if it's correct, however.
Comment: Thanks, I will look this over, it is the detail I am looking for thanks!
Comment: Why is count a short? I thought the header was 4bytes?
Comment: Thanks, so far this seems to be working, I have to wait until my server is up to do a real test but side by side testing next to a "real" BSTR seems to work.
Comment: This will not work so far in Linux, it will in Windows but porting it is not the same. wchar to me would be a unsigned short but wcslen will not accept and unsigned short if I convert the wchars over to that type. I have tried a bunch of different ways and so far nothing is working for linux. Also the L attribute wont work when allocating, again the type mismatch and so far nothing else will work for me.
Comment: Actually, it won't work in Windows either, since a BSTR has to be allocated from a special heap, but that's irrelevant on Linux. Anyway, try changing `wchar` to `wchar_t`. I don't think about this normally (`tchar` in Visual Studio is either `char` or `wchar_t`, depending on whether you're compiling unicode or not)
Comment: By the way, if you still have trouble, shoot me an email, so we can stop cluttering Stack Overflow :) We'll work it out, and report back here. My email is "`email@example.com" (where the substitutions are exactly as they appear in my user name)
Comment: Thanks, I will send one, I have not been back here in a few days. I have been swamped with some many things.
Comment: Thanks, I actually after this post became an expert on it, and now I've forgotten it all :)

BSTR, how to make your own?


Visual Studio 10, reset configuration manager to factory settings

Question: I have made several changes to both debug and release settings and now I want to return to factory settings. How could I do that?
Comment: Have you tried [this](http://msdn.microsoft.com/en-us/library/ms247075.aspx)
Answer: There is no easy way to go back to the default configuration for a project file.  When you create a new project it's based off a template located in your Visual Studio directory (e.g. C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ProjectTemplates\CSharp\Windows\1033\ClassLibrary.zip) and VS has no way of reapplying the template.  However, you can manually go back to the default configuration by doing the following:

Delete *.user file in your project's directory, this contains a few build configurations values such as command line arguments.
Create a new project that is the same type you're trying to reset.
For the new empty project and your existing project: right click and select Unload Project, right click and select Edit, then copy all the PropertyGroup sections from new project and paste them over all the PropertyGroup sections in your old project.

The above assumes you didn't actually add or remove any configurations or platforms, otherwise you will lose those changes.  That should get almost all the settings back to their defaults without messing up your source files or references.
Answer: If you have a backup of your project just search for the files that has .user extension on your backup then copy it and simply replace the files from your current project. Re-open your project. That's it
In my case there are 2 files with .user extension. It is sampleForm.vbproj.user and MyProject.vbproj.user
Answer: If you want to reset your VS follow below mentioned steps

On the Tools menu, click Import and Export Settings.
On the Welcome to the Import and Export Settings Wizard page, click Reset all settings and then click Next.
If you want to save your current settings combination, click Yes, save my current settings, specify a file name, and then click Next.


MaxMind API how to parse array?

Question: My MaxMind API Call receives this array:
object(MaxMind\MinFraud\Model\Score)#5 (8) {
  ["disposition":protected]=>
  object(MaxMind\MinFraud\Model\Disposition)#33 (3) {
    ["action":protected]=>
    NULL
    ["reason":protected]=>
    NULL
    ["rawResponse"]=>
    NULL
  }
  ["fundsRemaining":protected]=>
  float(4.94)
  ["id":protected]=>
  string(36) "604DE3C0-13DE-11E7-B630-507824A72470"
  ["ipAddress":protected]=>
  object(MaxMind\MinFraud\Model\ScoreIpAddress)#36 (2) {
    ["risk":protected]=>
    float(0.01)
    ["rawResponse"]=>
    array(1) {
      ["risk"]=>
      float(0.01)
    }
  }

How I get this value ["risk"]=>float(0.01) ?
Thanks in advance!
Comment: It is a protected property, so your object needs to provide a method to access the property.
Answer: Per the documentation, you can access the IP risk score with $resp->ipAddress->risk or the overall risk score with $resp->riskScore.
Comment: Thank you so much!

MaxMind API how to parse array?