text:
Q: Disable "Share" tab in MS Word 2016 My problem
MS word 2016 adds a "Share" button above the ribbon.  It is bound to the "Y" Alt-access key, which conflicts with another extension I have installed.

This adds extra key presses to a keyboard shortcut I use frequently, and means I need to retrain my muscle memory and use a different series of keystrokes on workstations with different Word installations. As I don't use the "Share" functionality, I'd like to remove this button.
What I've tried

*

*I can't find an option within Word.

*I've added the Registry DWORD key Computer\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\16.0\Common\SignIn\SignInOptions with a value of  1

*Per Microsoft's advice, I've downloaded a Group Policy Template, but when I run the program it doesn't seem to create any files; when I run "Edit group policy" from the Control Panel, Word isn't listed under User Configuration→Administrative templates, and I can't find a profile to add.

*Setting the registry key HKEY_CURRENT_USER\SOFTWARE\Policies\Microsoft\office\16.0\Word\DisabledCmdBarItemsList\TCID1 to 26594 (per @harrymc below) disables the button but doesn't remove the Alt shortcut:

A: To disable the Share button in Office 2016/2019 :

*

*Open the registry editor regedit

*Ensure that the following keys exist (create missing keys):
HKEY_CURRENT_USER\SOFTWARE\Policies\Microsoft\Office\16.0\Word\DisabledCmdBarItemsList

*Add a String value named TCID1 (if already exists, increase the number)

*Set its value to 26594

*Start Word and check that the button is disabled.


text:
Q: Enable GPU for cryptocurrency mining while running monitor off IGP? Users in the cryptocurrency community usually solve this by either:
-Using DVI-A or such to vga adaptor and make a dummy plug with resistors. However, all my hardware run with DVI-D. Vga adaptors don't fit.
-Or supposedly just installing amd drivers, amd sdk and intel IGP drivers + reboot enable both IGP and GPU and they then both support opencl.
My problem is the intel website auto detect doesnt work, manually getting drivers for my i3 3220 IvyBridge all return "computer does not meet requirement" when trying to install them.
Right now what happen is when i boot on IGP as primary, GPU (r9 290) is detected but labeled inactive by miner applications and GPU-Z report OpenCL disabled for the r290 and also for the IGP. (the later is supposed to be enabled if you can install opencl 1.2 for intel IGP but i edit:can't because of same previous error)
W7 64bit, i3 3220 (HD2500), r9 290.

A: I am in a similar situation as you, but I got this to work. I have a Core i7 3770K and a Radeon HD7970. Using the latest available graphics drivers from Intel and AMD for Windows 8.1 64-bit, with my BIOS's "IGP Multi-monitor mode" set to "Enabled", I was able to use the IGP as my graphics card by plugging an HDMI HDTV into the motherboard, with nothing plugged into the Radeon, and use the Radeon for compute in the OpenCL application "Diablo Miner" (Java program). It lets you specify the OpenCL device, and both Intel and AMD ICDs were available, so I went ahead and chose AMD.
If you are unable to reproduce this functionality, it could be:

*

*Your IGP doesn't support multi-monitor mode? I believe this is required. What it should really say is "multi-graphics card mode" from what I can tell, but BIOSes are awful at describing what their options actually do.

*Windows 7, using an older revision of the WDDM specification, doesn't support the required infrastructure that's needed for this configuration? In that case, try Windows 8 or 8.1 (8.1 bumps the WDDM revision, so I'd go with 8.1 if I were upgrading from Windows 7.) Also of note is that AMD and Intel maintain separate drivers for Windows 7 and Windows 8/8.1, so it could be a Windows7-driver-only bug you are encountering.

*An OpenCL ICD issue? As I recall, older Intel (or was it AMD? I forget now) drivers have a problem with their OpenCL ICD, where the one "errant" ICD will take precedence over and hide all other ICDs from being made available to programs. If you're in this situation, you may have to completely uninstall and purge all graphics driver implementations on your system; ensure that no ICD remnants remain; and install fresh (as to what's the proper order of installing the Intel or AMD driver first, I couldn't tell you, as I'm not sure.)

In conclusion, there are various things it could be, but the configuration should be possible without having to create a fake VGA plug or anything silly like that. Recent Intel and AMD drivers -- at least on Windows 8/8.1, can't speak for 7 -- should be able to support "compute from anything, render to anything" configurations, where you can choose which device you want to be the graphics renderer, and choose which device you want to be the compute card. From what I understand, a chip on the motherboard from LucidLogix is supposed to support or enable this, but I don't have their software installed, so I'm not sure if my LucidLogix Virtu MVP device is enabling me to have this configuration, or if it's just built into the platform controller hub of all Z77-series motherboards.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Probability of linear separation in a dataset with categorical response I am simulating datasets to which I fit polytomous logistic regression models. The maximum likelihood estimator of this model is undefined when all categories are linearly separated (and it is quite unstable when there are "close" to be) from all others. My question is: what is the probability of this happening ? It clearly increases with the dimension of explanatory variables and decreases with the number of data points. Is there any known result on that ?
More formally,
let $x_1, ..., x_n$ be $n$ i.i.d. realizations of a random variable $X \in \mathbb{R} ^ p$ following a distribution $F_X$, and $Y_1, ..., Y_n$ be n categorical responses among $\{1, ..., K\}$ following multinomial distribution with logistic link (including an intercept) to $x_1, ..., x_n$, i.e. such that $P(Y_i = k) = \frac{e^{\alpha_k + {\beta_k}^T x_i}}{1 + \sum_{j = 1}^{K-1} e^{\alpha_j + \beta_j^T x_i}}$ for $k \in \{1..K-1\}$ and $P(Y = K) = \frac{1}{1 + \sum_{j = 1}^{K-1} e^{\alpha_j + \beta_j ^T x_i}}$.
What is the probability that there exist $K$ lines $l_1, ..., l_K$ such that $l_k$ separates $\{x_i : Y_i = k\}$ from $\{x_i : Y_i \neq k\}$ ?
Any asymptotic equivalent would already be of great use.
For simplicity, $X$ can be assumed to be $\mathcal{N}(0, I_p)$ or can be supposed fixed.

A: First of all, for more than one class, the estimator is stable unless you add the intercepts to your model (one for each class other than baseline), so $P(Y_i = k) = \frac{e^{{\beta_k} x_i}}{1 + \sum_{j = 1}^{K-1} e^{\eta_{ji}}}$ where $\eta_{ji} = \beta_{0j} + \beta_{ji} \cdot x_i$ if $x$ is univariate. Note that I also had to introduce another index $j$ to distinguish it from $i$, that ranges over the observations instead.
Also, another point is that, for the estimation to diverge, you need at least one category to be linearly separable from all the others, not all of them being linearly separable from each other. For instance, a multilogit won't converge in Iris dataset even if versicolor and virginica species are not separable, that's because there is setosa, which is.
I am not sure about what answer are you looking for, but the exact one depends on a set of $(K-1)(m+1)$ postulated parameters, where $m$ is the number of predictors, as well as the distribution of $X$ and on the total number of observations of course. Given these, you can estimate the probability that any of the classes is linearly separated from all the others put together. That's the probability that the model estimation won't converge.
By the way, I'm not saying that given all this information the computation will be easy, but without it, it is clearly impossible.
Take this simple example, which doesn't even include information on the number of sample $n$ or on the steepness of the slopes:

Of course, the steepier are the slopes, the likelier is that your data will show linearly separable categories, but it is also clear from this example that the distribution of $X$ also plays a crucial role: here we can reasonably expect category $y_1$ to be separable because it has good probability of being observed just on a little proportion of the sample, quite set aside from the other data points.


text:
Q: How this php query generated a selection input field? <p class="<?php if (get_option('jr_submit_cat_required')!=='yes') : echo 'optional'; endif; ?>"><?php _e('Job Category', 'appthemes'); ?> <?php if (get_option('jr_submit_cat_required')=='yes') : ?>*<?php endif; ?> <?php
            $sel = 0;
            if (isset($posted['job_term_cat']) && $posted['job_term_cat']>0) $sel = $posted['job_term_cat'];
            global $featured_job_cat_id;
            $args = array(
                'orderby'            => 'name',
                'exclude'            => $featured_job_cat_id,
                'order'              => 'ASC',
                'name'               => 'job_term_cat',
                'hierarchical'       => 1,
                'echo'               => 0,
                'class'              => 'job_cat',
                'selected'           => $sel,
                'taxonomy'           => 'job_cat',
                'hide_empty'         => false
            );
            $dropdown = wp_dropdown_categories( $args );
            $dropdown = str_replace('class=\'job_cat\' >','class=\'job_cat\' ><option value="">'.__('Select a category…', 'appthemes').'</option>',$dropdown);
            echo $dropdown;
        ?>

I try to insert  onchange="changeValue(); into this select field, but I can not find the  field!!
 Yet the code actually generates a select field in the form.
Please help me find out why.

A: Its generating the <select> for you, but you could sneak it in near the bottom.
replace this line
$dropdown = str_replace('class=\'job_cat\' >','class=\'job_cat\' ><option value="">'.__('Select a category…', 'appthemes').'</option>',$dropdown);

with this
$dropdown = str_replace('class=\'job_cat\' >','class=\'job_cat\' onchange="changeValue();"><option value="">'.__('Select a category…', 'appthemes').'</option>',$dropdown);

and it should work as you asked!


text:
Q: Meteor: Iterating over mongoDB collection produces no results I have a collection in Mongo that is populated with three records.
When viewing my app in localhost, it lists nothing. There are no errors displayed, however nothing is listed either.
What am I doing wrong?
Console output from manual find:
meteor:PRIMARY> db.users.find({})
{ "_id" : ObjectId("55ddba705374fcb03117d585"), "username" : "coderboy", "joined" : ISODate("2015-08-26T13:09:04.872Z") }
{ "_id" : ObjectId("55ddc7475374fcb03117d586"), "username" : "plumberboy", "joined" : ISODate("2015-08-26T14:03:51.960Z") }
{ "_id" : ObjectId("55ddcf3b5374fcb03117d587"), "username" : "sparkieboy", "joined" : ISODate("2015-08-26T14:37:47.883Z") }

HTML:

Our users:

            {{#each user}}
                {{> userlist}}
            {{/each}}

<template name="userlist">

{{username}}

</template>

JS:
users = new Mongo.Collection("users");

if (Meteor.isClient) {
    Template.userlist.helpers({
            user: function () {
               return users.find({});
            }
    });
}

A: You use the user helper of userlist outside of the userlist template. So that's not defined. An easy fix is put move the each into the userlist template.

Our users:

            {{> userlist}}

<template name="userlist">
    {{#each user}}

{{username}}

    {{/each}}
</template>


text:
Q: Send a message using message.content I want to send a message which uses the message content
If a user writes !alcool, for example, I want my bot to answer textealcool.png
If they write !car, I want textecar.png.
My code is :
from discord.ext.commands import Bot

BOT_PREFIX = ("!")
TOKEN = "XXXXXX"

client = Bot(command_prefix=BOT_PREFIX)

@client.event
async def on_message(message):
    if message.content.startswith("!"):
        newMessage = 'texte' + str(message.content)[1:] + '.png'
        await client.send_message(message.channel, newMessage)

client.run(TOKEN)

I wrote "!alcool" but my Bot answered with :
textealcool
texte!alcool
textealcool
texte
textealcool.pgn
textealcool.pgn
textealcool
textealcool.pgn
textealcool

I don't understand why I have so many answers with only two are right.

A: In the line
newMessage = 'texte' + str(messagelu)[1:] + '.png' what is messagelu?
Change messagelu to message.content and it will work


text:
Q: Prove that there exists n such that $\frac{1}{n+1}\leq\frac{x}{y}<\frac{1}{n}$. Prove that there exists a natural number $n$ such that $\frac{1}{n+1}\leq\frac{x}{y}<\frac{1}{n}$ where $\frac{x}{y}$ is a rational number and $0<\frac{x}{y}<1$ and $x,y>0$ and $x$ and $y$ have no common divisors.

A: Hint: Consider $\lfloor\dfrac{y}{x}\rfloor$. Also note that this is not the answer.

A: It appears that you have all the pieces, so here's how I would approach the problem:
Given rational $\frac xy$ such that $0\lt \frac xy \lt 1$, we have $0\lt x \lt y$, or $1 \lt \frac yx$.  There must exist a positive integer $n$ such that $n\le \frac yx\le n+1$, which means that $\frac 1n\ge \frac xy\ge \frac 1{n+1}$.
Given that $\frac 1n \gt \frac 1{n+1}$, we can say that if $\frac xy=\frac 1k$, choose $n=k-1$ so we can write $\frac 1n\gt \frac xy \ge \frac 1{n+1}$.  Then we have shown the required inequality.
Alternatively, note that $\frac 1n - \frac 1{n+1}=\frac 1{n(n+1)}$, meaning that there is a nonempty interval of values between the two.  Further, note that for all $n$, if $\frac xy \lt \frac 1{n+1}$, then let $n\to n+1$ and compare again.


text:
Q: Which is better: "bidirectionally-anonymous channel" or "bidirectional-anonymous channel" I am writing my thesis (in computer science) and me and my supervisor disagree about the correct way of describing a communication channel which is anonymous in both directions. Without delving in too much technicalities, think of this channel as if there is a special button on your mobile phone that, when you click on it, will call someone else in the country, such that you do not get to know his phone number (or any other information about him) nor does he get to know your phone number or any other information about you. You both are anonymous with respect to each others. This is a property of the channel: it provides anonymity to both its ends. So it is bidirectional[ly]-anonymous channel.
Which is the right way in English to describe it:

*

*Bidirectionally-anonymous channel, or

*Bidirectional anonymous channel?

Thank you.

A: "Bidirectionally anonymous" works, because if the channel is not bidirectional in the first place it cannot be bidirectionally anonymous.

A: The ambiguity might arise because of the understanding of whether or not a channel is inherently bi-directional or not.  To be fully precise you might say "bi-directionally anonymous bi-directional channel" that would clarify the simplex/duplex confusion.
"Bidirectionally anonymous channel" means that that each channel is anonymous and a channel is bi-directional. Otherwise you don't have a need for bi-directionality of anonymity.
"Bidirectional anonymous channel" means that a channel is inherently one directional, but in this case it is bi-directional and at least one of the channels is anonymous.
Bidirectionally anonymous is more concise as the bi-directionality applies to the anonymity as opposed to applying to the channel.


text:
Q: Block sent SMS from being logged in default messaging app I have an auto reply sms Android application I built and I don't want the auto reply (sent sms) to show in the default messaging app. I have searched and searched and couldn't find an answer. Is there a way to bypass writing the sent sms into the default messaging app?
Here my BroadcastReciever I am using to get the data and send out the message
public class SmsReceiver extends BroadcastReceiver {

ParseUser user = ParseUser.getCurrentUser();
// Auto reply message composed of the current reply and url from that business
String msg = user.getString("myCurrentReply") + " " + user.getString("couponUrlChosen");

List smsFromList = user.getList("smsFrom");
String userName = (String) user.get("username");

@Override
public void onReceive(final Context context, Intent intent) {
    Bundle bundle = intent.getExtras();

    Object messages[] = (Object[]) bundle.get("pdus");
    SmsMessage smsMessage[] = new SmsMessage[messages.length];
    for (int n = 0; n < messages.length; n++) {
        smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
    }
    final String pno = smsMessage[0].getOriginatingAddress();
    user.put("lastSmsFrom", pno);
    user.saveInBackground();

    // show first message
    Toast toast = Toast.makeText(context, "Received SMS: " + smsMessage[0].getMessageBody(), Toast.LENGTH_LONG);
    toast.show();

    // Check Phone Number from SMS Received against Array in User Row
    ParseQuery<ParseObject> query = ParseQuery.getQuery("_User");

    Log.d("Username: ", userName);
    query.whereEqualTo("username", userName);
    query.whereContainedIn("lastSmsFrom", smsFromList);
    query.findInBackground(new FindCallback<ParseObject>() {
        public void done(List<ParseObject> smsList, ParseException e) {
            if (e == null) {
                Log.d("Errors", "none");
                if (smsList.size() == 0) {
                    // Send SMS
                    sendSms(pno, msg);

                    // Add Phone number to smsFrom in currentUsers Row
                    user.addUnique("smsFrom", pno);

                    // Save Phone Number in Array
                    user.saveInBackground();

                    Log.d("List size: ", " " + smsList.size());

                }
            } else {
                Log.d("Error Message: ",
                        e.getMessage());
            }
            Log.d("Already sent to this number today. ", " " + smsList.size());
        }
    });

}

private void sendSms(String phonenumber, String message) {

    SmsManager manager = SmsManager.getDefault();
    manager.sendTextMessage(phonenumber, null, message, null, null);

}
 }

A: Prior to KitKat, SMS sent using SmsManager require the app sending the message to insert it into the Provider, so it would just be a matter of omitting that.
Starting with KitKat, any app that is not the default SMS app and uses SmsManager to send messages will have the messages automatically written to the Provider for it by the system. There's no way to prevent this, and, furthermore, the app won't be able to delete those messages, either, as it won't have write access to the Provider.*
The app that is the default SMS app is responsible for writing its outgoing messages, so it would be able to omit that step. The system does no automatic writes for the default SMS app.

* There is a security hole in 4.4 only, by which a non-default app can gain write access to the Provider. It is detailed in my answer here, but it will not work in versions after KitKat.


text:
Q: How to fix this error in git clone I have tried different methods to install this, but it still does not work. I am trying to clone from github using git clone https://github.com/CocaPods/Specs.git master. Please share your ideas. I am using Mac Sierra with 8GB Ram.

A: This error most likely cause of low buffer size of git. Other reason,  Antivirus or Firewall could be modifying the HTTP packets.

*

*Increase the git buffer size:
$ git config --global http.postBuffer 2M

*Disable your Antivirus or Firewall for some time and try clone again.

A: not sure if your problem is cloning or running some command of the project.
to clone try both:

*

*git clone https://github.com/CocoaPods/Specs.git

*git clone git@github.com:CocoaPods/Specs.git


text:
Q: i can't install docker on ubuntu 17.10 i'am trying to install Docker on my ubuntu 17.10 so  i followed the instructions on the link :
https://docs.docker.com/install/linux/docker-ce/ubuntu/
 sudo apt-get update

it shows
sudo apt-get install \
apt-transport-https \
ca-certificates \
curl \
gnupg-agent \
software-properties-common

shows

what can i do please ?

A: I had similar issues installing Docker on a Ubuntu VM. This is what worked for me.
sudo apt update
sudo apt install apt-transport-https ca-certificates curl software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic stable"
sudo apt update
apt-cache policy docker-ce
sudo apt install docker-ce

And finally sudo systemctl status docker to check if it has installed properly.

A: symlinking the https dir in /usrLib/apt/methods to http seems to work:
$ cd /usr/lib/apt/methods
$ ln -s http https

Make sure you dont have any sources with https:// configured after apt-get install apt-transport-https it actually overwrites the symlink with the correct files.
After that run the docker installation script:
# remove old packages
$ sudo apt-get remove docker docker-engine docker.io containerd runc

# update
$ sudo apt-get update

# install dependencies
$ sudo apt-get install \
apt-transport-https \
ca-certificates \
curl \
gnupg-agent \
software-properties-common

# fetch rep
$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

# add stable repo
$ sudo add-apt-repository \
"deb [arch=amd64] https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) \
stable"

# update
$ sudo apt-get update

# install
$ sudo apt-get install docker-ce docker-ce-cli containerd.io

This should work (from official docs)


text:
Q: Developer Script error I got an apex script error email as i have been set as the last modified by for that apex class.But i have never updated the class,so how did the last modified by field get updated by my name?Is there any process automation /workflow that set affects the last modified by?

A: There's no workflow rule or process that would have affected this field. It may have been part of a synchronization using the Force.com IDE, Migration Toolkit, Gearset, etc. Just because you didn't change the content does not mean that your user did not perform a "change" as defined by the last modified by field.


text:
Q: Is it possible to make a call from iphone simulator and put some listeners to it? I am new to iphone development.
I just want to know that is it possible to make a call from iphone simulator and then register some listeners to monitor this?

A: You cant make calls from simulator. Though there is an option Hardware->Toggle in-call status bar, which changes the status bar.

A: No it's not possible.Phone call,sms,Camera option,GPS,push notifications etc.. we are not able to test it on simulator


text:
Q: SFM module for OpenCV on Windows I already installed OpenCV 3.1 with opencv_contrib on Windows.
Now i want to use the SFM module inside the opencv_contrib, but on the website of the module (http://docs.opencv.org/3.1.0/db/db8/tutorial_sfm_installation.html) it says "Note: The module is only available for Linux/GNU systems."
Does anyone know if and how i am still able to use it on Windows?

A: You could try this:
http://qiita.com/ChaoticActivity/items/3888e886925ef0f84926.
Here is the english translation:
https://translate.google.com/translate?hl=en&sl=auto&tl=en&u=http%3A%2F%2Fqiita.com%2FChaoticActivity%2Fitems%2F3888e886925ef0f84926&sandbox=1


text:
Q: I am trying to publish the App into playstores but its giving me for violating our dangerous products policy this the error mail getting from the Google and i am using the Android studio for the development of apps i am not able to understand why i am getting this error because there no violence of the google developer policy
this is project struture i had copied the WWW folder from the Created android folder by cordova
    Vulnerability   APK Version(s)
    Apache Cordova
The vulnerabilities were fixed in Apache Cordova v.3.5.1. For more information about the vulnerabilities, and for guidance on upgrading Apache Cordova, please see https://cordova.apache.org/announcements/2014/08/04/android-351.html. For other technical questions about Apache Cordova, please post to Stack Overflow and use the tags "android-security" and "cordova."

A: npm install -g cordova
cd my_project
cordova platform update android

A: replace the WWW folder with your contain folder in it after updating the cordova which includes CSS,Image,Js files and the links of html in it.


text:
Q: Change start of weekday from monday to sunday in datetimeindex in python The default start of the weekday is Monday (0) in Pandas. Am trying to make this as Sunday instead on datetimeindex for getting weekly counts ending on Saturday to forecast a timeseries model.

A: I got a breakthrough, yes.
From my previous code, I redefined W-SAT instead of the default W.
Previous code:
weekreq = daysreq.resample('W').apply({'Numbers':'sum'})
to
New code:
weekreq = daysreq.resample('W-SAT').apply({'Numbers':'sum'})


text:
Q: How can I find my building in a superflat world? I made a superflat world and typed /tp ~ ~ ~-10000 or something similar a few times to have a separate area to build a house on, but i accidentally died and lost my house. What can I do to find it?
I have McEdit if that helps.

A: If you had any entities in your building that do not spawn naturally in the superflat, eg. Villagers, cats, dogs, horses,  item frames, dropped items ("Item") etc., you can try to teleport to them:
/tp @p @e[type=EntityName]

Don't forget to write the type of entity with a capital letter at the beginning.

A: Assuming no-one traveled in a different direction, you can look at the region files to find the one furthest away from spawn. Your building is likely in that 512x512 area.

A: The easy way is to use a compass to lead you back to your original spawnpoint (if that is where you want to get back to). Follow the red line in the compass until you see your build in or just wait until the lines turns over and faces the other way. I'm sure there is other ways but this is the simplest.


text:
Q: Why are 5+ expected frequencies needed in Pearson's chi-square I've been told in my current textbook that for approximation of the exact distribution by means of $X^2$ or $G^2$ the expected frequencies have to be $\ge 5$.
The book says that the approximation could be biased, but I wonder how and why?

A: The counts are discrete. The chi-square approximation for $X^2$ relies on the counts being approximately normally distributed; when all the expectations are greater than 5 the chi-square approximation often tends to be at least reasonable; it's a pretty arbitrary cut-off though and not suitable in every circumstance. For $G^2$ it relies on an asymptotic argument; I think it generally comes in more slowly than for $X^2$. The condition of all expecteds above 5 is very old; many more recent papers suggest somewhat less stringent requirements are fine for the Pearson.
Basically, when a discrete r.v. has nearly all its probability concentrated in a few values, even the best of continuous approximations is not going to be much good. Consider a chi-square goodness of fit test for a bernoulli(.25), where we have 4 observations. The chi-square is the sum over the number of $0$'s and $1$'s of the usual $(O-E)^2/E$. The two expected counts are 3 and 1. The actual distribution of the chi-square statistic takes exactly four values. The chi-square(1) has a 5% critical value of 3.84, but the 95th percentile of the actual distribution is 5.33.


text:
Q: With 'hg record', is there a way to automatically look at all changes in all files? hg record is very useful for splitting the changes in your working copy into multiple commits.
When you run hg record, it will ask you for each modified file:
examine changes to '<file>'? [Ynesfdaq?]

and if you say yes, then for each change in the file:
record change X/Y to '<file>'? [Ynesfdaq?]

However, I often find that I could complete the operation much more efficiently by automatically being shown all changes (i.e. as if I said y to every question of the first form). Basically, I want to see all changed hunks and make yes/no decisions about them, without the distraction of intervening examine changes to <file>? questions (to which I would always say yes).
Is there to get hg record way to do this?

A: I find the CRecord Extension invaluable for this. It gives a curses based UI for the record command, and allows you to get a much better overview of all your changes. It also allows you to select down to line resolution, rather than just each hunk.


text:
Q: I'd like to incorporate an advanced custom field into my Wordpress menu Here's my code now:
$menu_icon = get_field('menu_icon');

if($menu_icon) {
    $m_icon = '';
} else {
    $m_icon = "";
};

$personal = array(
    'theme_location'  => 'personal',
    'menu'            => 'Personal Menu',
    'before'          => '$m_icon',
);

wp_nav_menu( $personal );

And here's what it spits out:

        $m_icon Link

$m_icon SubLink 1

$m_icon SubLink 2

$m_icon SubLink 3

I'd like to have it produce something like this:

        Link

 SubLink 1

 SubLink 2

 SubLink 3

Here's the general idea:

It's wrong for a few reasons. I know the advanced custom field: "menu_icon" probably isn't able to retrieve anything outside of a loop, and I'm not familiar enough with the wp_nav_menu() function to know whether or not it's possible to echo an image specific to the page it's displaying.
Does anyone know how I can achieve this?

A: Not exactly what you asked for and i don't have the correct solution for your entire problem right now but i can help you with getting custom fields to work outside the loops if that helps you :)
you just have to set the page ID after your field name for it to work outside of loop like this
get_field('your-field', $page_ID);

A: One thing I notice right away is that you have extra single quotes, and php is translating the content literally. You actually want the string contained in $m_icon, and NOT the string '$m_icon' which is not a variable.
$personal = array(
    'theme_location'  => 'personal',
    'menu'            => 'Personal Menu',
    'before'          => $m_icon, //this line was wrong, single quotes means 'literally this$ $tring'
);

Edit:
I took the liberty of writing a filter function for what you're trying to do. Cheers.
function insert_icons($items, $menu, $args){
    //check our menu name so we filter the right one
    if($menu->name=='Personal Menu'){
        //loop through the menu items
        foreach($items as $key => $item){
            //make sure object_id is set (this is the page or post id)
            if(isset($item->object_id) && !empty($item->object_id)){
                //grab the menu icon
                $menu_icon = get_field('menu_icon',$item->object_id);
                //make sure the previous line returned something
                if(isset($menu_icon) && !empty($menu_icon)){
                    //create our image string
                    $m_icon = '';
                    //insert it into the page title
                    $item->title = $m_icon.$item->title;
                }
            }
        }
    }
    return $items;
}
add_filter('wp_get_nav_menu_items','insert_icons',NULL,3);


text:
Q: Angular:  with filter I have:
<select name="club" id="club" ng-model="currentUser.club_id" ng-options="club.id as club.name for club in clubs | filter:{ country_id: currentUser.country_id }" required></select>

I'm happy with that, except that since I filter the clubs list, there are cases where <select> has no <option>, which implies that the required attribute makes the form unsubmittable.
I could do
<select ng-required="(clubs | filter:{ country_id: currentUser.country_id }).length"></select>

but I though maybe there is a more elegant way to do that. Something like:
<select ng-required="$element.options.length"></select>

Is my intuition correct? What's the way to do that?

A: You can simply try
ng-repeat="item in filtered = (items | filter:filterExpr)"

and then use
filtered.length

This works for ng-options too !
Hope this was helpful
Reference Filter Length


text:
Q: Pandas - flatten columns After:

*

*aggregating with sum()

*grouping by ['country', 'match_id']

*creating a mean column with mean(axis=1)
I ended up with this:
                     Gls  Ast  avg_attack
                     sum  sum
country    match_id
Argentina  20eb96e2  0.10 0.20 0.15
           18eb43e2  0.20 0.30 0.25
...

Now, how do I flatten my dataframe back to this?
country     match_id Gls  Ast  avg_attack
Argentina  20eb96e2  0.10 0.20 0.15
Argentina  18eb43e2  0.20 0.30 0.25

A: Use pandas.Index.get_level_values to flatten the hierarchical index in columns then pandas.DataFrame.reset_index to reset the multi index in rows.
df.columns = df.columns.get_level_values(0)
out = df.reset_index()

# Output :
print(out)

     Country  match_id  Gls   Ast   avg_attack
0  Argentina  20eb96e2  0.10  0.20        0.15
1  Argentina  18eb43e2  0.20  0.30        0.25


text:
Q: Nested object lists, last list not accessible? In the code below I try to add the AttributeValueInfoEntity to the AttributeValueExportList, however it is not showing up as a property of the ArticleAttributeExportLarge object at the place where I put //largeExportList.AttributeExportList in the code.
Am I doing something wrong, or am I missing a important nesting rule in C#?
public partial class Export_Articles_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
            ArticleInfoEntity[] articleInfoList = ArticleInfoFactory.Instance.ListInfo(244);
            List<ArticleExportLarge> list = new List<ArticleExportLarge>();

            foreach (ArticleInfoEntity aie in articleInfoList)
            {
                ArticleExportLarge largeExportList = new ArticleExportLarge(aie);
                largeExportList.AttributeExportList = new List<ArticleAttributeExportLarge>();

                List<AttributeInfoEntity> attributeInfoList = AttributeInfoFactory.Instance.ListByArticle(aie.ArticleId);

                foreach (AttributeInfoEntity attributeInfo in attributeInfoList)
                {
                    largeExportList.AttributeExportList.Add(new ArticleAttributeExportLarge(attributeInfo));
                    List<AttributeValueInfoEntity> ArticleValueInfoList = AttributeValueInfoFactory.Instance.ListByArticleAndAttribute(aie.ArticleId, attributeInfo.AttributeId);

                    foreach (AttributeValueInfoEntity avie in ArticleValueInfoList)
                    {
                       //largeExportList.AttributeExportList
                    }
                }

                list.Add(largeExportList);
            }
        }
}

public class ArticleExportLarge
{
    private ArticleInfoEntity articleInfo;
    private List<ArticleAttributeExportLarge> attributeExportList;

    public ArticleExportLarge(ArticleInfoEntity articleInfo)
    {
        this.articleInfo = articleInfo;
    }

    [XmlElement(ElementName = "attributeList")]
    public List<ArticleAttributeExportLarge> AttributeExportList
    {
        get { return attributeExportList; }
        set { attributeExportList = value; }
    }

}

public class ArticleAttributeExportLarge
    {
        private AttributeInfoEntity attributeInfo;
        private List<ArticleAttributeValueExportLarge> attributeValueExportList;

        public ArticleAttributeExportLarge(AttributeInfoEntity attributeInfo)
        {
            this.attributeInfo = attributeInfo;
        }

        [XmlElement(ElementName = "attributeValueList")]
        public List<ArticleAttributeValueExportLarge> AttributeValueExportList
        {
            get { return attributeValueExportList; }
            set { attributeValueExportList = value; }
        }
    }

public class ArticleAttributeValueExportLarge
{
    private AttributeValueInfoEntity attributeValueExportEntity;

    public AttributeValueInfoEntity AttributeValueExportEntity
    {
        get { return attributeValueExportEntity; }
        set { this.attributeValueExportEntity = value; }
    }

}

A: I found my error. I need to iterate through the secondary list largeExportList.AttributeExportList if I want to access the objects in that list.


text:
Q: Confused about residue of a complex, rational function I am asked to find $\text{Res}(i)$ for $R(z)=\frac{2z+3}{(z-i)(z^2+1)}$. Noticeably, $R(z)=\frac{2z+3}{(z-i)^2(z+i)}$.
While I understand how to find the corresponding partial fraction decomposition for the above equation, I am confused about the nature of $\text{Res}(i)$. Should $\text{Res}(i)$ be the coefficient for the $\frac{A}{(z-i)^2}$ term? Or the coefficient for the $\frac{B}{(z-i)}$ term? Or somehow both?
Thank you for your help!

A: $z=i$ is a double pole of $R(z)=\frac{2z+3}{(z-i)^2(z+i)}$, hence
$$\text{Res}\left(R(z),z=i\right) = \lim_{z\to i}\frac{d}{dz}\left((z-i)^2 R(z)\right)=\lim_{z\to i}\frac{d}{dz}\left(\frac{2z+3}{z+i}\right) $$
and
$$\text{Res}\left(R(z),z=i\right) =\lim_{z\to i}\frac{2i-3}{(z+i)^2}=\color{red}{\frac{3-2i}{4}}.$$
We have
$$ R(z) = \frac{A}{(z-i)^2}+\frac{\color{red}{B}}{z-i}+\frac{C}{z+i}+Q(z) $$
where $Q(z)$ is an entire function and the wanted residue is $B$.


text:
Q: How to dynamically create an anonymous class that extends an abstract class in PHP? Simply, let me explain by an example.
<?php
class My extends Thread {
    public function run() {
        /** ... **/
    }
}
$my = new My();
var_dump($my->start());
?>

This is from PHP manual.
I am wondering if there is a way to do this in more Java-like fashion. For example:
<?php
$my = new Thread(){
        public function run() {
            /** ... **/
        }
      };
var_dump($my->start());
?>

A: Alternatively, you can use PHP7's Anonymous Classes capability as documented at http://php.net/manual/en/migration70.new-features.php#migration70.new-features.anonymous-classes and http://php.net/manual/en/language.oop5.anonymous.php

A: I know this is an old post, but I'd like to point out that PHP7 has introduced anonymous classes.
It would look something like this:
$my = new class extends Thread
{
    public function run()
    {
        /** ... **/
    }
};

$my->start();

A: You do have access ev(a|i)l. If you used traits to compose your class it COULD be possible to do this.
<?php
trait Constructor {
  public function __construct() {
    echo __METHOD__, PHP_EOL;
  }
}

trait Runner {
  public function run() {
    echo __METHOD__, PHP_EOL;
  }
}
trait Destructor {
  public function __destruct() {
    echo __METHOD__, PHP_EOL;
  }
}

$className = 'Thread';
$traits = ['Constructor','Destructor','Runner',];
$class = sprintf('class %s { use %s; }', $className, implode(', ', $traits));
eval($class);
$thread = new $className;
$thread->run();

This outputs ...
Constructor::__construct
Runner::run
Destructor::__destruct

So you CAN, but not sure if you SHOULD.

A: Or you can just use namespaces.
<?php
namespace MyName\MyProject;
class Thread {
   public function run(){...}
}
?>

<?php
use MyName\MyProject;
$my = new Thread();

$my->run();


text:
Q: How do I modify this jQuery :submit selector example? Looking at this jQuery example, how can I modify the code so that it only changes the color of the cell if the value of the submit button in that cell is a certain value.
i.e.-
          var submitEl = $("td :submit")

          //Only do the below if the submit buttons value is "XYZ"

          .parent('td')
          .css({background:"yellow", border:"3px red solid"})

A: $("td input[value='SomeValue']:submit")

A: var submitEl = $('td :submit').filter(function() { return $(this).val() == "certain"; });

You can check for the value in the selector, but it may lead to quoting headaches (depending on the value) and also it may not be quite as fast (though that's rarely a serious concern).

A: select only the elements that have the value you want:
var submitEl = $("td :submit[value='XYZ']")

A: you need a each loop I think this is what your trying to  do
  $("td :submit").each(function(){
   if ($(this).val()== "XYZ"){
     $(this).parent('td').css({background:"yellow", border:"3px red solid"});
   }
   });

EDIT
using better selector eliminates if statment
  $("td:submit[value='XYZ']").each(function(){
     $(this).parent('td').css({background:"yellow", border:"3px red solid"});
  });"


text:
Q: UI Bootstrap Typeahead $digest already in Progress Got $digest is already in progress when trying to populate data from $http.get
And here is my code
JSON result:
[
  {
    "id": 14,
    "name": "RIAU"
  },
  {
    "id": 21,
    "name": "KEPULAUAN RIAU"
  }
]

Controller:
    $scope.getProvince = function(value) {
      return $http.get('/api/v1/province', {
        params: {
          q: value
        }
      }).then(function(response) {
        return response.data;
    });
   }

HTML

            Province
            <input type="text" uib-typeahead="province for province.name in getProvince($viewValue)" placeholder="{{ province }}"
              typeahead-loading="loadingLocations" typeahead-no-results="noResults"
              class="form-control" ng-model="cat.customer.anchor_residence_1.province">

               No Results Found

Anyone know how to resolve this?

A: getProvince function returns Promise, not real data. you have to separate saving data and listing data.
... in provinces ... ng-keydown=getProvince($viewValue) ... in html

#
Problem is to mixed angular digest cycle.
1) getProvince called in digest cycle (in html)
2) getting data from server, before completed return promise.
3) getProvinxe again, because promise is not list. so "falling in digest cycle in digest cycle". Error occured.


text:
Q: Application was slow and even stuck and had to restart the database server What would be the good steps to troubleshoot a situation where the application was and even stuck and I had to restart the database server?
The application was written in Java and ran different reports/queries few time then the application became so slow and stuck eventually. Then, had to restart the SQL database server again to get it back to work. It was obviously running out the resource on the server.


text:
Q: IntelliSense doesn't work for Resources.resx file in WPF/C# project, VS2010 In my WPF 4.0 desktop-based application in order to localize my application (e.g. English & French localizations) I'm using Resources.resx file, where I type dialog name (ID) and its value for English and French localization. Everything works great, except one thing — IntelliSense of Visual Studio 2010.
Let's say, I have a button:
<Button x:Name="Toolbar_Search_Button"
        Content="{x:Static res:Resources.Toolbar_Search_Button}" />

Where I want to put its content (label on the button) in English and in French as well, in order to do this I added to Resources.resx and Resources.fr.resx string with ID Toolbar_Search_Button and gave a value for each of them (Search/Recherche) and now I have to assign the string ID to button content property. In my case I have to write all this long string: x:Static res:Resources.Toolbar_Search_Button and IntelliSense doesn't help me at all. The only thing that it suggests me is Member=, but I want that when I type res:Resources. it gives me all existed strings ID, as we can usually see when IntelliSense is enabled.
I checked VS2010 preferences, IntelliSense is enabled for all kinds of projects/languages and it works when I write other XAML/C# code, like when I type «Wi» it suggests me «Width» etc.
How to enabled IntelliSense for localization/Resources? That I could type res:Resources. and see all localization resources strings that I have.

A: I have exactly the same problem. I don't believe Microsoft is stupid enough to disable that bit of intellisense via some unset option/setting for a default Visual Studio 2010 install.
But I do belive Microsoft is stupid enough not to implement the feature in VS 2010. I could have forgiven them VS 2008, since that was the first proper implementation of XAML design support (VS 2005 plugin is something else). Lack of implementation could perhaps have something to do with the fact if you write a string in your resx file and then specify the key value in XAML, XAML will start complaining that the new key does not exist in your resx file. Once you build your application will XAML start accepting the new key.
Mind you, XAML has horrid intellisense support to begin with. Take for instance the new and improved intellisense in code behind - if you type ".Cust", intellisense will offer both "Customer" and "ExistingCustomer". But the same feature is not implemented in XAML intellisense. There are more such examples...
So to answer your question - you can't enable resx intellisense support in XAML, at least I'm not aware of such a possibility.


text:
Q: Intent not getting fired sometimes I have the following code:
public class CheckoutPresenter extends CheckinOutPresenter {

    @Inject
    public CheckoutPresenter(ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread, OnlineBookingRepository onlineBookingRepository, OfflineBookingRepository offlineBookingRepository, ImageRepository imageRepository) {
        super(threadExecutor, postExecutionThread, onlineBookingRepository, offlineBookingRepository, imageRepository);
    }

    @Override
    protected void bindIntents() {
        Observable<CheckinOutViewState> checkinViewStateObservable =
                intent(CheckinOutView::fetchLocalCheckin)
                        .switchMap(uuid -> offlineBookingRepository.fetchCheckoutById(uuid, false)) <-- Here sometimes get called, sometimes not
                        .subscribeOn(Schedulers.from(threadExecutor))
                        .map(CheckinOutViewState.SuccessLocalFetch::new)
                        .cast(CheckinOutViewState.class)
                        .onErrorReturn(CheckinOutViewState.ErrorStateOut::new)
                        .observeOn(postExecutionThread.getScheduler());

        Observable<CheckinOutViewState> sendCheckin =
                intent(CheckinOutView::sendCheckin)
                        .switchMap(checkinIntent -> imageRepository.saveImage(checkinIntent.getFilename(), checkinIntent.getSignature())
                                .subscribeOn(Schedulers.from(threadExecutor))
                                .filter(cnhImageResponse -> cnhImageResponse.getLinks() != null)
                                .switchMap(response ->  {
                                    CheckinOutCommand command = checkinIntent.getCheckinOutCommand();
                                    command.setSignatureUrlImage(response.getLinks().getUrl());
                                    return onlineBookingRepository.doCheckout(command).subscribeOn(Schedulers.from(threadExecutor));
                                })
                                .subscribeOn(Schedulers.from(threadExecutor))
                                .map(CheckinOutViewState.SentSuccessfuly::new)
                                .cast(CheckinOutViewState.class)
                                .startWith(new CheckinOutViewState.LoadingStateOut())
                                .doOnError(error -> offlineBookingRepository.doCheckout(checkinIntent.getCheckinOutCommand()))
                                .doOnComplete(() -> offlineBookingRepository.deleteCheckoutById(checkinIntent.getCheckinOutCommand().getBookingId(), false))
                                .onErrorReturn(CheckinOutViewState.ErrorStateOut::new))
                        .observeOn(postExecutionThread.getScheduler());

        subscribeViewState(Observable.merge(checkinViewStateObservable, sendCheckin), CheckinOutView::render);
    }

}

which inherits from:
public abstract class CheckinOutPresenter extends MviBasePresenter<CheckinOutView, CheckinOutViewState> {

    protected final ThreadExecutor threadExecutor;
    protected final PostExecutionThread postExecutionThread;
    protected final OnlineBookingRepository onlineBookingRepository;
    protected final OfflineBookingRepository offlineBookingRepository;
    protected final ImageRepository imageRepository;

    CheckinOutPresenter(ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread, OnlineBookingRepository onlineBookingRepository, OfflineBookingRepository offlineBookingRepository, ImageRepository imageRepository) {
        this.threadExecutor = threadExecutor;
        this.postExecutionThread = postExecutionThread;
        this.onlineBookingRepository = onlineBookingRepository;
        this.offlineBookingRepository = offlineBookingRepository;
        this.imageRepository = imageRepository;
    }

}

@Override
    public Observable<String> fetchLocalCheckin() {
        return Observable.just(booking.getBookingId());
    }

But the problem is, sometimes the fetchLocalCheckin is fired, sometimes not.
What am I doing wrong here ? Did I miss something ?

A: @Override
public Observable<String> fetchLocalCheckin() {
     return Observable.just(booking.getBookingId());
}

Observable.just(...). This one triggers exactly one time onNext() followed immediately by a onComplete(). Since Mosby's MviBasePresenter follows the Reactive contract which basically says that once a onComplete() event is received the whole stream "finishes", that means  the CheckinOutView::fetchLocalCheckin only triggers exactly one time and cannot be invoked a second time (because onComplete() already has been triggered).
So if you want to trigger multiple times this intent, don't use Observable.just() but rather PublishSubject or PublishRelay.
i.e. with your case, this one will only ever trigger the first time your View layer (Fragment, Activity, ViewGroup) has been created, but no second time, i.e. after screen orientation changes, because the first time it has been created Observale.just() triggers onComplete() which prevents MviBasePresenter from accepting future events.


text:
Q: Using Firebase Id Token in Firebase Cloud Functions In the function that triggers when firebase user is created, I want to send a request to my rest api server.
How could I get the Firebase ID Token and attach to the api request for verifying step in my api server?


text:
Q: How to know if I'm in packrat mode in R command line? If I'm using RStudio it is very easy to know if I'm in packrat mode: I just open the packages tab and click the Packrat icon. However, I don't know any commands to do it programatically or outside RStudio. Also, packrat commands such as packrat::status() work even if I'm not in Packrat mode.

A: You use packrat::search_path() to infer. See how could be done around it:
With packrat disabled.
> packrat::off()

Packrat mode off. Resetting library paths to:
- "/home/ajoe/R/x86_64-pc-linux-gnu-library/3.4"
- "/usr/local/lib/R/site-library"
- "/usr/lib/R/site-library"
- "/usr/lib/R/library"
>
> any(grepl("packrat", packrat::search_path()$lib.dir))
[1] FALSE

With packrat enabled.
> packrat::on()
Packrat mode on. Using library in directory:
- "~/wx/your_project_dir/packrat/lib"
>
> any(grepl("packrat", packrat::search_path()$lib.dir))
[1] TRUE

The same can be achieved with .libPaths() instead of packrat::search_path().


text:
Q: How to eliminate group of observations under conditions I have a panel data that looks like the following:
id  name    year    dummy
1   Jane    1990    1
1   Jane    1991    1
1   Jane    1992    0
1   Jane    1993    0
2   Tom     1978    0
2   Tom     1979    0
2   Tom     1980    0
3   Jim     1981    1
3   Jim     1982    1
3   Jim     1983    0

I want to subset this data so that I eliminate people without 1 as dummy variable. This means that in the above example, I want to eliminate observations for Tom, because he does not have a dummy variable of 1. Wanted output is:
id  name    year    dummy
1   Jane    1990    1
1   Jane    1991    1
1   Jane    1992    0
1   Jane    1993    0
3   Jim     1981    1
3   Jim     1982    1
3   Jim     1983    0

Would there be a way to code this in R? I'm having trouble because this has to been done by id, since I don't want to eliminate ALL observations with dummy 0.

A: You can use ave and subset:
subset(dat, as.logical(ave(dummy, id, FUN = any)))

   id name year dummy
1   1 Jane 1990     1
2   1 Jane 1991     1
3   1 Jane 1992     0
4   1 Jane 1993     0
8   3  Jim 1981     1
9   3  Jim 1982     1
10  3  Jim 1983     0

where dat is the name of your data frame.

A: An option using data.table
library(data.table)
setDT(df)[, if(any(dummy)) .SD, by = id]

A: Or you could just subset and use %in%.
df <- df[df$name %in% df$name[df$dummy > 0],]

Where df is your data frame
This relies entirely on primitive calls, and so should be (a) pretty fast and (b) not dependent on any packages.


text:
Q: Heatmap plot by value using ggmap I am attempting to use ggmap to look at education scores by school. I created a coordinate list of all the schools and the individual student scores like so:
     score      lat       lon
3205    45 28.04096 -82.54980
8275    60 27.32163 -80.37673
4645    38 27.45734 -82.52599
8962    98 26.54113 -81.84399
9199    98 27.88948 -82.31770
340     53 26.36528 -81.79639

I first used the pattern from most of the tutorials that I worked through:
http://journal.r-project.org/archive/2013-1/kahle-wickham.pdf
http://www.geo.ut.ee/aasa/LOOM02331/heatmap_in_R.html
library(ggmap)
library(RColorBrewer)

MyMap <- get_map(location = "Orlando, FL",
                 source = "google", maptype = "roadmap", crop = FALSE, zoom = 7)

YlOrBr <- c("#FFFFD4", "#FED98E", "#FE9929", "#D95F0E", "#993404")

ggmap(MyMap) +
stat_density2d(data = s_rit, aes(x = lon, y = lat, fill = ..level.., alpha = ..level..),
               geom = "polygon", size = 0.01, bins = 16) +
scale_fill_gradient(low = "red", high = "green") +
scale_alpha(range = c(0, 0.3), guide = FALSE)

In the first plot, the graphics look great but it doesn't take the score into account.
In order to incorporate the score variable, I used this example Density2d Plot using another variable for the fill (similar to geom_tile)?:
ggmap(MyMap) %+% s_rit +
  aes(x = lon, y = lat, z = score) +
  stat_summary2d(fun = median, binwidth = c(.5, .5), alpha = 0.5) +
  scale_fill_gradientn(name = "Median", colours = YlOrBr, space = "Lab") +
  labs(x = "Longitude", y = "Latitude") +
  coord_map()

It colours by value, but it doesn't have the look of the first. The square boxes are clunky and arbitrary. Adjusting the size of the box does not help. The dispersion of the first heatmap is preferred. Is there a way to blend the look of the first graph with the value-based plot of the second?
Data
s_rit <- structure(list(score = c(45, 60, 38, 98, 98, 53, 90, 42, 96,
45, 89, 18, 66, 2, 45, 98, 6, 83, 63, 86, 63, 81, 70, 8, 78,
15, 7, 86, 15, 63, 55, 13, 83, 76, 78, 70, 64, 88, 61, 78, 4,
7, 1, 70, 88, 58, 70, 58, 11, 45, 28, 42, 45, 73, 85, 86, 25,
17, 53, 95, 49, 80, 70, 35, 94, 61, 39, 76, 28, 1, 18, 93, 73,
67, 56, 38, 45, 66, 18, 76, 91, 76, 52, 60, 2, 38, 73, 95, 1,
76, 6, 25, 76, 81, 35, 49, 85, 55, 66, 90), lat = c(28.040961,
27.321633, 27.457342, 26.541129, 27.889476, 26.365284, 28.555024,
26.541129, 26.272728, 28.279994, 27.889476, 28.279994, 26.6674,
26.272728, 25.776045, 26.541129, 30.247658, 26.365284, 25.450123,
27.889476, 26.541129, 27.264513, 26.718652, 28.044369, 28.251435,
27.264513, 26.272728, 26.272728, 28.040961, 30.312239, 27.889476,
26.541129, 26.6674, 27.321633, 26.365284, 28.279994, 26.718652,
30.23286, 28.040961, 30.193704, 30.312239, 28.044369, 27.457342,
25.450123, 30.23286, 30.312239, 30.193704, 28.279994, 30.247658,
26.541129, 26.365284, 28.279994, 27.321633, 25.776045, 26.272728,
30.23286, 30.312239, 26.718652, 26.541129, 25.450123, 28.251435,
28.185751, 25.450123, 28.040961, 27.321633, 28.279994, 27.321633,
27.321633, 27.321633, 28.279994, 26.718652, 28.362308, 27.264513,
26.365284, 28.279994, 30.23286, 25.450123, 28.362308, 25.450123,
25.776045, 30.193704, 28.251435, 27.457342, 27.321633, 28.185751,
27.457342, 27.889476, 26.541129, 26.541129, 30.23286, 30.312239,
26.718652, 25.450123, 26.139258, 28.040961, 30.23286, 26.718652,
28.185751, 28.044369, 28.555024), lon = c(-82.5498, -80.376729,
-82.525985, -81.843986, -82.317701, -81.796389, -81.276464, -81.843986,
-80.207508, -81.331178, -82.317701, -81.331178, -80.072089, -80.207508,
-80.199437, -81.843986, -81.808664, -81.796389, -80.433557, -82.317701,
-81.843986, -80.432125, -80.091078, -82.394639, -81.490407, -80.432125,
-80.207508, -80.207508, -82.5498, -81.575916, -82.317701, -81.843986,
-80.072089, -80.376729, -81.796389, -81.331178, -80.091078, -81.585975,
-82.5498, -81.579846, -81.575916, -82.394639, -82.525985, -80.433557,
-81.585975, -81.575916, -81.579846, -81.331178, -81.808664, -81.843986,
-81.796389, -81.331178, -80.376729, -80.199437, -80.207508, -81.585975,
-81.575916, -80.091078, -81.843986, -80.433557, -81.490407, -81.289394,
-80.433557, -82.5498, -80.376729, -81.331178, -80.376729, -80.376729,
-80.376729, -81.331178, -80.091078, -81.428494, -80.432125, -81.796389,
-81.331178, -81.585975, -80.433557, -81.428494, -80.433557, -80.199437,
-81.579846, -81.490407, -82.525985, -80.376729, -81.289394, -82.525985,
-82.317701, -81.843986, -81.843986, -81.585975, -81.575916, -80.091078,
-80.433557, -80.238901, -82.5498, -81.585975, -80.091078, -81.289394,
-82.394639, -81.276464)), .Names = c("score", "lat", "lon"), row.names = c(3205L,
8275L, 4645L, 8962L, 9199L, 340L, 5381L, 8998L, 5476L, 4956L,
9256L, 4940L, 6681L, 5586L, 1046L, 9017L, 1878L, 323L, 4175L,
9236L, 8968L, 6885L, 5874L, 9412L, 6434L, 7168L, 5420L, 5680L,
3202L, 1486L, 9255L, 9009L, 6833L, 8271L, 261L, 5024L, 8028L,
1774L, 3329L, 1824L, 1464L, 9468L, 4643L, 4389L, 1506L, 1441L,
1826L, 4968L, 1952L, 8803L, 339L, 4868L, 8266L, 1334L, 5483L,
1727L, 1389L, 7944L, 8943L, 4416L, 6440L, 526L, 4478L, 3117L,
8308L, 4891L, 8290L, 8299L, 8233L, 4848L, 7922L, 5795L, 6971L,
179L, 4990L, 1776L, 4431L, 5718L, 4268L, 1157L, 1854L, 6433L,
4637L, 8194L, 560L, 4694L, 9274L, 8903L, 8877L, 1586L, 1398L,
5865L, 4209L, 6075L, 3307L, 1634L, 8108L, 514L, 9453L, 5210L), class = "data.frame")

A: I'd like to suggest an alternate way of visualizing the distribution of scores (in general) and the median outcomes of each school. It might be better (I don't really know your data or overall problem statement) to show the distribution of scores themselves by various levels (0-10, 10-20, etc) separately then show a view of the actual median rankings per school. Something like this:
library(ggplot2)
library(ggthemes)
library(viridis) # devtools::install_github("sjmgarnier/viridis)
library(ggmap)
library(scales)
library(grid)
library(dplyr)
library(gridExtra)

dat$cut <- cut(dat$score, breaks=seq(0,100,11), labels=sprintf("Score %d-%d",seq(0, 80, 10), seq(10,90,10)))

orlando <- get_map(location="orlando, fl", source="osm", color="bw", crop=FALSE, zoom=7)

gg <- ggmap(orlando)
gg <- gg + stat_density2d(data=dat, aes(x=lon, y=lat, fill=..level.., alpha=..level..),
                          geom="polygon", size=0.01, bins=5)
gg <- gg + scale_fill_viridis()
gg <- gg + scale_alpha(range=c(0.2, 0.4), guide=FALSE)
gg <- gg + coord_map()
gg <- gg + facet_wrap(~cut, ncol=3)
gg <- gg + labs(x=NULL, y=NULL, title="Score Distribution Across All Schools\n")
gg <- gg + theme_map(base_family="Helvetica")
gg <- gg + theme(plot.title=element_text(face="bold", hjust=1))
gg <- gg + theme(panel.margin.x=unit(1, "cm"))
gg <- gg + theme(panel.margin.y=unit(1, "cm"))
gg <- gg + theme(legend.position="right")
gg <- gg + theme(strip.background=element_rect(fill="white", color="white"))
gg <- gg + theme(strip.text=element_text(face="bold", hjust=0))
gg

median_scores <- summarise(group_by(dat, lon, lat), median=median(score))
median_scores$school <- sprintf("School #%d", 1:nrow(median_scores))

gg <- ggplot(median_scores)
gg <- gg + geom_segment(aes(x=reorder(school, median),
                            xend=reorder(school, median),
                            y=0, yend=median), size=0.5)
gg <- gg + geom_point(aes(x=reorder(school, median), y=median))
gg <- gg + geom_text(aes(x=reorder(school, median), y=median, label=median), size=3, hjust=-0.75)
gg <- gg + scale_y_continuous(expand=c(0, 0), limits=c(0, 100))
gg <- gg + labs(x=NULL, y=NULL, title="Median Score Per School")
gg <- gg + coord_flip()
gg <- gg + theme_tufte(base_family="Helvetica")
gg <- gg + theme(axis.ticks.x=element_blank())
gg <- gg + theme(axis.text.x=element_blank())
gg <- gg + theme(plot.title=element_text(face="bold", hjust=1))
gg_med <- gg

# tweak hjust and potentially y as needed
median_scores$hjust <- 0
median_scores[median_scores$school=="School #10",]$hjust <- 1.5
median_scores[median_scores$school=="School #8",]$hjust <- 0
median_scores[median_scores$school=="School #9",]$hjust <- 1.5

gg <- ggmap(orlando)
gg <- gg + geom_text(data=median_scores, aes(x=lon, y=lat, label=gsub("School ", "", school)),
                     hjust=median_scores$hjust, size=3, face="bold", color="darkblue")
gg <- gg + coord_map()
gg <- gg + labs(x=NULL, y=NULL, title=NULL)
gg <- gg + theme_map(base_family="Helvetica")
gg_med_map <- gg

grid.arrange(gg_med_map, gg_med, ncol=2)

Adjust the school labels on the map as needed.
That should help show whatever geographic causality (or lack of) you're trying to show.


text:
Q: WPF / XAML: How do I execute threaded processes and prevent the main UI from being busy / freezing? I have a XAML application that serves as the UI for an automation.  The entire automation can take anywhere from 20-30 hours to fully execute so I created a Task class object that essentially wraps Thread methods (Start/Stop/Reset).
However, when I run the automation method under the Task object, the XAML UI is busy and I cannot interact with the other controls, including the Pause button which toggles the Thread.Set() flag.
There is another post
Prevent UI from freezing without additional threads
where someone recommended the BackgroundWorker class this MSDN article mentions it is a bad idea to use this when if it manipulates objects in the UI, which mine does for purposes of displaying status counts:
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
Any idea around this?
    private void OnButtonStartAutomationClick(object sender, RoutedEventArgs e)
    {
        btnPauseAutomation.IsEnabled = true;
        Automation.Task AutomationThread = new Automation.Task(RunFullAutomation);
    }

    private void RunFullAutomation()
    {
        // do stuff that can take 20+ hours
        // threaded so I can utilize a pause button (block)
    }

class Task
{
    private ManualResetEvent _shutdownFlag = new ManualResetEvent(false);
    private ManualResetEvent _pauseFlag = new ManualResetEvent(true);
    private Thread _thread;
    private readonly Action _action;

    public Task(Action action)
    {
        _action = action;
    }

    public void Start()
    {
        ThreadStart ts = new ThreadStart(DoDelegatedMethod);
        _thread = new Thread(ts);
        _thread.Start();
        _thread.Priority = ThreadPriority.Lowest;
    }

    public void Resume()
    {
        _pauseFlag.Set();
    }

    public void Stop()
    {
        _shutdownFlag.Set();
        _pauseFlag.Set();
        _thread.Join();
    }

    private void DoDelegatedMethod()
    {
        do
        {
            _action();
        }
        while (!_shutdownFlag.WaitOne(0));
    }
}

A:
where someone recommended the BackgroundWorker class this MSDN article mentions it is a bad idea to use this when if it manipulates objects in the UI, which mine does for purposes of displaying status counts

BackgroundWorker is actually ideal for this, as it was designed for this type of scenario.  The warning is that you shouldn't change UI elements inside of DoWork, but rather via ReportProgress and the ProgressChanged event.
The reason the warning exists is "DoWork" is executed on a background thread.  If you set a UI element value from there, you'll get a cross threading exception.  However, ReportProgress/ProgressChanged automatically marshals the call back into the proper SynchronizationContext for you.

A: Take a look at the Dispatcher object in WPF. You can, and should in your scenario, run the long running tasks on a background thread and the BackgroundWorker is a good way to do it. When you need to update the UI you need to verify access to the UI thread and if you don't have it use the dispatcher to invoke an update method on the UI thread.

A: There are two possible causes here: first, that the blocking task is blocking the UI thread rather than running on a background thread, and second, that the background thread is starving the UI thread so that it never gets the chance to respond to input.  You need to find out which of these is the case.  A crude way to do this is, in your Click handler, Debug.WriteLine the current thread ID (Thread.CurrentThread.ManagedThreadId), and do the same in the RunFullAutomation callback.
If these print the same number, then you have the first problem.  Reed and TheZenker have provided solutions to this.
If these print different numbers, then you are already on a worker thread, and you have the second problem.  (BackgroundWorker may get you to the worker thread more elegantly, and will help with updating the UI, but it won't stop starvation.)  In this case the simplest fix is probably to set _thread.Priority = ThreadPriority.BelowNormal; before starting the worker thread.
By the way, your code never appears to actually call AutomationThread.Start, which means the RunFullAutomation callback isn't even executed.  Is this just a typo?

A: I'd advise against rolling out your own Task class given that .NET 4 has full support for running tasks asynchronously in the background using the Task Parallel Library
That said,you can do what Reed suggests and use a BackgroundWorker which is ideal or if you prefer more control over the nature of how the task si executing, you could use the Task class from System.Threading.Tasks and implement something like so:
public partial class MainWindow : Window
{
    CancellationTokenSource source = new CancellationTokenSource();
    SynchronizationContext context = SynchronizationContext.Current;
    Task task;
    public MainWindow()
    {
        InitializeComponent();
    }

    private void DoWork()
    {
        for (int i = 0; i <= 100; i++)
        {
            Thread.Sleep(500); //simulate long running task
            if (source.IsCancellationRequested)
            {
                context.Send((_) => labelPrg.Content = "Cancelled!!!", null);
                break;
            }
            context.Send((_) => labelPrg.Content = prg.Value = prg.Value + 1, null);
        }
    }

    private void Start_Click(object sender, RoutedEventArgs e)
    {
        task = Task.Factory.StartNew(DoWork, source.Token);
    }

    private void Cancel_Click(object sender, RoutedEventArgs e)
    {
        source.Cancel();
    }
}

In DoWork() you use the WPF SynchronizationContext and post messages to update the UI wiget you need.
The example has a progress bar and a label control that is updated on each iteration of the for loop.Cancellation is supported using CancellationTokenSource which is checked in each iteration.
Hope this helps.


text:
Q: Are the values of the subkeys and substitution boxex arrays fixed in the blowfish Are the values of the subkeys and substitution boxex arrays fixed in the blowfish algorithm? If so, how was it determined?
https://github.com/spotify/linux/blob/master/crypto/blowfish.c
ref link bf_pbox, bf_sbox The two fields above use the same value no matter where you look.
i'm curious as to why you use those P, S values as fixed. No reason?


text:
Q: How to plot a gray color density plot This is suppose to be a simple task but I can not get a simple gray scale density plot. I have tried the color function, but can not get to the one that plots in gray scale or just one color
DensityPlot[Sin[Pi*x - Pi], {x, -4, 4}, {y, -3, 3}, ImageSize -> {1500, 500},
  AspectRatio -> Full, ColorFunction -> "BlueGreenYellow", Mesh -> 30]

A: Replace your ColorFunction -> "BlueGreenYellow" with PlotTheme -> "Monochrome"

A: Try
DensityPlot[Sin[Pi*x - Pi], {x, -4, 4}, {y, -3, 3}, ImageSize -> {1500, 500},
 AspectRatio -> Full, ColorFunction -> "GrayTones", Mesh -> 30]

or
DensityPlot[Sin[Pi*x - Pi], {x, -4, 4}, {y, -3, 3}, ImageSize -> {1500, 500},
 AspectRatio -> Full, ColorFunction -> "MonochromeFractalGradient", Mesh -> 30]

or
DensityPlot[Sin[Pi*x - Pi], {x, -4, 4}, {y, -3, 3}, ImageSize -> {1500, 500},
 AspectRatio -> Full, ColorFunction -> (GrayLevel[#] &), Mesh -> 30]

for gray scale, and
DensityPlot[Sin[Pi*x - Pi], {x, -4, 4}, {y, -3, 3}, ImageSize -> {1500, 500},
 AspectRatio -> Full, ColorFunction -> (Lighter[Blue, #] &), Mesh -> 30]

or
DensityPlot[Sin[Pi*x - Pi], {x, -4, 4}, {y, -3, 3}, ImageSize -> {1500, 500},
 AspectRatio -> Full, ColorFunction -> (Opacity[1 - #, Blue] &), Mesh -> 30]

or
DensityPlot[Sin[Pi*x - Pi], {x, -4, 4}, {y, -3, 3}, ImageSize -> {1500, 500},
 AspectRatio -> Full, ColorFunction -> (LCHColor[#, 1, 0.8] &), Mesh -> 30]

for a single color.


text:
Q: Sphinx search with xml pipe I have one json array of Objects.I am creating sphinx compatible xml document from this JSON Array.For each object i create one document and specify id value for it.For example if json array contains 20 objects then i have to create 20 documents starting from 1 to 20.Now my json  array update with time and new Objects come in place so i need to assign them id starting from 21 and so on.So is there any way to maintain this id values from Sphinx side internally?

A: Just store the latest used id somewhere. A text file or something.
Or just get the highest id from the sphinx index. So the script building the xml file, could just first run a sphinxql query
select id from gi_stemmed order by id desc limit 1;


text:
Q: Setup/Start running Selenium tests between two systems I develop code on my main OS (Windows 7) and execute it on my VM (Ubuntu Server 12.04.4). VM is running on VMware Workstation. Selenium server (jar file) I was starting on main OS, but I'm not sure wether I should pass anything in parameters to it, so that it would know where to listen for tests.
I understand, that those should be the following steps

*

*Start Selenium Server on main OS

*Execute test on Ubuntu server

*Make somehow it work

*Enjoy the result

Any help with setting this infrasture would be much appreciated.

A: *

*Start Selenium Grid Hub on main OS:
java -jar selenium-server-standalone-2.38.0.jar -role hub

*Start Selenium node on Ubuntu:
java -jar selenium-server-standalone-2.38.0.jar -role node  -hub http://main-os-address:4444/grid/register

*Specify host in test cases (address of Selenium Hub):
setHost("127.0.0.1")

*Run test case from command line on main OS. It will start testing on Ubuntu VM.

*Enjoy the result


text:
Q: How do I find multiple values, store them, and then manipulate them in VBA? I am currently using VBA in excel on Financial Data.
Essentially what I want to do is find a value in column D "Automotive" and then find the corresponding value in Column G, for all occurrences of "Automotive".
Once I have all of the values (and there are many), I will then find "Automotive" and corresponding value in Column H. All of the values I will find I want to then perform a SUMPRODUCT on them.
So it will look something like this
Automotive       9.121..........................4.6

X

Y

Automotive       4.8............................2.2

Z

B

I will store 9.121,4.8 in an Array (say Auto) and 4.6,2.2 in another.
Then the program will execute a sumproduct on all of the different values
(9.121 x 4.6) +

(4.6 x 2.2) +
...... etc.

A: With questions like this it is usually best to disclose what you are planning to do with the result. The best plan of attack is often determined by where and how the result will be used.
I'm going to assume that a VBA function that will return a double that is the result you are looking for will be sufficient. Here are a few examples.
Function byProductAutomotiveA(rngA As Range, crt As String, rng1 As Range, rng2 As Range)
    Dim frmla As String

    'like =SUMPRODUCT((B2:B10="Automotive")*(D2:D10)*(G2:G10))
    frmla = "=SUMPRODUCT((" & rngA.Address(external:=True) & "=""" & crt & """)*" & _
                        "(" & rng1.Address(external:=True) & ")*" & _
                        "(" & rng2.Address(external:=True) & "))"
                        'D2:D10)*(G2:G10))
    'Debug.Print frmla
    byProductAutomotiveA = Application.Evaluate(frmla)

End Function

Function byProductAutomotiveB(rngA As Range, crt As String, rng1 As Range, rng2 As Range)
    Dim rng As Range, rslt As Double

    For Each rng In rngA
        If LCase(rng.Value2) = "automotive" Then
            rslt = rslt + (rng.Offset(0, rng1.Column - rng.Column).Value2 * rng.Offset(0, rng2.Column - rng.Column).Value2)
        End If
    Next rng

    byProductAutomotiveB = rslt

End Function

Sub byProductAutomotive()
    Dim rw As Long, rslt As Double

    With Worksheets("Automotive")
        For rw = 2 To .Cells(Rows.Count, 4).End(xlUp).Row
            If LCase(.Cells(rw, 4).Value2) = "automotive" Then
                rslt = rslt + (.Cells(rw, 7).Value2 * .Cells(rw, 8).Value2)
            End If
        Next rw
        .Cells(13, 10) = rslt
    End With

End Sub

The following specifically discards hidden rows.
Function byProductAutomotiveBH(rngA As Range, crt As String, rng1 As Range, rng2 As Range)
    Dim rng As Range, rslt As Double

    On Error Resume Next

    For Each rng In rngA
        If LCase(rng.Value2) = LCase(crt) And Not rngA.Parent.Rows(rng.Row).Hidden Then
            rslt = rslt + (rng.Offset(0, rng1.Column - rng.Column).Value2 * rng.Offset(0, rng2.Column - rng.Column).Value2)
        End If
    Next rng

    byProductAutomotiveBH = rslt

End Function

The functions can also be used to retrieve a result back to var in another sub. Be careful to get any Range object correct.

A: You probably already know that this does not have to be done in VBA. Excel can handle the analysis through its functions. However, if you were to write a script to first get the products and then get a grand total, there are several ways to do it. Here's one.
Loop through the ranges, and keep a running sum.
First, assume you have references to the Worksheet. We'll call it Sht here. Also, this example uses a for each loop, but a for loop is probably better (requires you to count the rows in the first column).
Sub AutoProdSum()

    Dim AutoR as Excel.Range
    Dim ColG as Excel.Range
    Dim ColH as Excel.Range

    Set AutoR = Sht.Range("$D:$D")
    Set ColG = Sht.Range("$G:$G")
    Set ColH = Sht.Range("$H:$H")

    Dim ThisAuto as Excel.Range
    Dim Var as Variant
    Dim ThisG as Excel.Range
    Dim valG as Double
    Dim ThisH as Excel.Range
    Dim valH as Double
    Dim prod as Double
      prod = 0
    Dim total as Double
      total = 0

    For Each Var in AutoR
      Set ThisAuto = AutoR.Find("Automotive",SearchBy:=xlValues)
      If ThisAuto.Value = "Automotive" Then
        Set ThisG = ThisAuto.Offset(0,3)
        Set ThisH = ThisAuto.Offset(0,4)
        valG = ThisG.Value
        valH = ThisG.Value
        prod = valG * valH
        total = total + prod

      End If
    Next

    MsgBox "The grand total is " & total
    'Or you can insert the total into the spreadsheet.

End Sub


text:
Q: Render R markdown from a function I need to automate some report generation. I would like to create an rmarkdown report from a function, something like
make_report <- function(file_path = "data_file.txt", outfile){

    # get data from external file
    object <- parse_text(file_path)

    # ?pass it into report template?
    rmarkdown::render("report_template.Rmd", outfile)
}

Where report_template.Rmd prints tables and figures based on the information in the data_frame object. I've seen ways to make rmarkdown templates, but I don't know if there is a way to pass anything into them.

A: You cannot directly pass objects to render function, but you still can save objects into RDS/csv and load them in your rmarkdown file at the beginning in the hidden section, so it will not be printed to your output document.


text:
Q: Condition for this set of points This is for a calculator experimental prob. simulation. So, there is circle in a square and the circle is touching all 4 sides of the square. We need to first choose a coordinate system (two dimensional). So, it make sense it place the coordinate system at the center of the square. Then calibrate the coordinate system with units. So, let us make the radius of the circle equal to 1 unit. The devise a condition to define all the points in the circle. The condition in the example was $\sqrt{x^2+y^2}<=1$ and $x$ was the interval $[-1,1]$ and the $y$ interval was $[-1,1]$. How did they come up with this equation? Lets say we have a square inside a square. Lets say the side of the larger square is 96 and the side of the smaller square is 48. How would you calibrate and where is the origin and what is the conditions that defines that set of points?
Please help, I have a test tomorrow.

A: The point of this was to write a program to find the probability of a coordinate falling in the figure out the sample space. So, in the program we can store the sample space on the $x$-axis as an interval called $x$. And we can do the same and make an interval called $y$ for the $y$-axis. Then we can generate a $1000$ trials where the calculator picks a random number from that $x$ and $y$ interval and pairs them together giving us a coordinate. Like this we generate a $1000$ coordinates. Let's say we can define the figure using it boundaries. We can use   each line that makes the figure and find it as a function. Then if we list all the functions and use an inequality to represent not just the lines but also the space inside the figure. So, the calculator checks if the point it generates satisfies the conditions (list of the functions). If a point satisfies the all the inequality-functions then, it is inside the figure. The calculator does this for all the coordinates. It keeps track of the number of coordinates that fell inside of the figure. Then it gives you that number of how many fell inside the figure. Then the calculator displays the number of points that fell inside and it divides it by $1000$ (number of trials) giving you the probability $\left(\frac{\text{number of pairs that fell in the figure}}{1000}\right)$.
So, in this case the condition that represents all the points in the circle and the circle itself is $x^2+y^2<1$ . Then the calculator generates a bunch of points and tests them out and finds out how many fell into the event space and divides it by the number of trials run (number of points tested) giving you the probability. Remember this probability that is generated is just an estimate hence "experimental probability" and not theoretical probability.


text: Q: What does the "up" mean in "what's up"? I once stopped to think about exactly what I was saying, and, though I'd always known it didn't make sense, I realized I'd never questioned it before. Does it have its origin in a longer question that was cut short? Does it come from being concerned about a place or person that is literally higher than you? Or is it just an arbitrary preposition with no actual meaning and no real reason for being there?


text:
Q: Pass Data To GetVaryByCustomString From A Controller I have a ASP.NET MVC application and i use output cache.

I need to extra information from database at GetVaryByCustomString
  method.

I can't use Session, TempData etc... at GetVaryByCustomString .
How can i pass data to GetVaryByCustomString  from a controller?
//In Controller
Session["IsAdmin"] = LoggedUser.IsAdmin;
Session["IsSalesMan"] = LoggedUser.IsSalesMan;
Session["SomeData"] = SomeObject.SomeData;

//In global.asax
public override string GetVaryByCustomString(HttpContext context, string arg)
{
    var session = context.Session;
    var request = context.Request;

    var sb = new StringBuilder();

    //here throw exception becauase session is null
    sb.Append(session["IsAdmin"]);
    sb.Append(session["IsSalesMan"]);
    sb.Append(session["SomeData"]);

    return sb.ToString();
}


text:
Q: how to add a section to the WooCommerce settings "Shipping" tab The filter hook woocommerce_sections_shipping is not working to add a section tab to woocommerce shipping settings:
 if ( ! class_exists('WC_Shipping_Calculator')){
    class WC_Shipping_Calculator{
        public function __construct(){

            add_filter('woocommerce_get_settings_shipping', array( $this, 'add_settings_tab'), 100);
            //add_filter('woocommerce_settings_tabs_array', array( $this, 'add_settings_tab'), 100);
            //add_filter('woocommerce_sections_shipping_array', array( $this, 'add_settings_tab'), 100);
        }

        public function add_settings_tab($settings_tabs){
            $settings_tabs['shipping_calculator'] = __('Shipping Calculator', 'shipping-calculator');
            return $settings_tabs;

        }
    }
}

$GLOBAL['wc_shipping_calculator'] = new WC_Shipping_Calculator();

What is the filter that I can use to add a section tab to woocommerce shipping settings?

A: To add a custom additional tab to Woocommerce shipping settings, you will use:
if ( ! class_exists('WC_Shipping_Calc')){
    class WC_Shipping_Calc{
        public function __construct(){

            add_filter('woocommerce_get_sections_shipping', array( $this, 'add_shipping_settings_section_tab') );
        }

        public function add_shipping_settings_section_tab( $section ){
            $section['shipping_calc'] = __('Shipping Calculator', 'shipping-calculator');;

            return $section;
        }

    }
    $GLOBAL['wc_shipping_calc'] = new WC_Shipping_Calc();
}

Tested and works.

As there is a shipping calculator already in Woocommerce, to avoid problems, I have changed the class name


text:
Q: Detecting when an embedded Jetty server is fully initialized I have embedded Jetty in a java application and am calling the start() method on an instance of the Jetty server object (after setting a handler list which describes the location of the static and dynamic web content).  Does the start() call block until initialization is complete?  If not, how do I determine when the server is fully started and ready to receive requests?

A: Yes, the server is completely initialized when Server.start() returns. There's no need to do anything else. The documentation isn't clear about this behavior, but I just verified it by looking at the code.

A: We have an embedded Jetty application with dozens of plug-in WARS and servlets to initialize...I've never had a browser request time out while the app was starting, so the server init process IS pretty fast. However, you can check if the Jetty server is still starting up or ready by checking
Server.isStarting()
Server.isStarted()
Server.isRunning()

HTH

A: Here's an example of how I've down this within ANT, launching firefox once the jetty application was ready
<parallel>
    <jetty tempDirectory="${work.dir}">
        <connectors>
            <selectChannelConnector port="${jetty.port}"/>
        </connectors>
        <webApp name="ex1" warfile="ex1.war" contextpath="/ex1"/>
    </jetty>

    <sequential>
        <waitfor maxwait="10" maxwaitunit="second">
            <http url="http://localhost:${jetty.port}/ex1"/>
        </waitfor>

        <exec executable="firefox" spawn="yes">
            <arg line="http://localhost:${jetty.port}/ex1"/>
        </exec>
    </sequential>
</parallel>

A:
Does the start() call block until initialization is complete?

No. It will run the server in the background

If not, how do I determine when the server is fully started and ready to receive requests?

You use org.eclipse.jetty.server.Server#join() method.
// The use of server.join() the will make the current thread join and
// wait until the server is done executing.
// See
// http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join()
server.join();

See [1]  fore more info.
[1] http://www.eclipse.org/jetty/documentation/9.3.x/embedding-jetty.html


text:
Q: How to change download filename in struts At the moment the filename, that I want to download is named "downloadStatistic.html". I want to change it to "whatever-i-want". It's a *.csv File by the way.
Here is the code of my download action:
@Scope("prototype")
@Component("/downloadStatistic")
public class StatisticDownloadAction extends DownloadAction {

@Override
protected StreamInfo getStreamInfo(ActionMapping actionMapping,
                                   ActionForm actionForm,
                                   HttpServletRequest httpServletRequest,
                                   HttpServletResponse httpServletResponse) throws Exception {

    String filepath = httpServletRequest.getParameter("filepath");
    String contentType = "text/comma-separated-values";

    File file = new File(filepath);

    return new FileStreamInfo(contentType, file);
    }
}

And that is my struts xml:
    <action
            path="/shipmentStatistic"
            name="shipmentStatisticForm"
            scope="request"
            validate="false"
            type="de.logentis.struts.DelegatingActionProxy"
            input="/jsp/statistics/ShipmentStatistic.jsp">
        <forward name="back" path="/menu.html" redirect="true"/>
        <forward name="download" path="/downloadStatistic.html?filepath={0}" redirect="true"/>
    </action>

    <action
            path="/downloadStatistic"
            type="de.logentis.struts.DelegatingActionProxy">
        <forward name="back" path="/shipmentStatistic.html" redirect="true"/>
    </action>

Where I can define the filename of the downloaded file?

A: Perhaps you try the following:
public class DownloadFileAction extends Action{

 @Override
 public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
 throws Exception {

  String filepath = httpServletRequest.getParameter("filepath");
  response.setContentType("application/octet-stream");
  response.setHeader("Content-Disposition","attachment;filename=statistic.csv");

  try
  {
    FileInputStream in =
        new FileInputStream(new File(filepath));
    ServletOutputStream out = response.getOutputStream();
    byte[] outputByte = new byte[4096];
    while(in.read(outputByte, 0, 4096) != -1){
     out.write(outputByte, 0, 4096);
   }
   in.close();
   out.flush();
   out.close();

 }catch(Exception e){
   e.printStackTrace();
 }

 return null;
 }
}

Alternatively:
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
                         HttpServletRequest request, HttpServletResponse response)
    throws Exception {

String filepath = request.getParameter("filepath");
File statisticFile = new File(filepath);

byte[] ourArray = new byte[Integer.parseInt(statisticFile.length() + "")];

response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + statisticFile.getName());

FileInputStream in = new FileInputStream(statisticFile);
ServletOutputStream out = response.getOutputStream();

try {
    int c;
    while ((c = in.read()) != -1) {
        out.write(c);
        out.flush();
    }
} finally {
    if (in != null) {
        in.close();
    }
    if (out != null) {
        out.close();
    }
}
return null;
}


text:
Q: MongoDB 2.4.x storing GeoJSON objects with short names? Previously I was storing two type of geospatial data in my database: points and polygons without holes.
So I had something like this
{
    "a" : 12.0,
    "b" : 12.0,
    "c" : [[12.0, 32.0], [12.0, 32.0], [12.0, 32.0], [12.0, 32.0], [12.0, 32.0]]
}

Where (a,b) a = latitude, b = longitude represents a point, and c - is polygon which consists of lat,lng points. I deliberately have this small names to save space (I have pretty big amount of documents in my collection).
Right now I am thinking of switching to GeoJSON, and looking at http://geojson.org/ all I need to do is to change the point with
{
   "type": "Point",
   "coordinates": [100.0, 0.0]
}

and polygon with
{
  "type": "Polygon",
  "coordinates": [
    [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ]
    ]
}

I understand that I can shorten the names type to t, coordinates to c, but is it possible to shorten Point and Polygon to something like 1 and 2.
If so what queries should look like?
In particular I am interested in the following queries:

*

*Find all points inside a specific polygon

*Find all points near a specific point

*Find all polygons that intersect with a specific polygon


text:
Q: Read lines between two specific words in a text document I have data of the form:
Trifle
Beef gyoza with black vinegar dipping sauce
8 Comments

And I want to extract the line between Trifle and 8 Comments. Here it can be any number.

A: Use regmatches
regmatches(x, gregexpr("\\bTrifle\\b.*\\n+\\K.*(?=\\n+.*8 Comments\\b)", x, perl=TRUE))

DEMO
For general cases.
regmatches(x, gregexpr("\\bTrifle\\b.*\\n+\\K.*(?=\\n+.*\\b\\d+\\h+Comments\\b)", x, perl=TRUE))

A: Another option, using trimws and the (?s) regex flag, which includes newlines in the set of characters covered by the dot:
pat <- "(?s)^.*Trifle(.+)8 Comments.*$"
trimws(gsub(pat, '\\1', x, perl=TRUE))
# [1] "Beef gyoza with black vinegar dipping sauce"


text:
Q: Prove that a linear map is continuous if and only if it is continuous at 0. Let L : $\mathbb{R}^2$ →  $\mathbb{R}^2$ be a linear map. Prove that L is continuous on $\mathbb{R}^2$ if and only if L is continuous at (0,0).

A: Implication is obvious. Conversely, suppose $L$ continuous at $0$.
$$|L(a+h)-L(a)|=|L(h)|\underset{h\to 0}{\overset{L\ continuous\ at\ 0}{\longrightarrow} }0$$
what prove the claim.


text:
Q: Keras neural network function approximation I'm trying to approximate following function:

but my best result looks like:

(loss function on the right)
I've tried even with 50k epochs, similar results.
Model:
model = Sequential()
model.add(Dense(40, input_dim=1,kernel_initializer='he_normal', activation='relu'))
model.add(Dense(20, activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(1,input_dim=1, activation=activation_fun))
model.compile(loss='mse', optimizer='adam', metrics=['mse', 'mae', 'mape', 'cosine'])
history = model.fit(x, y, batch_size=32, epochs=5000, verbose=0)

preds = model.predict(x_test)
prettyPlot(x,y,x_test,preds,history,'linear',5000)
model.summary()

prettyPlot function creates plots.
How can I achieve better results without changing the topology of the NN? I don't want it to be big or wide. I want to use even less hidden layers and neurons, if possible.
The function that I want to approximate:
def fun(X):
    return math.sin(1.2*X + 0.5) + math.cos(2.5*X + 0.2) + math.atan(2*X + 1) -  math.cos(2*X + 0.5)

samples:
range = 20
x = np.arange(0, range, 0.01).reshape(-1,1)
y = np.array(list(map(fun, x))).reshape(-1,1)

x_test = (np.random.rand(range*10)*range).reshape(-1,1)
y_test = np.array(list(map(fun, x_test))).reshape(-1,1)

Then y and y_test are normalized using MinMaxScaler.
scalerY= MinMaxScaler((0,1))
scalerY.fit(y)
scalerY.fit(y_test)
y = scalerY.transform(y)
y_test = scalerY.transform(y_test)

Activation function in the last layer is linear.

A: If you still have problems with the accuracy try using a lot of data points like 10k-100k.

A: Has identical task, you shoud use "tanh" activation function on output layer (or use only one layer with it)


text:
Q: Can't vt Switch in Kubuntu 15.04 I'm trying to use the ctrl+alt+n (1-6) to switch to a terminal in Kubuntu 15.04 but it doesn't work. Nothing happens.
When I run ps au | grep tty this is what I see.
root      1141  0.3  0.7 200760 93232 tty7     Ss+  17:48   0:49 /usr/bin/X -core :0 -seat seat0 -auth /var/run/lightdm/root/:0 -nolisten tcp vt7 -novtswitch
root      1170  0.0  0.0  15856  2064 tty1     Ss+  17:48   0:00 /sbin/agetty --noclear tty1 linux
tjaart    5889  0.0  0.0   9492  2184 pts/1    S+   21:17   0:00 grep tty

A: Which display manager are you using? I had a similar problem when I switched to GDM while testing something. Switching back to SDDM resolved the issue. Apparently there's something in GDM's configuration which prevents vt switching.


text:
Q: Using Kubernetes or Apache mesos We have a product which is described in some docker files, which can create the necessary docker containers. Some docker containers will just run some basic apps, while other containers will run clusters (hadoop).
Now is the question which cluster manager I need to use.
Kubernetes or Apache mesos or both?
I read Kubernetes is good for 100% containerized environments, while Apache Mesos is better for environments which are a bit containerized and a bit not-containerized. But Apache Mesos is better for running hadoop in docker (?).
Our environment is composed of only docker containers, but some with an hadoop cluster and some with some apps.
What will be the best?

A: Both functionally do the same, orchestrate Docker containers, but obviously they will do it in different ways and what you can easily achieve with one, it might prove difficult in the other and vice versa.
Mesos has a higher complexity and learning curve in my opinion. Kubernetes is relatively simpler and easier to grasp. You can literally spawn your own Kube master and minions running one command and specifying the provider: Vagrant or AWS,etc. Kubernetes is also able to be integrated into Mesos, so there is also the possibility where you could try both.
For the Hadoop specific use case you mention, Mesos might have an edge, it might integrate better in the Apache ecosystem, Mesos and Spark were created by the same minds.
Final thoughts: start with Kube, progressively exploring how to make it work for your use case. Then, after you have a good grasp on it, do the same with Mesos. You might end up liking pieces of each and you can have them coexist, or find that Kube is enough for what you need.


text:
Q: How to log in automatically in Android to open WiFi that requires web user/password? In first place, I connect to the open Wifi programaticaly
public static boolean conectar(Context ctx, String user, String pass){

    boolean conectado = false;

    String networkSSID = "wifiguay.es";

    WifiConfiguration conf = new WifiConfiguration();
    conf.SSID = "\"" + networkSSID + "\"";

    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

    WifiManager wifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
    wifiManager.addNetwork(conf);

    List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
    for( WifiConfiguration i : list ) {
        if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
             wifiManager.disconnect();
             wifiManager.enableNetwork(i.networkId, true);
             wifiManager.reconnect();
             conectado = true;

             break;
        }
    }

    return conectado;
}

Then, I detect if the open Wifi is "Wifiguay.es" and I open the browser to put the username and password.
public class ConexionEstablecida extends BroadcastReceiver  {

    public void onReceive(Context context, Intent intent) {

        NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
        if(info != null){
            if(info.isConnected()){
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ssid = wifiInfo.getSSID();
                String networkSSID = "wifiguay.es";

                if(ssid.equalsIgnoreCase("\"" + networkSSID + "\"")){
                    Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://wifiguay.lan/login?dst=http%3A%2F%2Fwww.google.es%2F"));
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(i);
                }
            }
        }
    }
}

Now, i don´t know how to do to put the data.

A: You can take a look at this question, you'll have to customize it for your needs, namely changing the field names.
Also, I don't know if this applies to your situation, but storing sensitive passwords is "tricky" at best, maybe consider simply opening the browser and letting the user (or the browser if it's setup to save credentials) take care of entering the password.
Edit:  The example from that question:
mWebView.loadUrl(url);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
    String user="u";
    String pwd="p";
    view.loadUrl("javascript:document.getElementById('nameofyourusernamefield').value = '"+user+"';document.getElementById('nameofyourpasswordfield').value='"+pwd+"';");
}

});


text:
Q: if the order is lack of property of reflexive,can it be total order?
X on {a}* so that eVf iff length(e) smaller than length(f)
i noticed that the order is lack of (Λ,Λ) (a,a),so it is not reflexive and not the total order.but the ans told that is the total order.can someone explain?

A: A total order is a strict order in most definitions, but I'll state definitions that are commonly used:
A partial order is reflexive, symmetric and transitive. We can call it total if $\forall x,y \in X: (x \le y \lor y \le x)$ holds.
Your definition (though somewhat unclearly written) as $x \le y$ iff $\operatorname{len}(x) \le_{\mathbb{N}} \operatorname{len}(y)$ is a linear order on $X=\{a\}^\ast$. If we define $x R y$ iff $\operatorname{len}(x) <_{\mathbb{N}} \operatorname{len}(y)$, we don't have a partial order (so not a total partial order) but a (strict) total order that usually obeys the axioms (denoting it by the symbol $R$ here):

*

*$\forall x: \lnot xRx$

*$\forall x,y: x \neq y \implies x R y \lor y R x$

*$\forall x,y,z: x R y \land yRz \implies xRz$
and it's easy to check that $<$ is defined does obey these.