Organizing ordered results into labeled sections

Question: I am trying to properly place my returned results into  labeled sections - example of what i mean.
Controller:
public IEnumerable<Users> GetUserList(int? id, int? pageNumber)
        {
            if (!id.HasValue)
                throw new HttpResponseException(HttpStatusCode.NotFound);

            int _pageNum = pageNumber.HasValue ? pageNumber.Value : 1;
            return new UserService().GetUsers(id.Value, pageNumber: _pageNum);
        }

View:

knockout.js/jquery: UPDATED
  var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// The ViewModel for the page
var viewModel = {
    Users: ko.observableArray([]),
    users: ko.observableArray([]),
    groups: ko.computed({
        read: function(){
            var groups = [];
            var groupLetter;
            for(var i = 0; i <letters.length; i++){
                viewModel.Users.groups[letters[i]].users([]);
            }
            ko.utils.arrayForEach(viewModel.users(), function (user) {
                groupLetter = user.name()[0].toUpperCase();
                if (groups.indexOf(groupLetter) < 0) {
                    groups.push(groupLetter);
                }
                groups[groupLetter].users.push(user);
            });
            return groups.sort();
        },
        deferEvaluation: true
    }),

};
for (var i = 0; i < letters.length; i++) {
    viewModel.users.groups[letters[i]] = { users: ko.observableArray([]) };
}

// The ViewModel for the page
var viewModel = {
    Users: ko.observableArray([]), //already a sorted list of users
    TotalRoster: null,
    CurrentPage: ko.observable(1),
    DataIsLoading: ko.observable(false),

};

So this returns in the view:
Amanda
Bob
Frank
Kate
Tim
I would like to have this displayed in the view:
A (Header)
Amanda
B (Header)
Bob
F (Header)
Frank
K (Header)
Kate
T (Header)
Tim
Mainly for a visual reference for viewers to see - it will show letter headers for the users that exist so if there are no users with a name that starts with S then there won't be a S header. Any help as to where i could look into or what this could be called i could read about that would be great.
Answer: You can group the users by their name on client side as follow :
// assuming the array is sorted
var users = ['Amanda', 'Anna', 'Bob', 'Frank', 'Francois', 'Sam'];

var lastGroup = null;
var vm = {
    groups: []
};

ko.utils.arrayForEach(users, function (user) {
    // known group
    if (lastGroup && lastGroup.name == user[0]) {
        lastGroup.users.push(user);
    } else {
        // unknown group
        lastGroup = {
            name :user[0], users : [user]
        };
        vm.groups.push(lastGroup);
    }
});

See fiddle
Answer: I can tell you that you're not going to be able to do this by just looping through the Users array in the binding.  Each iteration through will generate that templated html code provided for each of the User objects.
One approach I would consider is creating a dynamic array of groups that are based on the first letter of the User's name and attach these to the root observableArray object.
function ViewModel() {
    var self = this;
    var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    self.users = ko.observableArray([]);
    self.users.groups = ko.computed({
        read: function(){
            var groups = [];
            var groupLetter;
            for (var i = 0; i < letters.length; i++) {
                self.users.groups[letters[i]].users([]);
            }
            ko.utils.arrayForEach(self.users(), function (user) {
                groupLetter = user.name()[0].toUpperCase();
                if (groups.indexOf(groupLetter) < 0) {
                    groups.push(groupLetter);// not listed?  Add it
                }
                self.users.groups[groupLetter].users.push(user);// Add to the grouped users array
            });
            return groups.sort();
        },
        deferEvaluation: true
    });

    for (var i = 0; i < letters.length; i++) {
        self.users.groups[letters[i]] = { users: ko.observableArray([]) };
    }
}

Now in your View:

jsFiddle
*Note:  You'd only want to go this route if you had a need to update these names dynamically on the client side.  If this list were to remain static, it'd probably be best to go with Damien's answer.
Comment: Thanks i will go ahead and try both out. Also i updated my post with my viewModel for the page in where i call the Users for the foreach. Would i place what you have in your viewmodel into the viewmodel where i have `users:ko.observableArray([])` or would i create a separate viewmodel?
Comment: If you can help it, I would keep it all in one ViewModel.  In your case, you're defining a ViewModel in an object directly instead of a constructor function.  Which is fine, where I have `self.users.groups = ko.computed(...);`, you would add that after your ViewModel declaration and it would look like: `viewModel.Users.Groups = ko.computed(...);`  Just be wary of the case sensitivity.  You're using upper case where as I'm using camel case.  Also, where I have `self.` references, you would have `viewModel.` references.
Comment: So i went ahead and implemented your solution but when i run it - in the console i get an uncaught error: Uncaught TypeError: Cannot set property 'A' of undefined and that references to the `for loop`
Comment: If you look at my [fiddle](http://jsfiddle.net/QChNw/), I bet that's happening on line 10.  It happens because `self.users.groups` isn't defined yet when the computed tries to do its first evaluation during the declaration.  The part you may have overlooked is on line 21.  This tells KO, hey don't evaluate this yet until something calls this computed.  This allows you to make a reference to the computed, within the computed, before it's declared.


Shift the mean of a (not) normal distribution but keep same scale

Question: Warning: I am not a statistician, so please go easy!
I have a (not) normally distributed measure of a population, with possible values from 0 to 100%. Its mean is 60%.
I need to be able to shift the distribution to give it a mean of 70%.
I obviously can't just add 10% to all scores because anyone who previously scored 100% would now score an impossible 110%.
So is there a formula I can use to shift the population data so the mean is increased, while maintaining integrity of the limits of 0% and 100%?

Edited because obviously this non-statistician elicited eye-rolls from the more knowledgeable people in the room.
So it's apparently not a normal distribution but it has a bell-curve shape. The rest of what I'm trying to achieve holds true so if anyone is able to offer any useful suggestions, I'd still be interested to hear.

Editing to add further information. I have to be somewhat vague due to IP, but I'll try to explain best I can.
We have two measures that are used in a larger calculation. We know that one is inherently more trustworthy than the other, by a factor of about 10%, due to the way the data is collected. That cannot be resolved. However, when being used in the calculation, we need them to be calibrated to the same scale. The thought was that we could shift the population of one in order to match the mean of the other, so calibrate them and give us more meaningful results. Does that help?
Comment: Since the normal distribution is defined on $(-\infty,\infty)$ then your variable cannot be normally distributed. In any case, if your distribution is bounded, and you want to change the mean then the distribution is likely to not be normal anymore since it will be skewed. So maybe your question should be "how do I transform my arbitrary distribution into another arbitrary distribtuion?"
Comment: @user2974951 is bang on here. Positive advice about what to do probably depends on (1) knowing why you want to do this (2) agreeing that your goal makes sense statistically (3) knowing more about your data. As you're aware your goals are on the face of it contradictory.
Comment: @rusiano: no, that is wrong. The standard normal is just as unbounded as any other normal.
Comment: Rather than change the measure, why not change the 'larger calculation' in a way that accounts for the difference between the measures?
Comment: @rusiano Not so. The standard normal is not bounded any more (or less) than any other normal.
Comment: Still, there is a normal distribution between [0, 1] and it is the standard normal distribution (or Z-distribution).
Comment: Do you want to modify the *distribution* your data presumably are sampled from ("bell curve" sounds like a [beta](https://en.wikipedia.org/wiki/Beta_distribution), where you could shift the mean but keep the overall shape), or do you want to transform *every single observation*? Can you edit your post to include your data?
Answer: Suppose your original observations are $x_1, \dots, x_N$, all between $0$ and $1$. One simple transformation would be to take an observation $x_i$ and shift it closer to $1$ by some factor $\alpha$, i.e., to reduce its distance from $1$:
$$ x_i \mapsto x_i':=1-\alpha(1-x_i). $$
If your original mean is
$$ \bar{x} = \frac{1}{N}\sum_{i=1}^N x_i, $$
then your new mean is
$$ \bar{x}' = \frac{1}{N}\sum_{i=1}^N x_i' = \frac{1}{N}\sum_{i=1}^N \big(1-\alpha(1-x_i)\big) = 1-\alpha + \alpha \bar{x}. $$
Solve this for $\alpha$,
$$ \alpha=\frac{1-\bar{x}'}{1-\bar{x}}, $$
and transform your data. Here is a little illustration in R:
<code>xx <- c(1,rep(0.1,8),rep(0.2,25),rep(0.3,60),rep(0.4,90),rep(0.5,100),
  rep(0.6,90),rep(0.7,60),rep(0.8,25),rep(0.9,8),1)
mean(xx)
# [1] 0.5021368

desired_mean <- 0.7
alpha <- (1-desired_mean)/(1-mean(xx))
xx_prime <- 1-alpha*(1-xx)
mean(xx_prime)
# 0.7
</code>

This approach will keep the order relationship of your original data, but it will change the variance. If you want to also keep the variance but change the mean (both only approximately), you could proceed as here: fit a beta distribution with parameters $a$ and $b$ to your data, then determine parameters $a'$ and $b'$ of a new beta distribution with the desired mean and variance, then transform any observation $x$ to
$$ x\mapsto F_{a',b'}^{-1}\big(F_{a,b}(x)(x)\big), $$
where $F_{a,b}$ is the cumulative distribution function (CDF) of the beta distribution. This can be done easily in R or Python. However, note that this changes the underlying fitted distribution, and the mean and variance of the transformed data will likely not precisely what you desired, but a little off.
Comment: I edited my answer. I'm not surprised you didn't get it to work, because I had an error in my calculation. I'm sorry for the confusion. It should now work, or at least seems so given your data.
Comment: Thanks @Stephan, this is a big help. However, I can't get it to work. Hopefully you can point out what I'm doing wrong?

I've put together some dummy data, format "value (count)".
0 (1), 0.1 (8), 0.2 (25), 0.3 (60), 0.4 (90), 0.5 (100), 0.6 (90), 0.7 (60), 0.8 (25), 0.9 (8), 1 (1)

Mean is 0.5.
If I want to transform so the mean is 0.6, using the formula above I would have  = (¯′N - 1)/(¯N - 1) = 1.2
Then each value ′:=1−(1−).
New mean, however, is then 0.4 not 0.6, and I end up with negative values for smaller values of .

Any help, please?
Comment: I'll take a look as soon as I find the time.


How to populate flex combo box with xml data

Question: here is the xml data :
<root>
    <recommendedMaterials>
        <value label="Aluminium" data="0" />
        <value label="Iron" data="0" />
    </recommendedMaterials>

</root

My code :

<mx:Script>
        <![CDATA[
public function populateRecommendedMaterials(xml_val:XML)
            {
                 materials_Cmb.dataProvider=(xml_val.recommendedMaterials);
            }

    ]]>

</mx:Script>

    <mx:ComboBox x="212" y="164" id="materials_Cmb" dataProvider="materialsCmb_Dp"></mx:ComboBox>

</mx:Canvas>

The problem is that the whole xml gets populated. I just want the labels. :(
Answer: There are two approaches here, depending on what you need. In either case the data you want are the children of the recommendedMaterials node, not the node itself (which is what you did).
materials_Cmb.dataProvider =
    new XMLListCollection(xml_val.recommendedMaterials.children());

This should already do the trick. Note that I wrapped the XMLList in an XMLListCollection: this is not strictly necessary with the mx:ComboBox, because it will do the same internally, but for Spark components it would be mandatory.
Another more concise solution would be to just find all the 'value' nodes, but I don't know whether that approach fits your bill.
materials_Cmb.dataProvider =
    new XMLListCollection(xml_val..value);

Also don't forget to assign the correct 'labelField' in the ComboBox:
<s:ComboBox labelField="@label" />

The @ sign represents an XML attribute.
Comment: ok.. thnx a lot!
However i was already confused between XML and XMLList, and you added a new one XMLListCollection. :(.  Added the term to my research :)
Comment: @VishwasGagrani Just to get you started: XML and XMLList are low-level ActionScript/E4X classes (E4X being the XML parsing idiom), whereas XMLListCollection is a class from the Flex framework. Basically XMLListCollection is to XMLList what ArrayCollection is to Array.


How to read a file from a java class, both are in the same jar

Question: I have following structure in jar

myjar.jar -> com -> MYProgram.class
       -> file.txt

In MYProgram i am trying to do:
getClass().getResourceAsStream("../file.txt")

I am getting NullpointerException when i try to read the inputstream..
Where is it going wrong ?
Answer: Either use
getClass().getResourceAsStream("/file.txt")

or
getClass().getClassLoader().getResourceAsStream("file.txt")

(ClassLoader.getResourceAsStream always takes an "absolute" resource name.)
I don't believe navigating up the "directory hierarchy" works in getResourceAsStream - the path either has to be relative to the given class but without navigating back up the tree, or it has to be absolute to start with.
Answer: Try the absolute path:
getClass().getResourceAsStream("/file.txt")

The Javadoc for getResourceAsStream says:

If the name begins with a '/'  ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
    modified_package_name/name

Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').

This would turn your path into this absolute path:
/com/../file.txt

I don't think the .. notation is respected.  It literally looks for the above absolute path.


Proof using chebyshev's inequality

Question:
Consider the sequence of random non-negative values $X_1...X_n$ where
  $E[X_n], Var[X_n] > 0$ for all $n \in \mathbb{N}$ and:
  $$\lim_{n\rightarrow \infty} \frac{Var[X_n]}{E[X_n]^2} = 0$$
  Prove:
  $$\lim_{n\rightarrow \infty} P(X_n >0) = 1$$

How would I prove this using Chebyshev's inequality?
Answer: Chebyshev's inequality is in the right direction, but before trying to apply it without a plan, take a look at how assumption looks like: it says that
$$
\lim_{n\rightarrow \infty} \frac{Var[X_n]}{E[X_n]^2} = 0.
$$ If one looks at the assumption carefully, one may notice that $\frac{1}{E[X_n]}$ plays a role of normalizing constant. So, by letting $$X_n' :=\frac{X_n}{E[X_n]},$$ one gets
$$
E[X_n'] = 1,\quad \lim_{n\rightarrow \infty} Var[X'_n] = 0.
$$ The problem gets simpler now. Chebyshev's inequality implies that $$
P(X_n>0) = P(X'_n>0)\geq P(|X'_n -1|\leq \frac{1}{2}) \geq 1- 4Var[X'_n]\to 1,
$$
(in fact, $X'_n \to_p 1$ in probability) and hence that $\lim_{n\to\infty}P(X_n>0)=1$ as desired.

Proof using chebyshev's inequality


What is the angle the car turned?

Question: A car drives a route through town as indicated alongside, crossing square M
five times while doing so. How large is the total angle his car turned through when it has completed the route?

I just don't understand how the answer is supposed to be 1080. I just see 5 triangles, so I immediately assumed 900.
Answer: Note that if the path were a triangle, the car would turn $360$ degrees, not $180.$  The amount the car turns is the exterior angle, not the internal angle at each point, which is $180$ degrees minus the interior angle.  If the car went all the way around each triangle, it would turn $5 \cdot 360= 1800$ degrees.  It did not make the turn at each of the angles in the square.  Because the five segments are straight, the five angles inside the triangles add up to $180$ degrees, so the angle we didn't turn is $5 \cdot 180 - 180=720$ and the total angle turned is $1800-720=1080$ degrees.
Comment: inside the triangles? Also, if the line is straight, why can't we say 0 degrees? The car doesn't turn on a straight line?
Comment: @YlykCoitus:  do you see the argument for $360$ in a triangle?  At each corner of an equilateral triangle you turn $120$ degrees, not $60$.  In the five triangle problem, I am trying to figure out how much the car would have turned in the center if it went all the way around all the triangles, so I can subtract it.
Comment: I really don't understand the slightest bit of this
Answer: The Car travels through 5 equal triangles. Each of the triangles vertex angle (angle centered at M) is $\frac{360}{10} = 36^0$
Each time, the car traverses the entire triangle, it covers a total angle of $180^0$ and then starts traversing the next triangle, which is at an offset of $36^0$ from its current position. Note, as there are 5 equal triangles with vertex angle of $36^0$, and the triangles are equally spaced, they are each at an angle of $36^0$.
So For each triangle, the car traverses $180^0+36^0=216^0$.
As there are 5 triangles, total angle covered is $216^0 \cdot 5 = 1080^0$
Comment: This seems logical and easy to follow. I'm only concerned by one thing: how are you sure they are 5 isosceles triangles?
Comment: @YlykCoitus: On a second though, it actually doesn't matters as long as the car returns back to $M$ to start on a different triangle. The reason I said isosceles is because as per your diagram, the sides are equal (notice two slashes next to the sides of the triangle)
Comment: @YlykCoitus:  I agree we are not given that the triangles match.  My solution does not assume that.  This one might help you understand the more general case.
Answer: Trace the route from any point back to the start. The middle of the left hand edge, heading north, is a convenient starting point. You are always turning clockwise so the turning angles are cumulative. Count how many times you turn through north. Each complete rotation through north is $360^{\circ}$.

What is the angle the car turned?


GCMRegistrar cannot be resolved when open gcm-demo-client by eclispe

Question: Still got many error message about GCMRegistrar after import GCM Demo ( gcm-demo-client ) and google-play-service_lib in eclispe.
did i missed some step?
https://i.stack.imgur.com/o3Zqz.jpg
Comment: Did you say  that your project uses the google play services project ?
Comment: @StephaneMathis , Thank you for reply. I'm trying to open a demo app downloaded from http://goo.gl/N9Wa9P .. then i go the error message of GCMRegistrar. (Google Play services had set up already in this demo app project)
Comment: Right click on your project, select Properties, then Android. Do you see the google play service lib listed ?
Comment: @StephaneMathis , Yes i did..That's why i'm so confused .. http://imgur.com/By1gqlH
Answer: as your example : https://github.com/google/gcm
Step 1: import Android code, folder \gcm-client\, not \samples\gcm-demo-client\, then will see DemoActivity Android project.
Step 2:  add the Play Services library to your project, DemoActivity -> Proterties -> Android -> Library -> add -> google_play_services
P.S. The Google Play services SDK is saved in your Android SDK environment at /extras/google/google_play_services/
Step 3: add android-support-v4.jar, it saved \extras\android\support\v4
Step 4: modify project.properties, target min is android-10
Good luck!!
Comment: It works by following your procedure!! Big thanks! May i ask why should change target min to android-10 ? It shows configChanges="orientation|keyboardHidden|screenSize" in AndroidManifest.xml goes wrong.
Comment: if android-8, "regid.isEmpty()" in DemoActivity.java on my eclipse will error ; and android-9 other place will error. so if you can try it, maybe your eclipse won't.
Answer: Its because of you have not put gcm library in your project. download it and add it to your project.
it can be found from here Andoird_SDK_Folder\extras\google\gcm\gcm-client\dist
Thank you,
Comment: Hi, Thank you for reply. gcm library? Do you mean google-play-service ?? Because i only see this lib should be imported into project from google official site. http://developer.android.com/google/gcm/client.html


Netsuite reconfigure inventory detail error

Question: On a custom record creation i am calling a map reduce script that in creating a negative inventory adjustment.
The script is called on after submit.
I am using following code to populate the inventory detail subrecords
<code>for (var n = 0; n < cp_lotsearch.length; n++) {
                    if (cree_onhand > 0) {
                        var cp_lotid = cp_lotsearch[n].getValue({name: 'internalid'});
                        var cp_parentcasenum = cp_lotsearch[n].getValue({name: 'custrecord_nsts_ia_lot'});
                        var itemsearch = search.create({
                            type: 'item',
                            filters: ['inventorynumber.inventorynumber', 'is', cp_parentcasenum],
                            columns: [search.createColumn({name: "quantityonhand", join: "inventorynumber"})]
                        }).run().getRange({
                            start: 0,
                            end: 1000
                        });
                        var qtyonhand = itemsearch[0].getValue({name: 'quantityonhand', join: 'inventorynumber'});
                        var remain_qtyonhand = Number(qtyonhand) - Number(cree_onhand);
                        if (remain_qtyonhand >= 0) {
                            var reduceqty = 0 - Number(cree_onhand);
                        } else {
                            var reduceqty = 0 - Number(qtyonhand);
                        }
                        log.debug("reduceqty", reduceqty);
                        subrecord.insertLine({sublistId: 'inventoryassignment',line: n});

                        subrecord.setSublistText({ sublistId: 'inventoryassignment',fieldId: 'issueinventorynumber',line: n,text: cp_parentcasenum});
                        subrecord.setSublistValue({sublistId: 'inventoryassignment',fieldId: 'binnumber', line: n, value: cree_bin});
                        subrecord.setSublistValue({sublistId: 'inventoryassignment',fieldId: 'quantity',line: n,value: reduceqty});
                        log.debug("reduceqty added to inventory detail", reduceqty);
                        cree_onhand = Number(cree_onhand) + Number(reduceqty);

                    }
                }
                var invadjid = parentcase_inv_Adj.save({
                    enableSourcing: true,
                    ignoreMandatoryFields: true
                });
</code>
When i try to run this code i am getting following error:
"type":"error.SuiteScriptError","name":"USER_ERROR","message":"You still need to reconfigure the inventory detail record after changing the quantity."
Same code is running perfect in sandbox account but in production it is throwing error
Can anyone help me to solve this error?
I Got one solution in suite answer that i already tried but it is not working here is link to it:
https://netsuite.custhelp.com/app/answers/detail/a_id/80790/kw/reconfigure%20error
Answer: I've discovered this error can be triggered server-side if :

multiple units of measure feature is enabled.
the stock units of measure are not 1-to-1, i.e. the receipt unit is in packs of 20, but the base unit of the UOM is 1's.
the item is serialised.

However, if the same is attempted client-side, the error becomes "The total inventory detail quantity must be XX" (XX being the quantity set in "adjustqtyby" on the inventory adjustment line).


MySQL table optimization for chat server

Question: Hi i am making a server using Netty and MySQL.
My server's primary task is to record user's info, and chats.
I am very new to database and I am stuck at writing the schema for chats.
I need to record the chat room number, sender ID, reciever ID, content, and timestamp for each chat sent from the client.
I think about 50 chats for each chat room will be sent. And at least 100 chat rooms will be created daily.
I am thinking of making one table for every chat room created. However, this will make about 3000 tables every month.
If I recorded all the chat rooms in one table, the table will be very long. I am guessing retrieving records from that table will take a lot of resources.
This part is where I am stuck. What is the normal practice when recording chats?
Comment: 3000 tables a month really is not much for a database. For your own sake, you could have a scheduled job which removes old data every now and then.
Answer: It should be fine to have a database row for each chat room with foreign key relationships between messages, users and rooms.
Have a rooms table:
id, name, created

a users table:
id, username, password, created

a messages table:
id, room_id, user_id, message, time

then use some very simple JOINs in order to retrieve the data you want. For example, to retrieve the latest messages in a chat room:
SELECT u.username, m.message, m.time FROM messages
LEFT JOIN rooms r ON m.room_id = r.id
LEFT JOIN users u ON m.user_id = u.id
WHERE r.name = 'chatroomName'
AND m.time > lastPolledTime

replace lastPolledTime with the time that you last checked for messages, in order to remove duplicates.
Comment: That query has very bad performance as you are having a WHERE that spans 2 different tables. MySQL will only be able to use one index. So each query will pull ALL rows for chatroom "chatroomName" OR ALL rows from ALL rooms where time > lastPolledTime.


Proof of posterior consistency

Question: Given the model
$x_1,...,x_n$ ~ $Poi(\theta)$ (iid),
and the prior
$\theta$~$ Gamma(a,b)$.
How do we prove the consistency of posterior distribution?
Thanks in advance.
Modification:
The definition of posterior consistency given on my lecture slides is:
"given the data $x_1,...,x_n$ iid and the model f(x;$\theta$), if we have posterior consistency at $\theta_0$, then
$\forall \epsilon$,
   $\lim_{n\rightarrow +\infty}\pi(|\theta-\theta_0|>\epsilon|X)$=0."
$\theta_0$ is not specified but I think it is the true value of $\theta$.
Comment: Thank you.  That was important, because consistency is not a property of any *distribution*: it's a property of the estimator and the model.  (Presumably, "$\pi$" means "probability.")  As far as your question goes, could you please indicate what attempts you have made towards a solution?  For instance, have you worked out what the posterior distribution actually is in terms of $a$, $b$, and $X$?
Comment: Could you explain what you mean for a distribution to be consistent?
Comment: I have added this in the original question.
Answer: Writing $X^{(n)}=(X_1,\dots,X_n)$, Bayes theorem tells us that
$$
  \Theta\mid X^{(n)}\sim\mathrm{Ga}\!\left(a+\sum_{i=1}^n X_i,\,b+n\right).
$$
Define
$$
  M=\mathrm{E}[\Theta\mid X^{(n)}]=\frac{a+\sum_{i=1}^n X_i}{b+n}
$$
and
$$
  V=\mathrm{Var}[\Theta\mid X^{(n)}]=\frac{a+\sum_{i=1}^n X_i}{(b+n)^2}.
$$
For any given $\epsilon>0$, if $|\Theta-M|<\epsilon/2$ and $|M-\theta_0|<\epsilon/2$, then, using the triangle inequality, we have
$$
  |\Theta-\theta_0| = |\Theta-M+M-\theta_0|\leq |\Theta-M|+|M-\theta_0| < \epsilon.
$$
Considering the contrapositive of the previous statement, we see that
$$
  \{|\Theta-\theta_0|\geq\epsilon\} \subset \{|\Theta-M|\geq\epsilon/2\} \cup \{|M-\theta_0|\geq\epsilon/2\}.
$$
Hence, monotonicity and Chebyshev's (Чебышёв) inequality give us
$$
  \Pr(|\Theta-\theta_0|\geq\epsilon\mid X^{(n)}) \leq \frac{4V}{\epsilon^2} + \Pr(|M-\theta_0|\geq\epsilon/2\mid X^{(n)}).
$$
Let $\mu_0$ be a $\mathrm{Poi}(\theta_0)$ distribution and note that $V\to 0$ a.s. $[\mu_0]$, and $M\to \theta_0$ a.s. $[\mu_0]$, as $n\to\infty$.
This is essentially what you need to see that this posterior is "simulation consistent". That is, if you're simulating iid $X_i$'s from a $\mathrm{Poi}(\theta_0)$ distribution, then your posterior distribution will concentrate all its mass at $\theta_0$, as your sample size goes to infinity.
To learn how to write a precise proof, please study Schervish (Theory of Statistics), section 7.4.1 (Consistency of Posterior Distributions).
Comment: I just link this proof also https://math.stackexchange.com/questions/1178435/how-to-apply-triangle-inequality-in-a-probability-statement

Proof of posterior consistency


I have the following sequence and I want to prove the monotonicity of this sequence

Question: The following sequence is provided and I am required to prove that the sequence is monotone and convergent.
$\left \{ \cos(\frac {1}{2}\arctan (\frac{-n}{2})^n)\right \}$
As far as convergence of the sequence is concerned, it will surely converge as for large $n$, the $\arctan (\frac{-n}{2} )^n$ part will tend to $π/2$. Consequently, the whole sequence will converge to $\frac{1}{√2}$. But, I am not able to prove the monotonicity of the given sequence. Any help would be appreciated. Thanks in advance.
Comment: Is that exponent $\;n\;$ on the arctangent's argument or on the whole arctan ? One must try to be as clear as possible when writing down messy stuff...
Comment: It's the exponent of its argument.
Answer: First, observe that the values of the argument of the arctangent, namely $\;\left(-\frac n2\right)^n\;$ , are going "to jump" from positive to negative values (according to $\;n\;$ even or odd, of course), but we don't care as $\;\cos x\;$ is an even function. Second, we have that
$$-\frac\pi2<\arctan x<\frac\pi2\implies-\frac\pi4<\frac12\arctan x<\frac\pi4\;$$
so all the values of $\;\frac12\arctan\left(-\frac n2\right)^n\;$ are within the interval $\;\left[-\frac\pi4,\,\frac\pi4\right]\;$ . Thus, we can write
$$\cos\left[\frac12\arctan\left(\frac{-n}2\right)^n\right]=\cos\left[\frac12\arctan\left(\frac n2\right)^n\right]$$
and also: as $\;n\to\infty\;$ , we have that
$$\;\left(\frac n2\right)^n\xrightarrow[n\to\infty]{}\infty\implies\frac12\arctan\left(\frac n2\right)^2\nearrow{}\frac\pi 4\implies\cos\left[\frac12\arctan\left(\frac n2\right)^n\right]\searrow\;\ldots$$
and you then get your sequence is monotone descending and obviously (?) bounded below, so it is convergent (in fact, the above already gives you the value of the limit, if you payed attention...)
Answer: Thanks to the cosine, you can ignore the minus sign. Then $(\frac n2)^n$ is obviously a growing function for $n\ge1$. The arctangent is strictly growing on $\mathbb R$ and outputs a value in $[0,\frac\pi2)$. Finally, the cosine is decreasing in $[0,\frac\pi4)$, and bounded below.
The sequence very quickly tends to $\sqrt{\frac12}$.


Treating missing values in panel data set

Question: You can often see in the empirical papers that do some kind of the regression analysis on economic data something like this "we drop the companies from our sample which do not have the observation in each year of the reporting period". Doing so the author reduces his/her sample. Another way to deal with missing values is to impute them.
My questions therefore are: what is more correct to drop or replace missing values while doing regression analysis?
Besides, is it better to use some sophisticated methods that allow us to account for missing values in dependent/independent variables or impute the values?
For example, I've panel data for 100 companies in the period of 6 last years. For them I've collected 5 variables such as profit, sales etc. For some companies I have missing values in 1-2 periods and for other in 4-5 periods. I am going to conduct the time series/cross-sectional analysis. Is it better  1). to leave all as it is, 2). to drop companies which have missing values in 4-5 periods (than the sample reduces by 50%) and rest of missing values replace with the mean values?
Besides what to do if the missing values are dependent variables? Does the imputation methods differ for dependent or independent variables?
Comment: The Amelia II documentation has a helpful discussion of why imputation is important in the social sciences.
Comment: Dropping observations with missing values and leaving them in the dataset are essentially equivalent. It's a software issue whether missing values are ignored automatically or you must instruct the software to do that but it's the same result either way. The general question here is whether and why to impute. That seems to be wrapped with a specific question of whether you should use only complete panels.
Comment: @user777 Thank you, I will read about this program.
Comment: @Nick You are right e.g. STATA will ignore all observations with missing values and conduct the regression analysis with the smaller sample. My problem is how to impute the values for that companies that has little observation over the time or is it more correctly to drop all companies with missing values.
Comment: Thanks for the detail on Stata, which happens to be a familiar program. See also http://www.statalist.org/forums/help#spelling More importantly, I don't see how I can help you on whether multiple imputation is a good idea for your project. It's popular because missing values are so common, but most applications I hear about skate rapidly over the question of whether the key assumptions about missingness are satisfied. Imputation that respects time series flavour seems especially problematic.
Comment: Amelia II is built specifically for imputing missing data in cross-sectional and time-series data. The documentation associated with that would be a good place to look
Comment: The key question:  are the values missing at random?  Or is there some process that determines the misingness, and does this process affect the outcome?  If the latter, estimates from complete-case data will be biased.  Imputation is tricky however -- packages that do it for you can be a bit of a black box, and doing it yourself is time-consuming.
Comment: @generic_user I am not sure, weather data missing at random. The database I use has the incomplete data, because the information is expensive, so they do not have everything that exist.
Answer: Imputation is very useful for improving the accuracy of your parameter estimates in situations where a significant amount of data would otherwise be deleted.  Consider that in a study with, for example, 100 observations and four regressors, each with a 10% missing observation rate, you'll only be missing 10% of the data but on average you'll be deleting about 34% of the observations if you drop each observation with one or more missing values - which is what happens if you just run the data through a standard regression package.  You'll be deleting much more data (2.4x in fact) than is actually missing.  In addition, unless your data is missing completely at random, case deletion can introduce bias into your parameter estimates.
It is typically better to use an imputation algorithm that captures at least the covariance structure of the data and generates random numbers (rather than replacing with mean or median values.)  This holds true especially if you're going to be doing some estimation using the imputed data, because you'll get more accurate estimates of the covariance matrix of the parameters.  Replacing by the mean value will give you overly optimistic standard errors, sometimes by quite a bit.
I've included an example using the default imputation method from the mice package in R.  The example has a regression with 100 observations and four regressors, each with a 10% chance of a missing value at every observation.  We compare the std. errors of the estimates for the complete-data regression (no missing values), the case deletion regression (delete any observation with a missing value), mean imputation (replace the missing value by the mean of the variable), and a good quality imputation routine that estimates the covariance matrix of the data and generates random values.  I've constructed nonlinear relationships between the regressors such that mice isn't going to model them using their true relationships, just to add a layer of inaccuracy to the whole thing.  I've run the entire process 100 times and averaged the standard errors of the four methods for each of the parameters for comparative purposes.
Here's the code, with a comparison of the standard errors at the bottom:
results <- data.frame(se_x1 = rep(0,400),
                      se_x2 = rep(0,400),
                      se_x3 = rep(0,400),
                      se_x4 = rep(0,400),
                      method = c(rep("Complete data",100),
                                 rep("Case deletion",100),
                                 rep("Mean value imputation", 100),
                                 rep("Randomized imputation", 100)))
N <- 100
pct_missing <- 0.1
for (i in 1:100) {
  x1 <- 4 + rnorm(N)
  x2 <- 0.025*x1^2 + rnorm(N)
  x3 <- 0.2*x1^1.3 + 0.04*x2^0.7 + rnorm(N)
  x4 <- 0.4*x1^0.3 - 0.3*x2^1.1 + rnorm(N)
  e <- rnorm(N, 0, 1.5)
  y <- x1 + x2 + x3 + e   # The coefficient of x4 = 0

  # Complete data regression
  mc <- summary(lm(y~x1+x2+x3+x4))
  results[i,1:4] <- mc$coefficients[2:5,2]

  # Cause data to be missing
  x1[rbinom(N,1,pct_missing)==1] <- NA
  x2[rbinom(N,1,pct_missing)==1] <- NA
  x3[rbinom(N,1,pct_missing)==1] <- NA
  x4[rbinom(N,1,pct_missing)==1] <- NA

  # Case deletion
  mm <- summary(lm(y~x1+x2+x3+x4))
  results[i+100,1:4] <- mm$coefficients[2:5,2]

  # Mean value imputation
  x1m <- x1; x1m[is.na(x1m)] <- mean(x1, na.rm=TRUE)
  x2m <- x2; x2m[is.na(x2m)] <- mean(x2, na.rm=TRUE)
  x3m <- x3; x3m[is.na(x3m)] <- mean(x3, na.rm=TRUE)
  x4m <- x4; x4m[is.na(x4m)] <- mean(x4, na.rm=TRUE)

  mmv <- summary(lm(y~x1m+x2m+x3m+x4m))
  results[i+200,1:4] <- mmv$coefficients[2:5,2]

  # Imputation; I'm only using 1 of the 5 multiple imputations
  # It would be better to use all the multiple imputations, though.
  imp <- mice(cbind(y,x1,x2,x3,x4), printFlag=FALSE)
  x1[is.na(x1)] <- as.numeric(imp$imp$x1[,1])
  x2[is.na(x2)] <- as.numeric(imp$imp$x2[,1])
  x3[is.na(x3)] <- as.numeric(imp$imp$x3[,1])
  x4[is.na(x4)] <- as.numeric(imp$imp$x4[,1])

  mi <- summary(lm(y~x1+x2+x3+x4))
  results[i+300,1:4] <- mi$coefficients[2:5,2]
}

options(digits = 3)
results <- data.table(results)
results[, .(se_x1 = mean(se_x1),
            se_x2 = mean(se_x2),
            se_x3 = mean(se_x3),
            se_x4 = mean(se_x4)), by = method]

And the output:
                  method se_x1 se_x2 se_x3 se_x4
1:         Complete data 0.208 0.278 0.192 0.193
2:         Case deletion 0.267 0.359 0.244 0.250
3: Mean value imputation 0.231 0.301 0.212 0.217
4: Randomized imputation 0.213 0.271 0.195 0.198

Note that the complete data method is as good as you can get with this data.  Case deletion results in considerably less accurate parameter estimates, but the randomized imputation of mice gets you almost all the way back to the accuracy you would get with complete data.  (These numbers are a little optimistic, as I'm not using the full multiple imputation approach, but this is just a simple example.) The mean value imputation in this case appears to have improved things considerably relative to case deletion, but is actually overly optimistic.
So the tl;dr version is: impute, unless you'd only be missing a very small fraction of your cases using case deletion (like 1%).  The big caveat is: understand the assumptions that are required for imputation first!  If data is not missing at random, and I'm using that phrase non-technically so look up what imputation requires in this respect, imputation won't help you, and may make things worse.  But that's a topic for another question.  Here are a couple of links which might be helpful: overview of imputation, missing data rates and imputation, different imputation algorithms.
Comment: Thank you for such extensive explanation and a lot of useful links. Now I now where to start.


Adding outlets and actions in XCode 4 for a Monobjc Application

Question: I've been following the tutorials in http://www.monobjc.net/ in order to do a small Mac app using monobjc for the GUI. However they are using Interface Builder 3 in order to create the actions and outlets that are needed and I can't find a way to add these into the app delegate when I edit the xib file in XCode 4. Is there a way to do this?
Comment: Are you using MonoDevelop to develop the application ?
Comment: Yes, I am using MonoDevelop 22.214.171.124 on Lion
Answer: I have updated the documentation to include a step-by-step guide on how to create action/outlet.
I hope it is clear enough for you to go with Monobjc/MonoDevelop/Xcode.


Show that the following are monotone classes

Question: While reading the proof of Monotone class theorem from this book pg. 31, I came accross with the following statement.
Let $\mathcal{A}$ be an algebra and $\sigma(\mathcal{A})$ be the smallest $\sigma$-algebra that contains $\mathcal{A}$. Let also $mc(\mathcal{A})$ be the smallest monotone class that contains $\mathcal{A}$.
Then, statement says, the following are monotone classes,
$$\mathcal{C}_1 = \{ E \in \sigma(\mathcal{A}):E^c \in mc(\mathcal{A})\}$$
$$\mathcal{C}_2 = \{E\in \sigma(\mathcal{A}):^\forall F \in \sigma(\mathcal{A}), E \cup F\in mc(\mathcal{A})\}.$$
How can we show that these collections of sets are monotone classes?
Answer: $\mathcal{C_1}$ is a monotone class.
You know that, $\sigma(\mathcal{A})=mc(\mathcal A)$ and a $\sigma$-algebra is closed under complements ,then
$\mathcal{C_1}=\sigma(\mathcal{A})$
and since every $\sigma$–algebra is a monotone class we're done.


can we trust feature importance of a poor model

Question: Usually when training ensemble learning algorithms or a regression model we calculate feature importance and make conclusion that feature with highest feature importance has largest affect on y-variable.
No doubt when model itself if reliable(High MSE or accuracy) however what if model is not performing well? Can we still trust feature importance?
Comment: You can trust it as much as you trust the predictive accuracy.
Answer: The key consideration is that feature importance is always an importance for the particular model and the particular dataset. There is no such a thing as global importance. If you use different feature selection algorithms, you can expect that they would pick different features, hence consider different features to be important.
So if you have a poorly performing model, than feature importance tells you that the feature is important for the model when it makes its (poor) predictions. It doesn't mean that there is no other, better performing model, that possibly assigns less or more importance to the feature.
Comment: Thanks! Is there reference that proves your statement?
Comment: @haneulkim you have results of an experiment in the linked thread, for importance in general, it is calculated using some model, so it cannot be independent of the underlying model.


Operationalizing a problem: Time-series Anomaly detection with multiple units and multiple sensors

Question: I have an IoT problem I am trying to operationalize.
I have multiple machines that should behave similarly over time (a good example is wind turbines nearby). They each have multiple sensors. And I have data over time.
Besides detecting absolute values that are dangerous (e.g. overheating), I am trying to operationalize how would I cross-reference the different sensors and different machines to detect other anomalies such as sensor failure.
Best I can think of at the moment are disjointed models within-machine/cross-sensors regression, and across-machines/across-sensors regression and then looking at then flagging large residuals.
HOWEVER, I am thinking there could be a way to maybe assemble this as some sort of covariance matrix or another, more computationally elegant solution. However, googling and reviewing literature has not yielded much of value yet.
I know this is broad, but hopefully allowed.
Thanks
Answer: Just a thought, you could use "boosting", e.g. monitor the relation of two similar sensors. To stick to the example, the ratio of temparature measurement of unit 1 and unit 2 should stay within a certain boundary.
I would consider combining sensors that either measure similar things, or use similar technologies, co-variances may be too computationally heavy.
Another technique, similar to the above, that is used in a different context is to compare one such measurement to the median and average of all such measurements. If the value of one sensor exceeds a threshold, you can do a relatively simple voting algorithm. This is how aeroplanes select altitudes from four sensors.


How to add complete value programmatically with Smart Date module?

Question: Iam using module Smart Date on Drupal 9.
And required programmatically add value to node in field with recurring rule (like Repeats every 1 year on xxxx-xx-xx). Technically, for this action also creating record in Rule table... But I understand, how this do... It seems like the smartdate module itself should make an entry in this additional table.
I used like this operation:
<code>// Create new node:
$node = \Drupal::entityTypeManager()->getStorage('node')->create([
  'type'        => 'event',
  'title'       => 'My new note title',
]);

// Assign value to field_date:
$node->set('field_date', '2022-03-01');
// ...needed add here also rule of yearly recurring...
</code>
field_data - its name of smartdate field, but how add field value with complete data (repeats every, until and etc.)?
Like in field widget on node edit with admin panel, there are more options available for this field.
Any ideas?
Comment: Usually, I find the easiest way to do figure this kind of thing out is to 1. Inspect the edit form to see what the field names are - very often they map to the property names a field expects. 2. Create a presave hook and add a breakpoint, then fill out the form with values, submit the form and inspect the field at your breakpoint.
Comment: Of course you can always review the module code / field definition too.
Comment: Yes, you said it right... But now I'm working on a hosting server, there there is no xdebug, and I'm starting to learn Drupal 8/9 current, until it's clear in which direction to dig when the module is not quite standard
Answer: When adding a Smart date range field to a content type, a table node__field_name will be added to the database. You have to fill in both the start (field_name_value) and end date (field_name_end_value) with a timestamp.
For example with your field name:
<code>$node->field_date->value = 1676039400;
$node->field_date->end_value = 1676046600;
</code>
For all day events you can fill in the duration as well:
<code>$node->field_date->value = 1675983600;
$node->field_date->end_value = 1676069940;
$node->field_date->duration = 1439;
</code>
Smart date fills in the number of days in minutes -1 minute for all day events as duration.


Converting a Unix Sort command into a Quicksort

Question: I have a command sort -n +1 -2 -o /tmp/ord_id in a C file that i call using system, which is pretty bad. How would i go about creating a quicksort function to complete the same tasks that the unix command will do? Here is how the command is called:
static const char sortcmd[] = "sort -n +1 -2 -o /tmp/ord_id "; //dec during function
//later in the function
bu_vls_strcpy(&cmd, sortcmd); //ONLY NEED TO FIX THIS COMMAND
bu_vls_strcat(&cmd, argv[1]);
bu_vls_printf(&gedp->ged_result_str, "%V\n", &cmd);
(void)system( bu_vls_addr(&cmd) );

bu_vls functions are predefined in the program,  so think of them like the usual string functions. i commented the line of code that the call appears, any tips or code is appreciated(this is not a homework assignment, independent project!)
Answer: There are a few steps:

Read in the file (assuming that's argv[1])
(optional) Parse it to find the fields selected by the +1 -2 using the same rules as sort.
Write a sort predicate to implement sorting with numeric sort for numbers (from the -n) argument.  This either operates on full lines (if you skipped step 2) or on the structure you created to represent the parsed line.
Call qsort
Write the data out in sorted order.
Comment: is qsort a predefined function? If so is it appart of the cstdlib?
Comment: how would i write to the file specified? would i need to create a FILE object and write to the object after the sort with argv[1]?
Comment: The output file is selected by `-o /tmp/ord_id` (which is not a particularly good way to make a temp file, but if you want to copy the existing behavior...) so you would need to open and write to that file explicitly.


How to grab the ID of a DIV tag referenced by the Class ID instead

Question: I am trying to grab the ID of a DIV class referenced by its Class name using JQuery, but failed to do it.
$(".myClass").click(function(e){
alert($(this).id);
}

Helloworld I am new to JQuery 1

    Helloworld I am new to JQuery 2

Could you help me please?
Answer: $(".myClass").click(function(e){
    alert($(this).attr('id'));
}

should do the trick!!
jim
Comment: Thank you Jim for your quick help.
Answer: try this:
$(".myClass").click(function(e){
    alert(this.id);
}

or
$(".myClass").click(function(e){
    alert($(this).attr("id"));
}

Comment: Many thanks to Am for your help. But I have to select Jim since he came first for this question.


weka.associations.fpgrowth: cannot handle any class attribute

Question: i am getting this error in weka while converting my attributes from nominal to binary for FPGrowth. dataset contains all nominal values 14:06:56: weka.associations.fpgrowth: cannot handle any class attribute!
Answer: Make sure you do not have a class attribute.
Association rule mining is for unlabeled data.
If you don't understand why exactly this error occurs, I suggest you check the source code of FpGrowth.


what are the appropriate way of writing a function for a delete button for a calculator?

Question: I am a react beginner!  have been trying to write a code inside deletehandler function wish was assign to delete button, whereby if the button is clicked, one or more value on the calculator screen should be erase or removed.
How can I get this done?
This is my code so far;
const deleteClickHandler = () => {

    let num = calc.num ? toLocaleString(removeSpaces(-calc.num)) : 0;
    let res = calc.res ? toLocaleString(removeSpaces(-calc.res)) : 0;

    setCalc({
        ...calc,
        num: (num /= splice(0, -1)),
        res: (res /= splice(0, -1)),
        sign: "",
    });
}

Comment: I am having trouble reading this code. What is `calc.num`. What is `calc.res`? Why is there a `-` in the argument to `removeSpaces()`?  What does `setCalc` do? What does `splice()` do? Usually this is an array method, but this isn't attached to an array.
Answer: If you are removing the last index in an array, for instance, you can use pop()
let numbers = [71, 6, 3 , 45, 5];
numbers.pop();

you can also apply this kind of approach with your res KEY
// [71, 6, 3, 45]


Probabilty with Combinations concept check

Question: When we calculate the probability of a random selection of $3$ students being all boys, from a group of $6$ boys and $4$ girls, then we can just multiply $\mathbb P(\text{1st being boy}) \times \mathbb P(\text{2nd being boy}) \times \mathbb P(\text{3rd being boy})$ i.e. $\frac 6 {10} \times \frac 5 9 \times \frac 4 8 $.
But when we need the probability of two coin flips being TAILS in $5$ flips of a fair coin, we need to multiply the $\mathbb P(T)\times\mathbb P(T)\times\mathbb P(H)\times\mathbb P(H)\times\mathbb P(H)\times{5\choose 2}$.
Why do we need to multiply the probabilities by the number of combinations in the coin flips problem but not in the first?
Comment: The first question : you pick three people, so first ,second and third picks have to be boys. Second question : two coin flips being tails out of five : but *which* two coin flips? First and third? Second and fourth? First and last? Indeed, any of them, so you accommodate all of them with the $5C2$. Note that , actually you are multiplying by "$3C0 = 1$" in the first one, because you are fitting in $0$ girls into $3$ slots, which can be done in only one way. But when you fit $2$ tails in five slots, the number $5C2 \neq 1$ becomes significant.
Comment: Conceptually, we can also think of it as multiplying by "3C3 = 1" in the first problem i.e. how many ways to fit 3 boys in 3 slots?
Comment: C'est bien,that too would work, since choosing girls for certain slots also amounts to choosing boys for the remaining slots.
Answer: Because there is only one way to get three boys.  If you were calculating the probability of getting two boys and one girl, you could do $\frac 6{10} \cdot \frac 59 \frac 48$, which chooses two boys first, then one girl, then multiply by $3$ because there are three orders you can choose the three children.


Is it ok to write a note of the same register in two voices (SATB)?

Question: I want to know if this is allowed when writing for SATB. The chord is D/F#. The note D is of the same register, but repeated in the Alto & Tenor voices. Is this allowed in a music theory exam?
Comment: @Dekkadeci It's for Trinity.
Comment: Which syllabus are you getting music theory lessons and exams from? I suspect things are at least slightly different between RCM and Trinity, for example.
Comment: Pretty sure the term is "doubling", in this case doubling the root. Not sure about whether your theory exam allows it, so this is a comment.
Answer: This is allowed in classical harmony.  I don't see why it shouldn't be allowed in a music theory exam, assuming that the voice leading to and away from it is correct.
Comment: I'm afraid I can't tell you that, because there are no fixed rules for music theory exams, as far as I know.  But I can't imagine how someone would object to it.
Comment: Ok, I wanted to clarify if rules were different for a music theory exam.


how to show up a value that is closest to or equal to the results of calculating the system with the database?

Question: I use Framework CI
I have two tables in the database. The first table is "A" and the second table is "B". In the table "A" there is a column "DIAMETER" containing numbers obtained from the calculation of the system by the user.
While in the table "B" there is a "STANDARD" column containing numbers that have been entered by the admin.
Then how do I show up the "STANDAR" number where the "DIAMETER" number calculated by the user approaches or equals the "STANDARD"?
In the database

Table A, column
Diameter
  2.5,  3.8,
     5.6
Table B, column
Standard
      3,
      3.5,
      4,
      5,
      6,
If the result of calculating the diameter of 3.8 is the result to be raised is 4, if the result is diameter 5.6 then the result will be raised 6.
The results that I expected top figures that approached the standard number or the same as the standard number
My Model
public function get_standar(){
$this->db->order_by('standar', 'ASC');
$this->db->limit('0');
return $this->db->get('B')->result();

}
My View

Diameter

    <input class="form-control" name="diameter" type="text" value="<?php echo number_format($getdata->diameter,2);?>" readonly="">
    mm

Standar
<select class="form-control" name="standar" id="standar">
<?php foreach ($standar as $stand) {?>
    <option <?php echo $standar_selected == $stand->id_standar ? 'selected="selected"' : '' ?> value="<?php echo $stand->id_standar ?>">
        <?php if ($getdata->diameter >= $stand->standar) { echo $stand->standar ;} ?>
    </option>
<?php }?>
</select>

enter image description here
enter image description here
Answer: The following query returns the minimum standard diameter bigger or equal than the diameter you calculated:
$diameter = 3.8;

$sql = "SELECT MIN(column_standard), {other columns you need}
FROM table B
WHERE column_standard >= $diameter";

$this->db->query($sql);

The query above returns 4 as result.
Comment: thanks for your answer, before i use framework codeigniter, can this be used?
Comment: Definitely, if you run this query on your mysql client it will work fine. You just need to replace the $diameter to a value on your mysql client.
Comment: What king of error are you getting? Can you provide some code related to you query?


Possible dismissals off a noball, wide ball and free hit

Question: I came to know that a batsman can be stumped out off a wide ball but not off a no-ball (Is it correct?)
What are the possibilities to dismiss batsmen, off a noball, a wide ball, a freehit ball and two or three pitched(dead)ball?
Comment: If a runner is 'stumped', then it is treated as a run-out and not stumped. Also, the use of runners have been banned by ICC from late 2011.
Comment: A Batsman can be out Stumped of a No Ball when he is using a Runner.
Comment: Orangecrush,
The Batsman can be stumped of a No Ball if using a runner. If the runner is out of the crease then that would be Run out. ICC uses Laws of Cricket in conjunction with Playing Regulations. The Playing Regulations do not allow runners.
Comment: Welcome to Sports SE! Would suggest you to go through the [FAQ section](http://sports.stackexchange.com/faq) before posting any further answers. Also, if you have any queries or want to point anything out related to the question/answer, please post a comment on your previous answer and do not post it as a separate answer. Thanks!
Comment: @Orangecrush Keep in mind that users with <50 rep cannot comment.
Comment: @PATELDAKU Welcome to Sports SE! Three things. 1) Creating multiple accounts are not recommended. 2) Multiple answers are also not recommended. 3) If you would like to clarify your answer, you have the ability to edit it.
Comment: @edmastermind29 Yes, I understand. What I meant was for him to comment on his first answer, as one doesnt need any rep to do so on ones own answer. Anyways, since that also was to be a comment, I don't see any other way out for him apart from editing the original answer.
Comment: A two- or three-pitched delivery is not a dead ball, it is a no-ball.
Answer: Yes, you are right when you say that a batsman can be stumped off a wide but not off a no-ball.

No Ball dismissals - hitting the ball twice, obstructing the field and run out (Law 21.8).
Wide dismissals -  hit wicket, obstructing the field, run out and stumped. (Law 22.9)
Freehit dismissals - hitting the ball twice, obstructing the field and run out.

Law 21.7 states that,

Ball bouncing more than once or rolling along the ground
The umpire shall call and signal No ball if a ball which he/she considers to have been delivered, without having previously touched bat or person of the striker, bounces more than once or rolls along the ground before it reaches the popping crease

So, in such cases the delivery is considered a no-ball and the same rules of a no-ball apply.


rack-rewrite 301 not matching for specific query

Question: Can any one tell me why this works:
r301 %r{(?:images\/)(\d*.jpe?g|png|gif)$}, 'http://mybucket.s3.amazonaws.com/540x310/$1'

URI = http://www.mysite.com/images/42720.jpeg

and this doesn't
r301 %r{(?:resized_images\/\d*x\d*\/)(\d*.jpe?g|png|gif)$}, 'http://mybucket.s3.amazonaws.com/540x310/$1'

URI = http://www.mysite.com/resized_images/560x344/77664.jpeg

Both work at Rubular:
http://rubular.com/r/PXHiEcoEqy
http://rubular.com/r/BfOta6YJa7

thanks in advance
----------update-------------
This is an issue with how i'm using rack-rewrite:
The rewrite isn't working with two 301 query strings.
if i comment out the first line the second works and vice versa.
Any idea how to get them both working.
use Rack::Rewrite do
    r301 %r{(?:images\/)(\d*.jpe?g|png|gif|bmp)$}, 'http://mybucket.s3.amazonaws.com/540x310/$1'
    r301 %r{(?:resized_images\/\d*x\d*\/)(\d*.jpe?g|png|gif|bmp)$}, 'http://mybucket.s3.amazonaws.com/540x310/$1'
 end

Comment: Has anyone got any idea on this. is there an issue in the regex that im not picking up in rubular?
Answer: final answer.
I broke the second redirect out into another use Rack::rewrite and it fixed the issue


Bayesian inverse modeling with non-identifiable parameters?

Question: If I have a physical model
\begin{equation}
y = \frac{1}{\beta_0} (\beta_1 x_1 + \beta_2 x_2)
\end{equation}
and want to estimate coefficients $\beta_0$, $\beta_1$, and $\beta_2$ from given data set $(y, x_1, x_2)$, with regression I would typically have to combine them into two coefficients $\beta_1/\beta_0$ and $\beta_2/\beta_0$ since that would be what I would be able to solve (contributions from $1/\beta_0$ and $\beta_1$ cannot be distinguished from each other individually).
However, if I have separate prior distributions for $\beta_0$, $\beta_1$, and $\beta_2$ - is it possible to obtain sensible posterior distributions for each of them using MCMC or Laplace's method without combining the variables?
Edits Corrected title and variable name error based on comments and answers.
Comment: I think you meant $\beta_{0}$ instead of $\alpha$. Note that, even if you have seperate priors for each parameter,  I can't prove it but I'm pretty certain that there will still be an identifiability issue with that model. Gelman and Meng wrote a paper regarding ridge problems associated with bayesian MCMC so you may want to check that out. Problem is that I can't remember the title at the moment.  I think it was in the 90's.
Comment: Hi: Now that I looked more carefully, I'm not sure it's related to your issue but it might be interesting to look at anyway because it shows another issue with bayesian model parameters. https://www.emeraldinsight.com/doi/pdfplus/10.1016/S0731-9053%2808%2923011-2
Answer: Adding priors does not solve the identifiability problem
This is a case where the parameters are non-identifiable in your model.  As you point out, contributions from the individual non-identifiable parameters in these ratios cannot be distinguished using the data.  A relevant paper on this matter is O'Neill (2005).
When using Bayesian analysis with a non-identifiable model, specification of a prior for all the individual non-identifiable parameters will still lead you to a valid posterior, but this is strongly affected by the prior.  The posterior for the non-identifiable parameters converges to a fixed asymptotic distribution that also depends heavily on the prior, so it lacks posterior consistency.
The fact that you get a valid posterior, and this converges to a fixed asymptotic distribution, often gives the misleading impression that Bayesian analysis renders the identifiability problem benign.  However, it is crucial to note that the posterior in these cases is strongly affected by the prior in ways that do not vanish as we get more and more data.  The identifiability problem is not rendered benign merely by using Bayesian analysis with priors.

Posterior depends heavily on prior: To see exactly what I mean, define the minimal sufficient parameters $\phi_1 \equiv \beta_1 / \beta_0$ and $\phi_2 \equiv \beta_2 / \beta_0$.  These are the parameters that are identified in the present model.  Using the rules for density transformation, the posterior distribution for the three non-identifiable parameters of interest can be written as:
$$\begin{equation} \begin{aligned}
\pi(\beta_0, \beta_1, \beta_2 | \mathbf{x}, \mathbf{y})
&= \frac{1}{\beta_0^2} \cdot \pi(\beta_0, \phi_1, \phi_2 | \mathbf{x}, \mathbf{y}) \\[6pt]
&= \frac{1}{\beta_0^2} \cdot p(\beta_0 | \phi_1, \phi_2) \cdot \pi(\phi_1, \phi_2 | \mathbf{x}, \mathbf{y}). \\[6pt]
\end{aligned} \end{equation}$$
Now, the posterior $\pi(\phi_1, \phi_2 | \mathbf{x}, \mathbf{y})$ for the minimal sufficient parameters (which are identifiable) is determined by the prior assumptions and the data as normal.  However, the density $p(\beta_0 | \phi_1, \phi_2)$ is determined purely by the prior (i.e., it does not change as you get more data).  This latter density is just an aspect of the assumed prior on the three non-identifiable parameters.  Hence, the posterior of the non-identifiable parameters will be determined in large measure by a part that is purely a function of the prior.
Posterior converges for identifiable parameters, not non-identifiable parameters: Bayesian asymptotic theory tells us that, under broad conditions, the posterior distribution of identifiable parameters converges towards a point-mass on the true values.  (More specifically, there are a number of convergence results that show asymptotic convergence to a normal distribution with mean that approaches the true identifiable parameter values and variance that approaches zero.)  In the context of regression there are some additional convergence conditions on the explanatory variables, but again, that convergence result holds broadly.
Under appropriate conditions, as $n \rightarrow \infty$ the density $\pi(\phi_1, \phi_2 | \mathbf{x}, \mathbf{y})$ will converge closer and closer to a point-mass distribution on the true values $(\phi_1^*, \phi_2^*)$.  In the limit the posterior distribution for the non-identifiable parameters converges to a limiting distribution determined by the prior (that is not a point-mass):
$$\begin{equation} \begin{aligned}
\pi(\beta_0, \beta_1, \beta_2 | \mathbf{x}, \mathbf{y})
&\rightarrow
\pi(\beta_0, \beta_1, \beta_2 | \mathbf{x}_\infty, \mathbf{y}_\infty) \\[6pt]
&\propto \frac{1}{\beta_0^2} \cdot p(\beta_0 | \phi_1^* = \beta_1 / \beta_0, \phi_2^* = \beta_2 / \beta_0). \\[6pt]
\end{aligned} \end{equation}$$
We can see that this asymptotic density is affected by the data only through the true values of the minimal sufficient parameters.  It is still heavily affected by the form of the density $p(\beta_0 | \phi_1, \phi_2)$, which is a function of the prior.  Although the posterior for the identifiable parameters has converged to a point-mass on the true values, the posterior density for the non-identifiable parameters $\beta_0, \beta_1, \beta_2$ still retains uncertainty even in this limit.  Its distribution is now entirely determined by the prior, conditional on holding the identifiable parameters fixed.
In the other answer by Björn you can see that he gives an excellent example of this phenomenon in the simple case of IID data from a normal distribution with a mean that is a ratio of two non-identifiable parameters.  As you can see from his example, with a large amount of data there is posterior convergence for the identifiable mean, but the corresponding posterior for the non-identifiable parameters is still highly variable (and almost entirely dependent on the prior).
Conclusion: In Bayesian analysis you can assign a prior to a set of non-identifiable parameters and you get a valid posterior.  However, despite the fact that we get a valid posterior, and asymptotic convergence of the posterior to a limiting distribution, all of those results are heavily affected by the prior, even with an infinite amount of data.  In other words, don't let that fool you into thinking that you have "solved" the identifiability problem.
Answer: Yes, with a Bayesian analysis you can get sensible posteriors and concentrate around sensible values to the point that the combination of information in prior and likelihood allow it. In this sense the Bayesian analysis can deal with this kind of situation a lot better than a frequentist analysis. However, it cannot get around the fundamental non-identifiability of the parameters in a model and the posteriors will still reflect the lack of identifiability of the parameters.
To use an example, let's use a simpler model that is just $\log Z_i \sim N(\theta_1/\theta_2, \sigma^2)$ and let's assume that we have a huge amount of data. We'll have hardly any uncertainty around the ratio $\theta_1/\theta_2$, but lots of values for each parameter are still getting support in the likelihood. Thus, we just get still a wide marginal posterior distribution and the joint distribution does have a very strong correlation between the two parameters.
This is illustrated with example code below (using the re-parameterization $Y_i := \log Z_i$ and $\beta_j := \log \theta_j$).
Obviously, the marginal posterior would be wider, if our prior for the parameters had been wider and the posterior correlation less strong, if we had less data (then the parameter identifiability problem would be less obvious).
I would expect something similar to happen in your example - whether that's a problem or not is a different matter.
<code>library(rstan)
library(bayesplot)
y <- exp(rnorm(10000, 0,1))

stancode <- "
data {
  int n;
  real y[n];
}

parameters{
  real beta0;
  real beta1;
  real<lower=0> sigma;
}

model {
  beta0  ~ normal(0,1);
  beta1 ~ normal(0,1);
  sigma ~ normal(0,1);
  y ~ normal(exp(beta1-beta0), sigma);
}
"

stanfit <- stan(model_code=stancode, data=list(n=length(y), y=y))

posterior <- as.matrix(stanfit)

mcmc_pairs(posterior, pars = c("beta0", "beta1"))
</code>
Comment: Side note: When identifiability is **not** an issue, one can specify (in for example `Stan`) multiple priors for the same parameter.  Priors are interchangeable with data so it's like adding more data to the analysis.  I assume that when the priors conflict somehow they are effectively averaged in some way.


Fatal error: Call to undefined function smug_1()

Question: Sorry to bother all you busy people I just can't work out why the function is not working. Spent 50ish min using trial and error. Error given is for line 15 "case 'smug': smug_1(); break;"
<?php
include "globals.php";

if ($ir['jailtime'] > 0) {
    print "The docks are closed to jail birds come back when thay release you";
    exit;
}
if ($ir['hospital'] > 0) {
    print "You cant go sailing while in hospital";
    exit;
}
switch ($_GET['action']) {
case 'smug':
    smug_1();
    break;
case 'smugsub':
    smug_1_sub();
    break;
case 'smug2':
    smug_2();
    break;
case 'smugsub':
    smug_2_sub();
    break;
case 'smug3':
    smug_3();
    break;
case 'smug3sub':
    smug_3_sub();
    break;
case 'smug4':
    smug_4();
    break;
case 'smug4sub':
    smug_4_sub();
    break;
case 'smug5':
    smug_5();
    break;
case 'smug5sub':
    smug_5_sub();
    break;
case 'smug6':
    smug_6();
    break;
case 'smug6sub':
    smug_6_sub();
    break;
default:
    smug_index('action');
    break;
}

function smug_index()
{
    global $ir, $c, $userid;
    print "
Crystal Smuggling

    You have {$ir['csmuggling']} Smuggling Turns Left.

    Welcome to the crystal smuggling docks. You can go to these location, more will be available when you are a higher level:
    [> France]";
    if ($ir['level'] > 5) {
        print "[> Holland]";
        if ($ir['level'] > 10) {
            print "[> Germany]";
            if ($ir['level'] > 20) {
                print "[> Portugal]";
                if ($ir['level'] > 30) {
                    print "[> Spain]";
                    if ($ir['level'] > 70) {
                        print "[> Switzerland]";
                    }

                    function smug_1()
                    {
                        global $db, $ir, $c, $userid;
                        $rand_gems = rand(1, 3);
                        echo "You get over to France And Managed To Smuggle $rand_gems crystals back.";
                        mysql_query("UPDATE users SET crystals=crystals+$rand_gems WHERE userid=$userid");
                        mysql_query("UPDATE users SET csmuggling=smuggling-1 WHERE userid=$userid");
                        print "[> Back]";
                    }

                    function smug_2()
                    {
                        global $db, $ir, $c, $userid;
                        $rand_gems = rand(2, 6);
                        echo "You get over to Holland And Managed To Smuggle $rand_gems crystals back.
                        ";
                        mysql_query("UPDATE users SET crystals=crystals+$rand_gems WHERE userid=$userid");
                        mysql_query("UPDATE users SET csmuggling=smuggling-1 WHERE userid=$userid");
                        print "[> Back]";
                    }

                    function smug_3()
                    {
                        global $db, $ir, $c, $userid;
                        $rand_gems = rand(4, 9);
                        echo "You get over to Germany And Managed To Smuggle $rand_gems crystals back.
                        ";
                        mysql_query("UPDATE users SET crystals=crystals+$rand_gems WHERE userid=$userid");
                        mysql_query("UPDATE users SET csmuggling=smuggling-1 WHERE userid=$userid");
                        print "[> Back]";
                    }

                    function smug_4()
                    {
                        global $db, $ir, $c, $userid;
                        $rand_gems = rand(9, 12);
                        echo "You get over to Portugal And Managed To Smuggle $rand_gems crystals back.
                        ";
                        mysql_query("UPDATE users SET crystals=crystals+$rand_gems WHERE userid=$userid");
                        mysql_query("UPDATE users SET csmuggling=smuggling-1 WHERE userid=$userid");
                        print "[> Back]";
                    }

                    function smug_5()
                    {
                        global $db, $ir, $c, $userid;
                        $rand_gems = rand(11, 15);
                        print "You get over to Spain And Managed To Smuggle $rand_gems crystals back.
                        ";
                        mysql_query("UPDATE users SET crystals=crystals+$rand_gems WHERE userid=$userid");
                        mysql_query("UPDATE users SET csmuggling=smuggling-1 WHERE userid=$userid");
                        print "[> Back]";
                    }

                    function smug_6()
                    {
                        global $db, $ir, $c, $userid;
                        $rand_gems = rand(13, 17);
                        echo "You get over to Switzerland And Managed To Smuggle $rand_gems crystals back.
                        ";
                        mysql_query("UPDATE users SET crystals=crystals+$rand_gems WHERE userid=$userid");
                        mysql_query("UPDATE users SET csmuggling=smuggling-1 WHERE userid=$userid");
                        print "[> Back]";
                    }
                }
            }
        }
    }
}

Thanks for taking the time to help me. :)
Comment: properly indent your code with braces, that may give you a hint
Comment: Your code needs a new design and flow!
Answer: Your functions are defined inside if() ... blocks therefore they are not available for parser until the if blocks are matched. Define them outside your if() blocks!
Comment: This is almost a perfect object lesson in why you want to follow coding standards, including indenting each control structure.  With proper indenting, you would instantly see that the *function* statement did not start in column 1, and that would be a giant red flag, since it would potentially indicate a conditional definition.  Coding standards are your friend!
Comment: @Jeffrey I meant out side of if() blocks!
Comment: @Jeffrey Check code again and you will see that functions are defined in `if ($ir['level'] > 30)`, they cannot be used until this (and all parent if blocks before it) is matched
Answer: You must load/include all functions (function codes) BEFORE your output .php document(s) starts...
So

Functions must be included/loaded first (and read by PHP)
Then you can call those in a file!

Obviously, your "output" codes are set before function codes (so PHP cant execute functions because it has no idea functions exists at that point). So, you must write codes otherwise.
<?php

include "globals.php";

//first functions

function smug_1()
{
global $db,$ir,$c,$userid;
$rand_gems = rand(1,3);
echo "You get over to France And Managed To Smuggle $rand_gems crystals back.
";
mysql_query("UPDATE users SET crystals=crystals+$rand_gems WHERE userid=$userid");
mysql_query("UPDATE users SET csmuggling=smuggling-1 WHERE userid=$userid");
print "[> Back]
";
}
function smug_2()
{
global $db,$ir,$c,$userid;
$rand_gems = rand(2,6);
echo "You get over to Holland And Managed To Smuggle $rand_gems crystals back.
";
mysql_query("UPDATE users SET crystals=crystals+$rand_gems WHERE userid=$userid");
mysql_query("UPDATE users SET csmuggling=smuggling-1 WHERE userid=$userid");
print "[> Back]
";
}
function smug_3()
{
global $db,$ir,$c,$userid;
$rand_gems = rand(4,9);
echo "You get over to Germany And Managed To Smuggle $rand_gems crystals back.
";
mysql_query("UPDATE users SET crystals=crystals+$rand_gems WHERE userid=$userid");
mysql_query("UPDATE users SET csmuggling=smuggling-1 WHERE userid=$userid");
print "[> Back]
";
}
function smug_4()
{
global $db,$ir,$c,$userid;
$rand_gems = rand(9,12);
echo "You get over to Portugal And Managed To Smuggle $rand_gems crystals back.
";
mysql_query("UPDATE users SET crystals=crystals+$rand_gems WHERE userid=$userid");
mysql_query("UPDATE users SET csmuggling=smuggling-1 WHERE userid=$userid");
print "[> Back]
";
}
function smug_5()
{
global $db,$ir,$c,$userid;
$rand_gems = rand(11,15);
print "You get over to Spain And Managed To Smuggle $rand_gems crystals back.
";
mysql_query("UPDATE users SET crystals=crystals+$rand_gems WHERE userid=$userid");
mysql_query("UPDATE users SET csmuggling=smuggling-1 WHERE userid=$userid");
print "[> Back]
";
}
function smug_6()
{
global $db,$ir,$c,$userid;
$rand_gems = rand(13,17);
echo "You get over to Switzerland And Managed To Smuggle $rand_gems crystals back.
";
mysql_query("UPDATE users SET crystals=crystals+$rand_gems WHERE userid=$userid");
mysql_query("UPDATE users SET csmuggling=smuggling-1 WHERE userid=$userid");
print "[> Back]
";
}

function smug_index()
{
global $ir,$c,$userid;
print "
Crystal Smuggling

You have {$ir['csmuggling']} Smuggling Turns Left.

Welcome to the crystal smuggling docks. You can go to these location, more will be available when you are a higher level:

[> France]
";
if ($ir['level'] > 5) {
print "[> Holland]
";
if ($ir['level'] > 10) {
print "[> Germany]
";
if ($ir['level'] > 20) {
print "[> Portugal]
";
if ($ir['level'] > 30) {
print "[> Spain]
";
if ($ir['level'] > 70) {
print "[> Switzerland]

";
}

}
}
}
}
}

 //then output codes

if ($ir['jailtime'] > 0){
print "The docks are closed to jail birds come back when thay release you";
exit;
}
if ($ir['hospital'] > 0){
print "You cant go sailing while in hospital";
exit;
}
switch($_GET['action'])
{
case 'smug': smug_1(); break;
case 'smugsub': smug_1_sub(); break;
case 'smug2': smug_2(); break;
case 'smugsub': smug_2_sub(); break;
case 'smug3': smug_3(); break;
case 'smug3sub': smug_3_sub(); break;
case 'smug4': smug_4(); break;
case 'smug4sub': smug_4_sub(); break;
case 'smug5': smug_5(); break;
case 'smug5sub': smug_5_sub(); break;
case 'smug6': smug_6(); break;
case 'smug6sub': smug_6_sub(); break;
default: smug_index('action'); break;
}

?>

Try that. Only problem is that globals.php can be before OR after functions (since I have no idea what globals.php does).centersmugsub
Comment: Thanks :D so much also thanks to shawndrek for formatting my other one, I'll try changing my otherfiles to have a better flow :D. Thanks mostly to Xfile for giving me an example to follow for my other function pages!
Comment: Thanks. I tried that but i still get the same error. I moved the functions correctly right? Sorry thought i could paste whole thing
Comment: Please wait a minute or so, ill edit my answer..
Comment: http://codepad.org/TPxGWfTS ? EDIT: Okay thank you so much Xfile
Comment: Here you are. That should work :P


Can't use certain colors in Windows 8 HTML5 app

Question: For some reason, when I set the background color in a Windows 8 app to either #0D0D0D or #EEEEEE it displays as #111111 or #F2F2F2 respectively.
Is this a bug, or is there a reason for this? It seems fine for random other colors, but for some reason when I set it to something between black and white it demands that it changes. I've tried switching to RGB colors, too, and it still isn't working.
It's really not that big of a deal, but I'm a perfectionist and it's frustrating that the colors are just slightly off of my designs.
Comment: I was also able to make an app with these background colors without problems.  Furthermore, asker has accepted an obviously-wrong claim as the correct answer.  It is my belief that this question reflects simple confusion on the asker's part.  (For example, they might have set the alpha of the layer and be seeing the base white through it, or something.)
Comment: Yep, doesn't matter if it's 6 or 3 characters.
Comment: Could you give some more details about how you're setting these colors? It's hard to fix a problem you can't duplicate, especially when it doesn't make much sense on the face of it.
Comment: Out of curiosity, does the same occur if you use the three-character form (where possible), such as `#eee` instead of `#eeeeee`? It *should* (depending on what the problem is), I'm just curious if whatever's happening only happens under certain circumstances.
Comment: how are you determining that it's using a different color than what you specified?  I'm not seeing any issues here, using those two colors.  A color picker from a third-party app is reporting exactly what was specified in the CSS. What color-depth are you running on your computer, if 24-bit color I don't think you should be seeing this behavior.
Comment: Have you got some code or an example?
Answer: i had the same issue, what i did is to change hex value into rgb or if it is exact color name i apply that name to hex value. you can find many online color converters online. hope this helps.


Making a HttpClient request in java

Question: I am creating a data downloader which has been giving me problems since using httpClient
This code append all variables needed to the URL :
   private void createOpenSession() {
   String params = new StringBuilder()
           .append("?u=").append(this.user)
           .append("&p=").append(this.password)
           .append("&q=").append(this.qualifier)
           .toString();
   this.openSession = new HttpGet(this.target + params);

}
Whenever i call the openSession, it print out the header in a simple way(Just what i need it to do)...
   public void start() throws ClientProtocolException, IOException  {

        try {
            HttpResponse response = this.httpClient.execute(this.openSession);
            if (response.getStatusLine().getStatusCode() == 200) {
                try {
                    String responseContent = this.readResponse(response);
                    System.out.println(responseContent);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                }}
            finally {
               createCloseSession();
            }
        }

This Prints a Single Line Thisdude:coole3r, but when i make another request that prints long line, It always bring this error:
    Exception in thread main
java.lang.IllegalArgumentException: HTTP request may not be null
    at org.apache.http.util.Args.notNull(Args.java:54)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:81)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)
    at com.si.data.client.ProxyClient1.start(ProxyClient1.java:72)
    at com.si.data.client.IpcClient.main(IpcClient.java:136)

This is the Second Request that gives error:
    private void createCurrencyPairsRequest(String currencyPairs) throws IOException {
    if (this.sessionId == null) {
        this.refreshSessioId();
    }
    String params = new StringBuilder()
            .append("?id=").append(this.sessionId)
            .append("&c=").append(currencyPairs)//The Pairs is an array
            .append("&f=").append(this.format)
            .toString();
    this.requestCurrencies = new HttpGet(this.target + params);
}

Am i doing anything wrong in the currencyPairsRequest() ?
Thanks for your time taken..
Answer: I Solved It By Debugging the currencyPairsRequest()..
This is how i solved this...
I changed the currencyPairsRequest() return type from void() to HttpGet.
   private HttpGet createCurrencyPairsRequest(String currencyPairs) throws IOException {
       if (this.sessionId == null) {
           this.refreshSessioId();
       }
       String params = new StringBuilder()
               .append("?id=").append(this.sessionId)
               .append("&c=").append(currencyPairs)
               .append("&f=").append(this.format)
               .toString();
       this.requestCurrencies = new HttpGet(this.target + params);
    return requestCurrencies;
   }

Then, I Called the `currencyPairsRequest() using :
System.out.println(requestCurrencies);

from the main() before initiating any request...
And, It Printed null, which means i've been sending a null request since yesterday..
So, I changed my request by not using requestCurrencies, but by calling the function itself and returning its value...
Thanks All..

Making a HttpClient request in java


How do I rewrite a fractional expression with a numerator that is a variable raised to an exponent...as an exponential?

Question: For example:
$(x^2)/2 = x^w$
where w stands in for the value I'm trying to find.
Comment: Take $\log_x$ of both sides.
Answer: Your power must be $2$ so the answer is $(\frac {x}{\sqrt 2})^2$


Evaluation of $\int\frac{\ln(\cos x+\sqrt{\cos 2x})}{\sin^2 x}dx$

Question:
Evaluation of $\displaystyle \int\frac{\ln(\cos x+\sqrt{\cos 2x})}{\sin^2 x}dx$

My Try:: Let $\displaystyle I = \int \frac{\ln(\cos x+\sqrt{\cos 2x})}{\sin^2 x}dx = \int \ln(\cos x+\sqrt{\cos 2x})\cdot \csc^2 xdx$
So $\displaystyle I = -\ln\left(\cos x+\sqrt{\cos 2x}\right)\cdot \cot x+\int \frac{1}{\left(\cos x+\sqrt{\cos 2x}\right)}\cdot \left(-\sin x-\frac{1}{2\sqrt{\cos 2x}}\cdot 2\cdot \sin 2x\right)\cdot \cot xdx$
Now How Can I solve after that
Help me
Thanks
Answer: Hint: After integrating by parts, try substituting $u=\sin{x}$. Also, it will be helpful to recall the trigonometric identity, $\cos{(2x)}=\cos^2{x}-\sin^2{x}=2\cos^2{x}-1=1-2\sin^2{x}$.
Let $I$ be your integral, then:
$$\begin{align}
I
&=-\cot{(x)}\ln{\left(\cos{x}+\sqrt{\cos{(2x)}}\right)}-\int\frac{\cot{x}\left(\sin{x}+\frac{\sin{(2x)}}{\sqrt{\cos{(2x)}}}\right)}{\cos{x}+\sqrt{\cos{(2x)}}}\mathrm{d}x\\
&=-\cot{(x)}\ln{\left(\cos{x}+\sqrt{\cos{(2x)}}\right)}-\int\frac{\cos{x}\left(1+\frac{2\cos{x}}{\sqrt{\cos{(2x)}}}\right)}{\cos{x}+\sqrt{\cos{(2x)}}}\mathrm{d}x\\
&=-\cot{(x)}\ln{\left(\cos{x}+\sqrt{\cos{(2x)}}\right)}-\int\frac{\cos{x}\left(1+\frac{2\sqrt{1-\sin^2{x}}}{\sqrt{1-2\sin^2{x}}}\right)}{\sqrt{1-\sin^2{x}}+\sqrt{1-2\sin^2{x}}}\mathrm{d}x\\
&=-\cot{(x)}\ln{\left(\cos{x}+\sqrt{\cos{(2x)}}\right)}-\int\frac{\left(1+\frac{2\sqrt{1-u^2}}{\sqrt{1-2u^2}}\right)}{\sqrt{1-u^2}+\sqrt{1-2u^2}}\mathrm{d}u\\
&=-\cot{(x)}\ln{\left(\cos{x}+\sqrt{\cos{(2x)}}\right)}-\int\frac{\frac{1}{\sqrt{1-2u^2}}-\sqrt{1-u^2}}{u^2}\mathrm{d}u.
\end{align}$$
This last integral may then be split up into two fairly easy integrals.
Comment: Let me know if the edit is OK. I just edited to make your text fit in the page.
Answer: As you have done, we first use integration by parts to get
$$\begin{align}
I &= \int \frac{\ln(\cos x+\sqrt{\cos 2x})}{\sin^2 x}dx
\\&= \int \ln(\cos x+\sqrt{\cos 2x})\csc^2 (x)dx
\\&=-\cot (x)\ln(\cos x+\sqrt{\cos 2x})+\int \left(\frac{1}{\cos x+\sqrt{\cos 2x}}\right) \left(-\sin x-\frac{\sin 2x}{\sqrt{\cos 2x}} \right)\cot (x)dx
\end{align}$$
Now we just need to  deal with the remaining integral which we will call $J$. First note that $$(\cos x+\sqrt{\cos 2x})(\cos x-\sqrt{\cos 2x})=\cos^2x-\cos2x=\cos^2x-(\cos^2x-\sin^2x)=\sin^2x$$
Hence
$$\begin{align}
J&=\int \left(\frac{1}{\cos x+\sqrt{\cos 2x}}\right) \left(-\sin x-\frac{\sin 2x}{\sqrt{\cos 2x}} \right)\cot (x)dx
\\&=\int\left(\frac{\cos x-\sqrt{\cos 2x}}{\cos x-\sqrt{\cos 2x}}\right)\left(\frac{1}{\cos x+\sqrt{\cos 2x}}\right) \left(-\sin x-\frac{\sin 2x}{\sqrt{\cos 2x}} \right)\cot (x) dx
\\&=\int\left(\frac{\cos x-\sqrt{\cos 2x}}{\sin^2x}\right) \left(-\sin x-\frac{2\sin x\cos x}{\sqrt{\cos 2x}} \right)\cot (x) dx
\\&=\int\left(\frac{-\sin x\cos x+\sin x\sqrt{\cos 2x}-\frac{2\sin x\cos^2 x}{\sqrt{\cos2x}}+2\sin x\cos x}{\sin^2x}\right)\cot (x) dx
\\&=\int\frac{-\cos^2 x+\cos x\sqrt{\cos 2x}-\frac{2\cos^3 x}{\sqrt{\cos2x}}+2\cos^2 x}{\sin^2x}dx
\\&=\int\left(-\frac{\sin^2x-1}{\sin^2x}+\frac{\sin^2x-1}{\sin^2x}\right)+\frac{\cos^2x +\cos x\sqrt{\cos 2x}-\frac{2\cos^3 x}{\sqrt{\cos2x}}}{\sin^2x}dx
\\&=-x-\cot x+\int\frac{\cos x\sqrt{\cos 2x}-\frac{2\cos^3 x}{\sqrt{\cos2x}}}{\sin^2x}dx
\\&=-x-\cot x+\int\frac{\cos x\cos 2x-2\cos^3 x}{\sin^2x\sqrt{\cos2x}}dx
\\&=-x-\cot x+\int\frac{\cos x(1-2\sin^2x)-2\cos^3 x}{\sin^2x\sqrt{\cos2x}}dx
\\&=-x-\cot x+\int\frac{-2\cos x\sin^2x+\cos x(1-2\cos^2 x)}{\sin^2x\sqrt{\cos2x}}dx
\\&=-x-\cot x+\int\frac{-\sin2x\sin x-\cos x\cos2x}{\sin^2x\sqrt{\cos2x}}dx
\\&=-x-\cot x+\int\frac{\frac{-\sin2x}{\sqrt{\cos2x}}\sin x-\cos x\sqrt{\cos2x}}{\sin^2x}dx
\\&=-x-\cot x+\frac{\sqrt{\cos 2x}}{\sin x}+C
\end{align}$$
Hence
$$\begin{align}I&=-\cot (x)\ln(\cos x+\sqrt{\cos 2x})-x-\cot x+\frac{\sqrt{\cos 2x}}{\sin x}+C
\\&=\frac{\sqrt{\cos 2x}}{\sin x}-x-\cot (x)(1+\ln(\cos x+\sqrt{\cos 2x})+C
\end{align}$$
Comment: I do just want to note that this solution was informed by the answer (I knew I wanted to manipulate the integral to get out an $x+\cot x$, and I knew I wanted to make the rest look like a quotient rule).


Time series forecasting of parking occupancy

Question: I would like to forecast parking space occupancy for several parking lots. My dataset contains information on the date and time of entering/exiting cars, parking capacity and price.
Is it possible to use time series modeling to predict when occupancy rates of the lots will increase/decrease throughout the day?
Answer: A time series at the very least requires a time measurement, as well as measuring a dependent variable that changes as time passes. In your case, your variable of interest would be the occupancy rate.
You would need to reorganize the dataset into something like the following:
<code> Time    # of Cars in Parking Lot    Parking Capacity    % Parking Capacity Filled     Price
 7:00          10                              100               10                       15
</code>
Then you would have a table of each time stamp and its respective measurement of occupancy rate, which is a time series. Then you can use time series modelling. So yes, it is possible.


The function $f(x)=\tan^{-1}(x)$ is not uniformly continuous on $\Bbb{R}$

Question: I'm trying to prove that

The function $f(x)=\tan^{-1}(x)$ is not uniformly continuous on $\Bbb{R}$.

Here's what I've done:
Let $\epsilon>0$ be given.
Now, $$|f(x)-f(y)|=|\tan^{-1}x-\tan^{-1}y|=\Big|\tan^{-1}\left( \frac{x-y}{1+xy}\right) \Big|$$
For non-negative $x,y\in \Bbb{R},$
$$|f(x)-f(y)|=|\tan^{-1}x-\tan^{-1}y|=\Big|\tan^{-1}\left( \frac{x-y}{1+xy}\right) \Big|\leq |\tan^{-1}(x-y)|\leq|x-y|<\delta$$
We can choose $\epsilon=\delta$. Now, for negative $x,y\in \Bbb{R}$. Please, how do I go about it?
Comment: I am afraid that any attempt to prove that claim is doomed to fail.
Comment: What you have started on seems to be to prove that it *is* uniformly continuous... Continue with that!
Comment: @ Hagen von Eitzen: Then, what should I do?
Comment: Actually,  this function  is uniformly continuous because of the limits $\lim\limits_{x\to +\infty}f(x)=\frac{\pi}{2}$ and $\lim\limits_{x\to -\infty}f(x)=\frac{-\pi}{2}$.
Comment: @ Piquito I did  not say "continuous and bounded  implies uniform continuous." I mean the existence of limits implies uniform continuous!!!!! OK???
Comment: @ Piquito For your example, both the two limits do not exist!
Comment: You are right I misunderstood your comment. I have put your first upvote. It wasn't necessary your three ???. I delete my comment. Regards.
Comment: @Riemann: Exactly, both the two limits do not exist! (from this the counterexample)
Comment: @ Piquito Sorry to three ???. Actually I didn't mean to offend you!Only just to emphasize.
Answer: The function $\tan^{-1}x$ is uniformly continuous on $\Bbb{R}$.
By the Mean Value Theorem, for any $x,y\in\Bbb{R}$,
$$|\tan^{-1}x-\tan^{-1}y|\leq |x-y|.$$
So for any $\epsilon>0$, take $\delta=\epsilon>0$, when $|x-y|<\delta$, we have
$$|\tan^{-1}x-\tan^{-1}y|\leq |x-y|<\delta=\epsilon.
$$
Comment: Your first inequality it would be enough. Regards.
Comment: Yes, you are right. There is no need to say any word!
Answer: You can do it in another way, that, find its derivative and observe that derivative is bounded then use LMVT to conclude the uniform continuity


Combinatorics problem (Pigeonhole principle).

Question: let {${a_i}$} $1\le i \le 55$ be a sequence of positive integers (not 0), and $\sum_{i=1}^{55}a_i \lt 95$.
And i'm asked to prove that there must exist a sequence $k \lt l$ in $[55]$ , such that $\sum_{i=k+1}^{l}a_i = 15$.
i thought about this: if all the sequence is 1's so there, the must exist one,
ina case that not all of them 1, all of them cannot be 2, so the sum of the sequence is got to be bounded by 55 and 94, i just feel like it was intended to use the pigeonhole principle and I can't figure out how.
Comment: Is there a significance to the sum indices starting at $0$ or is this a typo?
Comment: +1 nice question! Harder than it looks. One observation, might be obvious, but could be useful: The sub-sequence you're looking for can be at most 15 numbers long (because they're all above 0). It does smell of pigeonhole alright.
Comment: pigeonhole principle? Hundred, or so years ago? Probabilistic method of Erdos et al...
Answer: Consider the sequence of initial sums $S(0),S(1),\ldots,S(55)$
$$
S(n)=\sum_{i=1}^na_i.
$$
We have
$$S(0)=0<S(1)<S(2)<\cdots<S(55)<95,$$
a sequence of 56 distinct integers in the interval $[0,94]$ of $95$ possibilities.
Consider also the sequence of numbers $T(i)=S(i)-15$. There are 56 of those as well, all integers in the range $[-15,79]$. Because they are all distinct, at least $56-15=41$ of them are non-negative.
Hints:

Can you show that the sets $\{S(i)\mid 0\le i<56\}$ and $\{T(i)\mid 0\le i<56\}$ must have a non-empty intersection?
Do you see how the claim follows from this?

Spoiler #1

 Between them the two sets have 97 positive integers in the range $[0,94]$ so the pigeonhole principle tells us that there is some overlap.

Spoiler #2

 If $T(\ell)=S(\ell)-15=S(k)$ then $$ \sum_{i=k+1}^\ell a_i=S(\ell)-S(k)=15.$$
Comment: Not really, care to explain?
Comment: $\forall i : a_i \neq 0$
Comment: If $T(\ell)=S(k)$ then...
Comment: Very nice, the pigeonhole part: $56+41 = 97$
Comment: Indeed, @Colm. AFAICT we could allow the sum to reach $95$.
Comment: Yes the proof works up to 96, beyond that who knows. Would be interesting to prove the converse for 95.
Comment: Very nice proof, after reading it 70 times and
Comment: @YvesHalimi: Hard work pays off :-)
Comment: @Jyrki I really hope so ! :)
Answer: This is essentially the same answer as already given, but from a slightly different point of view. Keep this trick, because it pops up all over the place, for instance in the proof of Chebyshev's Inequality.
Instead of writing
$$
S = \sum_{i=1}^{55} a_i
$$
where $a_i \in \{1, 2, 3, \cdots\}$, let $N_k$ be the number of $i \in \{1, \cdots, 55\}$ such that $a_i = k$ and write
$$
S = \sum_{k=1}^\infty k \cdot N_k.
$$
That is, group the $a_i$ by value and add up the totals for each group. Within a group, each element has the same value so you need only count the elements. If you're familiar with measure theory, this is essentially converting a Riemann integral into a Lebesgue integral. (Conversely, if measure theory is confusing, thinking of it like this might help.)
Now observe that for any $a_i > 1$, we are adding at least $2$ to the sum, so we can approximate like this:
\begin{align}
S &= N_1 + \sum_{k=2}^\infty k \cdot N_k \\
&\ge N_1 + 2 \cdot \sum_{k=2}^\infty N_k \\
&= N_1 + 2 \cdot (55 - N_1) \\
&= 110 - N_1.
\end{align}
From here, use the fact that $S < 95$ to show that there are a large number of $a_i$ with $a_i = 1$.
Comment: This is all well, and you can conclude that there are at least 15 indices $i$ such that $a_i=1$. But how did you conclude that there is a sequence of **consecutive** entries $a_{k+1},a_{k+2},\ldots,a_\ell$ such that they sum up to 15?


Copy Excel from Source to Destination

Question: I am trying to copy excel files that start with XXXXX in a source directory and put them into a destination directory that matches the first XXXXX of the excel file. I would also only like to match the first XXXXX of the folder in destination. After the file is then put into the destination folder I want to changes the name. The below code only allows me to drop the src excel into a folder named only XXXXX not ( e.g. 'XXXXX FOLDER') and it only renames the file in the root directory. thoughts?
for root, dirs, files in os.walk(dir_src):
    for file in files:
        if file.endswith(".xlsx"):
            filename = file[:5]
            shutil.copy((dir_src +'\\'+file), (dir_dst + '\\'+ filename))
            for filename in glob.glob(os.path.join(dir_dst + '\\'+ filename, '*.xlsx')):
                    os.rename(filename, 'Weekly_Claims.xlsx')

Comment: Could you add an example, like the excel file with this name should end up in this folder? I am not sure what you want the final directory structure to be like
Comment: I want the excel file 00000_Services.xlsx to put into dir_dest folder that matches the excel slightly. '00000 James Joyce'. So I want to loop through the excel files all silimar in their style (e.g. 00001_ Services to match to then '00001 Hunter S. Thompson') basically given the first 5 char of the src file I want to copy it to a matching string folder in dir_des subfolder and put it into their. so 00000 matches the full 00000 James Joyce folder and copies only excel file 00000_Services.xlsx into it.  Does that help? Also all these folder in dir_des are already created.
Comment: @EdgarH if this is too verbose I can DM or email? Appreciate the help.
Answer: I think I figured it out... Though someone out there might have a more pythonic way of doing it
import glob,os
import shutil
import re

for root, dirs, files in os.walk(dir_src):
    for file in files:
        if file.endswith(".xlsx"):
            filename = file[:5]
            src_file = os.path.join(dir_src, file)
            #search destination subdirectory for folder
            for root, dirs, files in os.walk(des_test):
                for name in dirs:
                    #if the source filename equals first 5 of the subdirectory name, copy to the des_file
                    if filename == name[:5]:
                        dst_file = os.path.join(des_test, name)
                        shutil.copy(src_file, dst_file)

Copy Excel from Source to Destination