text:
Q: c# : Dynamically adding new User Settings to Settings.Default.Properties collection, and saving them once form is closed. I'm a novice programmer using Visual C# 2010. I am trying to dynamically (during run time) create a new SettingsProperty and add it to the Settings.Default.Properties collection in my application (new settings). These properties are essentially user defined views (stored in a string) that I want to save for later reloading. I have tried using the code below but it doesn't seem to be working. When I close the application, the newly created and saved properties are gone.
    private void button6_Click(object sender, EventArgs e)
    {
        string connectionText = maskedTextBox3.Text;
        string vusipsText = maskedTextBox2.Text;
        string chartText = maskedTextBox1.Text;

        string[] settingsArray = { connectionText, chartText, vusipsText };
        string saveSettings = String.Join(":", settingsArray);

        //configure new property
        SettingsProperty property = new SettingsProperty("kri");
        property.DefaultValue = saveSettings;
        property.IsReadOnly = false;
        property.PropertyType = typeof(string);

        property.Provider = Settings.Default.Providers["LocalFileSettingsProvider"];
        property.Attributes.Add(typeof(System.Configuration.UserScopedSettingAttribute), new System.Configuration.UserScopedSettingAttribute());

        Settings.Default.Properties.Add(property);

        //Properties.Settings.Default.Reload();

        Settings.Default.Save();
        ActiveForm.Close();
    }

How can I get around this issue?
Thanks

A: Your code looks fine, but the Settings doesn't know about your property next time you load the data.  If you define your property again (at load time) the value should be available.  This is a working sample out of a loop that I use to save enums:
     If My.Settings.Properties(settingName) Is Nothing Then
        Dim p = New Configuration.SettingsProperty(settingName)
        p.Provider = My.Settings.Providers("LocalFileSettingsProvider")
        p.Attributes.Add(GetType(Configuration.UserScopedSettingAttribute), _
                                    New Configuration.UserScopedSettingAttribute())
        p.PropertyType = GetType(SampleEnum)
        My.Settings.Properties.Add(p)
        If My.Settings(settingName) Is Nothing Then
           My.Settings(settingName) = SampleEnum.DefaultValue
        End If
     End If

Always run the code at startup to create the property and for the first time to create the value, too.


text:
Q: What is the shortcut of "enable scrolling" in Acrobat X Pro? I like the button "Fit to window width and enable scrolling" very much, now I know the shortcut of fit to window width is Ctrl+2. So, how about enable scrolling?

A: Edit » Preferences » Accessibility » Always use Page Layout Style. Check Single Page Continuous.
This helped me much more than having to keep switching it.

A:
What is the shortcut of "enable scrolling" in Acrobat X Pro?

Fast and easy way: press Ctrl+shift+H (Twice)
It will enable scrolling.

A: A slightly long way is the chain: AltVPC
I am not aware of any built in shortcut. There is also the toolbar button:

If you get something like Autohotkey, you can set any hotkey you like:
#IfWinActive ahk_class AcrobatSDIWindow
!S::SendInput {Alt}vpc

That's an AHK script to make AltS enable scrolling. !S means it activates on the AltS hotkey. The #IfWinActive means it only activates if Acrobat or Reader (they use the same class) is focused. See more possible hotkeys here.
Just copy that to a text file and change the extension to .ahk. When you install AHK, it should set itself as the default program for that extension so just open the file to run it.
You can set an AHK script to run on startup.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Small business VPN solution I've been looking for a while but I'd like to to implement a vpn solution for anywhere from 1-5 employees at a time (possibly 10 in a year or so)
edit:
Basically I would like outside users to fire up a client or open a web page and be able to access things inside the company network (share drives / printers/ webapps /etc)
I've looked at Astaro Gateway but im not sure if that's the right tool for the job.
I know "best" is a subjective term so i would like to break it into to different suggestions
1) what is the cheapest solution given the criteria above
2) what solution will result in the least amount of headaches from the point of view of maintenance and learning curve.

A: If you have skilled systems/network admins certainly OpenVPN can be the solution you are looking for.
It will require the users to be provided with a certificate and a small client to be run on their clients.
One the certificates are created there is no maintenance needed during the product lifetime.
OpenVPN is free and well known, you could run a hardened, Linux box to host the server.
Don't forget the security aspects of having user connecting externally to your network.

A: For simplicity sake, my vote goes to pfSense: it's a great open source firewall, can run on an older desktop like a champ, and has a great community.  It's my new firewall of choice for small business clients.  For simplicity, you can buy it on ALIX hardware from NetGate, but if you have a spare machine, get another NIC and you're all set.

A: I recommend Astaro without reservation.  It isn't free, but it is inexpensive. It uses the open source package OpenVPN for both IPSec and SSL VPN connectivity. The Astaro management interface is quite clear, and deploying the VPN is straight-forward.  Plus, you get a very good firewall along with the VPN.
Q1 (Cheapest): Rolling your own is inexpensive if your time is considered free. If you are familiar with Linux, OpenVPN server is the "market leader".  Windows can be a VPN server with no additional software on the server or on Windows clients, but I have never used it and would hesitate to because of my unwillingness to expose Windows to the internet.
Also, a similar question has an interesting answer .. flash the router with dd-wrt, an open source firmware that includes OpenVPN. Note that I recommended Astaro there as well!
Q2 (Least Headaches): Astaro is really easy to manage. I have also used Cisco and SonicWall VPNs and found them more difficult for the users and to administer. And, an Astaro appliance will be deployed and running in a tiny fraction of the time it will take to roll your own, or even to flash a router!
I think my opinion is clear!


text:
Q: apple finder webdav client puts file with no content I am creating a webdav server to be able to easily add/(re)move files to our backoffice software.
So I am also implementing the PUT command, and that works OK if I use Windows Explorer to create files.
However when I use the Mac OS X Finder (with the help of Transmit, but that makes no difference) to PUT a file to the server, I get no content.
I configured Fiddler as a reverse proxy, and that shows me the following request:
PUT http://localhost:15001/WebDav/test.txt HTTP/1.1
User-Agent: TransmitFSHelper/1.0.2 neon/0.29.3
Connection: TE
TE: trailers
Host: localhost:49416
Content-Length: 0

It does not send any content.
I have read something about 'trailers', chunked encoding etcetera, but don't know wat to respond to the client to get him to send the contents of the file.

A: When a new file is created (fopen('bla','w')) first an empty file will appear on the disk. This is why you're seeing the initial request with a 0-byte file. After that a program may append to the file, but this will be a separate request.
So treat the 0-byte file as a correct one, and send back 201 Created. You should see a secondary request after that.
however it is true that sometimes clients (such as Finder) will use chunked encoding in the HTTP request. I implemented a webdav server in PHP, and it's simply not working when using FastCGI and Finder, the server must run on apache with mod_php for it to work.
So if the chunked request fails or succeed depends on your stack, I wouldn't know with .NET. But at the very least you should be able to see 2 requests going to the server, rather than one. The chunked encoding issue is separate from that.


text:
Q: Fail to resize htmlwidget? I'm trying to figure out how to write the resize method for my htmlwidget. I read the instructions, but i'm not sure how to implement the force.size([width, height]).resume(); part. I tried a few different things but none is working. This is what I have right now:
HTMLWidgets.widget({

  name: 'IMPosterior',

  type: 'output',

  factory: function(el, width, height) {

    // TODO: define shared variables for this instance

    return {

      renderValue: function(opts) {

        //transition
        var transDuration = 2500;

        var dataDiscrete = opts.bars.map((b, i) => {
            b.y = Number(b.y);
            b.desc = opts.text[i];
            return b;
        });

        var distParams = {
            min: d3.min(opts.data, d => d.x),
            max: d3.max(opts.data, d => d.x)
        };

        distParams.cuts = [-opts.MME, opts.MME, distParams.max];

        opts.data = opts.data.sort((a,b) => a.x - b.x);

        var dataContinuousGroups = [];
        distParams.cuts.forEach((c, i) => {
            let data = opts.data.filter(d => {
                if (i === 0) {
                    return d.x < c;
                } else if (i === distParams.cuts.length - 1) {
                    return d.x > distParams.cuts[i - 1];
                } else {
                    return d.x < c && d.x > distParams.cuts[i - 1];
                }
            });

            data.unshift({x:data[0].x, y:0});
            data.push({x:data[data.length - 1].x, y:0});

            dataContinuousGroups.push({
                color: opts.colors[i],
                data: data
            });
        });

        var margin = {
                top: 50,
                right: 20,
                bottom: 80,
                left: 70
            },
            dims = {
                width: width - margin.left - margin.right,
                height: height - margin.top - margin.bottom
            };

        var xContinuous = d3.scaleLinear()
            .domain([distParams.min - 1, distParams.max + 1])
            .range([0, dims.width]);

        var xDiscrete = d3.scaleBand()
            .domain(dataDiscrete.map(function(d) { return d.x; }))
            .rangeRound([0, dims.width]).padding(0.1);

        var y = d3.scaleLinear()
            .domain([0, 1])
            .range([dims.height, 0]);

        var svg = d3.select(el).html("").append("svg")
            .attr("width", dims.width + margin.left + margin.right)
            .attr("height", dims.height + margin.top + margin.bottom);

        var g = svg
            .append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        var xAxis = d3.axisBottom()
            .scale(xDiscrete);

        var yAxis = d3.axisLeft()
            .scale(y)
            .ticks(10)
            .tickFormat(d3.format(".0%"));

        var yLabel = g.append("text")
            .attr("class", "y-axis-label")
            .attr("transform", "rotate(-90)")
            .attr("y", -52)
            .attr("x", -160)
            .attr("dy", ".71em")
            .style("text-anchor", "end")
            .style("font-size", 14 + "px")
            .text("Probability");

        g.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + dims.height + ")")
            .call(xAxis);

        g.append("g")
            .attr("class", "y axis")
            .call(yAxis);

        var areas = g.selectAll(".area")
            .data(dataDiscrete)
            .enter().append("path")
                .attr("class", "area")
                .style("fill", function(d) { return d.color; })
                .attr("d", function(d, i) {
                    let numPts = dataContinuousGroups[i].data.length - 2;
                    var path = d3.path();
                    path.moveTo(xDiscrete(d.x), y(0));
                    for (j=0; j<numPts; j++) {
                        path.lineTo(xDiscrete(d.x) + j*xDiscrete.bandwidth()/(numPts-1), y(d.y));
                    }
                    path.lineTo(xDiscrete(d.x) + xDiscrete.bandwidth(), y(0));
                    return path.toString();
                });

        var tooltip = d3.tip()
            .attr('class', 'd3-tip chart-data-tip')
            .offset([30, 0])
            .direction('s')
            .html(function(d, i) {
                return "<span>" + dataDiscrete[i].desc + "</span>";
            });

        g.call(tooltip);

        areas
            .on('mouseover', tooltip.show)
            .on('mouseout', tooltip.hide);

        var thresholdLine = g.append("line")
            .attr("stroke", "black")
            .style("stroke-width", "1.5px")
            .style("stroke-dasharray", "5,5")
            .style("opacity", 1)
            .attr("x1", 0)
            .attr("y1", y(opts.threshold))
            .attr("x2", dims.width)
            .attr("y2", y(opts.threshold));

        var updateXAxis = function(type, duration) {
            if (type === "continuous") {
                xAxis.scale(xContinuous);
            } else {
                xAxis.scale(xDiscrete);
            }
            d3.select(".x").transition().duration(duration).call(xAxis);
        };

        var updateYAxis = function(data, duration) {
            var extent = d3.extent(data, function(d) {
                return d.y;
            });
            extent[0] = 0;
            extent[1] = extent[1] + 0.2*(extent[1] - extent[0]);
            y.domain(extent);
            d3.select(".y").transition().duration(duration).call(yAxis);
        };

        var toggle = function(to, duration) {
            if (to === "distribution") {
                updateYAxis(dataContinuousGroups[0].data.concat(dataContinuousGroups[1].data).concat(dataContinuousGroups[2].data), 0);
                updateXAxis("continuous", duration);

                areas
                    .data(dataContinuousGroups)
                    .transition()
                    .duration(duration)
                        .attr("d", function(d) {
                            var gen = d3.line()
                                .x(function(p) {
                                    return xContinuous(p.x);
                                })
                                .y(function(p) {
                                    return y(p.y);
                                });
                            return gen(d.data);
                        });

                thresholdLine
                    .style("opacity", 0);

                g.select(".y.axis")
                    .style("opacity", 0);

                g.select(".y-axis-label")
                    .style("opacity", 0);

            } else {
                y.domain([0, 1]);
                d3.select(".y").transition().duration(duration).call(yAxis);

                updateXAxis("discrete", duration);

                areas
                    .data(dataDiscrete)
                    .transition()
                    .duration(duration)
                        .attr("d", function(d, i) {
                            let numPts = dataContinuousGroups[i].data.length - 2;
                            var path = d3.path();
                            path.moveTo(xDiscrete(d.x), y(0));
                            for (j=0; j<numPts; j++) {
                                path.lineTo(xDiscrete(d.x) + j*xDiscrete.bandwidth()/(numPts-1), y(d.y));
                            }
                            path.lineTo(xDiscrete(d.x) + xDiscrete.bandwidth(), y(0));
                            return path.toString();
                        });

                thresholdLine
                    .transition()
                    .duration(0)
                    .delay(duration)
                        .style("opacity", 1)
                        .attr("y1", y(opts.threshold))
                        .attr("y2", y(opts.threshold));

                g.select(".y.axis")
                    .transition()
                    .duration(0)
                    .delay(duration)
                        .style("opacity", 1);

                g.select(".y-axis-label")
                    .transition()
                    .duration(0)
                    .delay(duration)
                        .style("opacity", 1);
            }
        };

        // Add buttons

        //container for all buttons
        var allButtons = svg.append("g")
          .attr("id", "allButtons");

        //fontawesome button labels
        var labels = ["B", "D"];

        //colors for different button states
        var defaultColor = "#E0E0E0";
        var hoverColor = "#808080";
        var pressedColor = "#000000";

        //groups for each button (which will hold a rect and text)
        var buttonGroups = allButtons.selectAll("g.button")
          .data(labels)
          .enter()
          .append("g")
          .attr("class", "button")
          .style("cursor", "pointer")
          .on("click", function(d, i) {
            updateButtonColors(d3.select(this), d3.select(this.parentNode));
            d3.select("#numberToggle").text(i + 1);
            if (d === "D") {
                toggle("distribution", transDuration);
            } else {
                toggle("discrete", transDuration);
            }

          })
          .on("mouseover", function() {
            if (d3.select(this).select("rect").attr("fill") != pressedColor) {
              d3.select(this)
                .select("rect")
                .attr("fill", hoverColor);
            }
          })
          .on("mouseout", function() {
            if (d3.select(this).select("rect").attr("fill") != pressedColor) {
              d3.select(this)
                .select("rect")
                .attr("fill", defaultColor);
            }
          });

        var bWidth = 40; //button width
        var bHeight = 25; //button height
        var bSpace = 10; //space between buttons
        var x0 = 20; //x offset
        var y0 = 10; //y offset

        //adding a rect to each toggle button group
        //rx and ry give the rect rounded corner
        buttonGroups.append("rect")
          .attr("class", "buttonRect")
          .attr("width", bWidth)
          .attr("height", bHeight)
          .attr("x", function(d, i) {
            return x0 + (bWidth + bSpace) * i;
          })
          .attr("y", y0)
          .attr("rx", 5) //rx and ry give the buttons rounded corners
          .attr("ry", 5)
          .attr("fill", defaultColor);

        //adding text to each toggle button group, centered
        //within the toggle button rect
        buttonGroups.append("text")
          .attr("class", "buttonText")
          .attr("x", function(d, i) {
            return x0 + (bWidth + bSpace) * i + bWidth / 2;
          })
          .attr("y", y0 + bHeight / 2)
          .attr("text-anchor", "middle")
          .attr("dominant-baseline", "central")
          .attr("fill", "white")
          .text(function(d) {
            return d;
          });

        function updateButtonColors(button, parent) {
          parent.selectAll("rect")
            .attr("fill", defaultColor);

          button.select("rect")
            .attr("fill", pressedColor);

        }

        toggle("distribution", 0);

        setTimeout(() => {
            toggle("discrete", transDuration);
        }, 1000);

      },

      resize: function(width, height) {

        // TODO: code to re-render the widget with a new size

        var svg = d3.select(el).append("svg")
            .attr("width", dims.width + margin.left + margin.right)
            .attr("height", dims.height + margin.top + margin.bottom);

      }

    };
  }
});

How can I fix my resize method?


text:
Q: How to cut long labels in Matplotlib I would like to cut long labels, so that only the first 4 letters are displayed, without changing the values in the original data frame.
Example:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sn

np.random.seed(89)

# Toy Dataset
d = pd.DataFrame(np.random.randint(0,3, size=(100, 1)), columns=['var'])
d['var'] = (np.where(d['var'] == 1,'Long loooooong loooooong text',d['var']))

# Plot
f, axes = plt.subplots()
sns.countplot(y='var', data=d, orient='h');

Current output:

Desirable output:

A: This is best solved by supplying the data in short form already.
df2 = d.copy()
df2["var"] = df2["var"].apply(lambda x: x[:4])

# Plot
f, axes = plt.subplots()
sns.countplot(y='var', data=df2, orient='h');

A: I will provide a slightly general solution: Iterate through your y-tick labels and then create a list of new labels, which stores only up to 4 characters if any label has more than 4 characters. Finally, assign this new list of labels as the y-ticks
# Plot
f, axes = plt.subplots()
ax = sns.countplot(y='var', data=d, orient='h');

new_labels = []

for i in ax.yaxis.get_ticklabels():
    label = i.get_text()
    if len(label) > 4:
        new_labels.append(label[0:4])
    else:
        new_labels.append(label)

ax.yaxis.set_ticklabels(new_labels)

Or you can create the new labels in a single line using list comprehension as
new_labels = [i.get_text()[0:4] if len(i.get_text()) > 4 else i.get_text()
              for i in ax.yaxis.get_ticklabels()]

A: try this :
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

np.random.seed(89)

# Toy Dataset
d = pd.DataFrame(np.random.randint(0,3, size=(100, 1)), columns=['var'])
d['var'] = (np.where(d['var'] == 1,'Long loooooong loooooong text'[:4],d['var']))

# Plot
f, axes = plt.subplots()
sns.countplot(y='var', data=d, orient='h');

to get the 4 first letters of a string :
first_four_letters = your_string[:4]


text:
Q: How to increase area of collision / impact effect So for background I am trying to make my first game, its basically a 3d brick-breaker style game. My questions are more design related any help would be greatly appreciated!
I have created a collection of basic cubes that form a larger shape parented these to an empty game object. Then I have a sphere/ball that can collide with the cubes and destroy the cubes it comes in contact with as expected.
Now, what I was hoping to do is under different situations have the ball do more damage ie. destory more cubes. I have tried increasing the size of the ball - this works to some degree but depends on the angle of impact. I have also tried instantiating another sphere at the point of impact to trigger more collisions. This doesnt appear to have must effect.
I am sure there must be an obvious answer to this. How do I increase the "impact" area of the ball/sphere ? Is there a way to have it keep moving in the same direction until it has destroyed a number of cubes?
I have all collider materials set with bounce of 1.

A: Not sure about keeping the ball moving, but I have a solution for destroying multiple bricks at once. Since all spheres have a collider, you could use an OverlapSphere. This checks for all colliders in a sphere of certain radius.
private void DestroyMultiple(Vector3 hitBrickPosition)
{
    int radius = 4; //insert whatever radius you prefer
    Collider[] colliders = Physics.OverlapSphere(hitBrickPosition, radius);
    foreach(Collider col in colliders)
    {
         Destroy(col.gameObject);
    }
}

Alternatively, as @zyonneo said, you could increase the size of the ball's collider radius through collider.radius. However, this would increase the radius from the center of the ball, meaning it would destroy bricks before it even hit them. This could be circumvented by moving the pivot point as you increase the radius, but that's overly complex.


text:
Q: To specify Family id as random effect in GLMM or lme I am trying to fit generalized linear mixed model in R. I have big pedigree and genotype data. I tried this:
m1 <- lmer(Final_sx~(1 | ID)+cohort2+cohort3+cohort4+sex,
           data=solar_new_phen,family=poisson)

And it gave me message:

Number of levels of a grouping factor for the random effects is
  equal to n, the number of observations

I have seen in most of tutorials people are using ID as clustering variable. In kinship package as well in lmekin function it is like this:
rand.eff=formula(paste("~1|",sub.ID))
fit <- try(lmekin(fixed=fix.eff,data=x,random = rand.eff,varlist=list(kmat)))

Should I be using individual id or family id as random effect? I am confused. I have pedigrees and I think I should be using Family ID as clustering variable. It would be great if someone can guide me with little explanation about random effects.

A: Because you have probably only one row by ID ! For this, you need many obs for 1 ID


text:
Q: What are the input image size requirements for CoreML Vision face detection I'm working with Vision framework to detect faces in images. I couldn't find in the Apple's documentation what are the input image requirements. Usually when working with a machine learning model, and particularly with .mlmodel in CoreML, it describes the required input. For example Image (Color 112 x 112).
let image: UIImage = someUIImage()
let handler = VNImageRequestHandler(ciImage: CIImage(cgImage: (image?.cgImage)!))
let faceRequest = VNDetectFaceLandmarksRequest(completionHandler: { (request: VNRequest, error: Error?) in
    guard let observations = request.results as? [VNFaceObservation]
    else {
        print("unexpected result type from VNFaceObservation")
                return
        }
    self.doSomething(with observations: observations)
})

do {
    try handler.perform([faceRequest])
} catch {
    print("Face detection failed: \(error)")
}

A: It doesn't matter, Vision automatically takes care of this. (It may or may not use a machine learning model under the hood.)
You do need to make sure the entire face / head is visible in the image or the face detector won't work very well.
It's also possible it won't work well with really small images but I've never tried this.


text:
Q: Image alignment using HTML TextFlow I'm using a TextArea control with an HTML based textflow and can't seem to work out how to align the images.
HTML:

Some text.

Import to text flow:
myText.textFlow = TextConverter.importToFlow(content, TextConverter.TEXT_FIELD_HTML_FORMAT);

The problem is the text doesn't align around the image, it always sits underneath, i need the top of the image to align with the text. I checked the TextConverter documentation and it says that it doesn't support align in the img tag.
I'm trying to achieve something like this...
But i need the text to be in an .xml file, not hardcoded into the component. I've been looking into it for a while and can't seem to find an answer, it doesn't need to be HTML necessarily, i just need to be able to manage the formatting and text using an external file.
Thanks.

A: I don't know if this is of any use to anyone, but to align the top of the image with the text within a single line you can use the property dominantBaseLine of the textFlow and lineHeight of the specific InlineGraphicElement (or img). Set dominantBaseLine='ideographicCenter' and set lineHeight='[enter desired height here]' in the xml. If you don't set lineHeight it will overlap any lines below. I haven't figured out how to let TextFlow solve this automatically.
If you want to be able to use images of variable height... well, I abused the InlineGraphicElement styleName property as a tag to get these images using TextFlow's getElementsByStyleName() and then setting the InlineGraphicElement's lineHeight within the code. It's not pretty but at least it works.

A: Try these: width='30' height='30' align='left' hspace='10' vspace='10'


text:
Q: Excel chart component recommendations I have to build an analytic dashboard with Excel, and would like to know whether there is any chart library you would recommend.
The charts should be attractive and easy to use by standard users.
I've tried Microcharts, and they look very promising, but I'd like to evaluate more options before reaching a decision.
Thanks a lot.

A: If you are looking for custom charts in Excel, two resources that I turn to first are:

*

*Jon Peltier of Peltier Technical Services

*Chandoo of Pointy Haired Dilbert
For dashboards, specifically I would recommend the six part series by Robert "Creating KPI Dashboards in Microsoft Excel" (Robert also has a blog, Clearly and Simply, that has great content and a list of other sites that you may find useful under the sidebar "Blogs and Links")
For the theory behind dashboards, Stephen Few has a book "Information Dashboard Design: The Effective Visual Communication of Data" that goes into detail on best practices. He also wrote and article about dashboards focusing on good vs. bad designs.
You may also consider taking a look at Tableau if you want the end users/decision makers making their own dashboards.


text:
Q: Intuitive reasoning behind biased maximum likelihood estimators I have a confusion on biased maximum likelihood (ML) estimators. The mathematics of the whole concept is pretty clear to me but I cannot figure out the intuitive reasoning behind it.
Given a certain dataset which has samples from a distribution, which itself is a function of a parameter that we want to estimate, the ML estimator results in the value for the parameter which is most likely to produce the dataset.
I cannot intuitively understand a biased ML estimator in the sense that: how can the most likely value for the parameter predict the real value of the parameter with a bias towards a wrong value?

A: $\beta^{MLE}$ is not the most probable value of $\beta$. The most probable value is $\beta $ itself. $\beta^{MLE}$ maximizes the probability of drawing the sample that we actually got.
MLE is only asymptotically unbiased, and often you can adjust the estimator to behave better in finite samples. For example, the MLE of the variance of a random variable is one example, where multiplying by $\frac{N}{N-1}$ transforms it.

A: Here's my intuition.
Bias is a measure of accuracy, but there's also a notion of precision.

In an ideal world, we'd get the estimate, which is both precise and accurate, i.e. always hits the bull's eye. Unfortunately, in our imperfect world, we have to balance accuracy and precision. Sometimes we may feel that we could give a bit of accuracy to gain more precision: we trade-off all the time. Hence, the fact that an estimator is biased doesn't mean that it's bad: it could be that it's more precise.

A: The ordinary-language and technical meanings of biased are different. The answer by @Glen_b gives a good description of why maximum likelihood estimators can easily be biased in the technical sense.
It is possible for the maximum likelihood estimator to be biased in something like the ordinary-language sense, but it's not usual. Something has to go wrong.
The standard examples of an inconsistent MLE involve paired data.
Suppose $X_{ij}\sim N(\mu_i,\sigma^2)$, for $j=0,1$, and $i=1,2,3,\dots,n$. The MLE of $\mu_i$ is $(X_{i0}+X_{i1})/2$. The MLE of $\hat\sigma^2$ is
$$\hat\sigma^2= \frac{1}{2n}\sum_{i=1}^n\sum_{j=0}^1 (X_{ij}-\hat\mu_i)^2$$
As you get more data, $\hat\sigma^2$ converges not to $\sigma^2$ but to $\sigma^2/2$.
With binary matched-pair data the generating model is $$\mathrm{logit}\,P[Y_{ij}=1]=\alpha_i+\beta X_{ij}$$
The MLE $\hat\beta$ converges to $2\beta$ rather than to $\beta$.
In both cases, the problem is having the number of parameters grow with $n$, and the solution is a conditional likelihood that removes the $n$ intercept parameters before estimating the parameter you're interested in.

A:
the ML estimator results in the value for the parameter which is most likely to occur in the dataset.

Given the assumptions, the ML estimator is the value of the parameter that has the best chance of producing the data set.

I cannot intuitively understand a biased ML estimator in the sense that "How can the most likely value for the parameter predict the real value of the parameter with a bias towards a wrong value?"

Bias is about expectations of sampling distributions. "Most likely to produce the data" isn't about expectations of sampling distributions. Why would they be expected to go together?
What is the basis on which it is surprising they don't necessarily correspond?
I'd suggest you consider some simple cases of MLE and ponder how the difference arises in those particular cases.
As an example, consider observations on a uniform on $(0,\theta)$. The largest observation is (necessarily) no bigger than the parameter, so the parameter can only take values at least as large as the largest observation.
When you consider the likelihood for $\theta$, it is (obviously) larger the closer $\theta$ is to the largest observation. So it's maximized at the largest observation; that's clearly the estimate for $\theta$ that maximizes the chance of obtaining the sample you got:

But on the other hand it must be biased, since the largest observation is obviously (with probability 1) smaller than the true value of $\theta$; any other estimate of $\theta$ not already ruled out by the sample itself must be larger than it, and must (quite plainly in this case) be less likely to produce the sample.
The expectation of the largest observation from a $U(0,\theta)$ is $\frac{n}{n+1}\theta$, so the usual way to unbias it is to take as the estimator of $\theta$: $\hat\theta=\frac{n+1}{n}X_{(n)}$, where $X_{(n)}$ is the largest observation.
This lies to the right of the MLE, and so has lower likelihood.


text:
Q: Serve different Office add-in experiences to different clients, how to check? Because the variety of Office clients that support add-ins is quite large we want to serve some slightly different experiences to the different clients (also to circumvent some irregularities and bugs in some of the clients). There does not seem to be an API function in the office.js library to actually surface the host application? How would we 'detect' what client our add-in is hosted in?

A: At present, the Office ad-in API doesn't provide the API to get the client info. However, the Office will append the _host_Info query string to describe the host.
For example, here is an URL of Excel task pane add-in running on Windows:
https://localhost:44345/App/Home/Home.html?_host_Info=Excel|Win32|16.01|en-US
As a workaround, we can get the client info from this query string.

A: While the add-in API does not provide you an API call to see what the host is there are ways to do feature detection, so the actual question is: why do you want to know the host. You could instead detect whether some of the more 'unusual' features are available, and if they are not fall back to some other method. You can find a VERY elaborate explanation here.
Indeed if you really want to detect the host, you can check the requested URL because it appends to app url with information on the host (client & version).


text:
Q: Proving that cuboid of maximum volume in a sphere is a cube. I was preparing for my maths test . And preparing application of derivative (theory based question ) there I saw a problem of proving rectangle of maximum area in a circle is square . So there were two variables and I was able to find one in terms of other by applying Pythagoras since diagonal of rectangle is diameter of circle.
But soon I thought of a problem that similarly a cuboid of maximum volume in a sphere would be a cube .
But when I went of proving there were three different variables for length ,breadth and height  and i m not able to convert two of them in one variable. So it is becoming a constant problem for me . So please guide how should I move further so that I can change three variables into one .
I hope you guys understood my problem .

A: Make the rectangular prism's length, depth and height a function of x. This is doable because the prism fits into a sphere. Consider a view looking onto one face of the prism with the origin of a coordinate grid at the center of the circumscribing sphere. The length is $2x$, and the height and depth are both $2\sqrt{r^2 - x^2}$, where $r$ is the radius of the sphere.


text:
Q: Using Asterisk as a gateway to Provider I have 2 sip servers on different LANs. Freeswitch and another is Asterisk.
Asterisk  sits on a VPN with a provider and who has provided DIDs. All users register on Freeswitch. How can I route calls to the provider through Asterisk and back,
I tried  sofia/default/DIDNUMBER@ASTERISKSERVERIP:5060 but the call is not going through to the provider.

A: Asterisk ⟷ FreeSWITCH
Your needs of course might be different but this is a good start—I have a couple servers with a private connection and so you may need to adapt authentication measures but this should illustrate the basics of communication back and forth and dropping into correct context, etc.
Asterisk
pjsip.conf
[tel]
type=transport
protocol=udp
bind=10.8.0.2 # set asterisk's IP -- bind to this address

[acl]
type=acl
deny=0.0.0.0/0
permit=10.8.0.3/32 # allow only calls from freeswitch who is on 10.8.0.3 see above deny

[fs]
type=identify
endpoint=fs
match=10.8.0.3 # identify/auth traffic from freeswitch by its IP

[fs]
type=endpoint # set options for endpoint we identified just above
trust_id_inbound=yes
trust_id_outbound=yes
aors=fs
context=from-internal ## WHERE DO CALLS FROM FREESWITCH TO ASTERISK GO?
allow=!all,g722,ulaw
transport=tel

[fs]
type=aor
contact=sip:10.8.0.3 # address-of-record to find freeswitch so can dial to fs without it registering with us (this is fed up to [fs] type=endpoint via its aors above so calls to Dial(PJSIP/1234@fs) dials 1234 on FreeSWITCH 10.8.0.3)

extensions.conf
[from-internal]
include = toFreeSWITCH

[toFreeSWITCH]
exten = _N11!,1,Dial(PJSIP/${EXTEN}@fs)
exten = _0!,1,Dial(PJSIP/${EXTEN}@fs)
exten = _3XX,1,Dial(PJSIP/${EXTEN}@fs)
exten = _1NXXNXXXXXX,1,Dial(PJSIP/${EXTEN}@fs)
exten = _508NXXXXXX,1,Dial(PJSIP/${EXTEN}@fs)
exten = _774NXXXXXX,1,Dial(PJSIP/${EXTEN}@fs)

FreeSWITCH
conf/autoload_configs/acl.conf.xml
add this inside <network-lists>:
<list name="asterisk" default="deny">
  <node type="allow" cidr="10.8.0.2/32"/>
</list>

conf/sip_profiles/asterisk.xml
<profile name="asterisk">
    <gateways>
      <gateway name="asterisk">
        <param name="username" value="freeswitch"/>
        <param name="realm" value="your-asterisk-domain"/>
        <param name="password" value="unused-but-required-field"/>
        <param name="from-domain" value="your-asterisk-domain"/>
        <param name="proxy" value="10.8.0.2"/><!-- ASTERISK ADDRESS -->
        <param name="register" value="false"/><!-- INSTEAD WE SET AOR IN PJSIP.CONF -->
        <param name="cid-type" value="pid"/>
        <param name="rfc-5626" value="true"/>
       </gateway>
    </gateways>
    <settings>
        <param name="apply-inbound-acl" value="asterisk"/>
        <param name="auth-calls" value="false"/>
        <param name="context" value="public"/><!-- WHERE DO CALLS FROM ASTERISK COME INTO? -->
        <param name="rtp-ip" value="10.8.0.3"/><!-- this FreeSWITCH MEDIA IP -->
        <param name="sip-ip" value="10.8.0.3"/><!-- this FreeSWITCH SIP IP -->
    </settings>
</profile>

dialplan.xml
adapt and add inside a dialplan:
<extension name="to-asterisk">
  <condition field="destination_number" expression="^([2-9]11|1?[2-9]\d{2}[2-9]\d{6}|3\d{2})$">
    <action application="set" data="dialed_extension=$1"/>
    <action application="export" data="dialed_extension=$1"/>
    <action application="set" data="call_timeout=30"/>
    <action application="set" data="hangup_after_bridge=true"/>
    <action application="set" data="continue_on_fail=true"/>
    <action application="export" data="rtp_secure_media=false"/>
    <action application="bridge" data="sofia/gateway/asterisk/${destination_number}"/>
  </condition>
</extension>


text:
Q: MySQL GROUP BY without crossovers from another column I have a table my_table, with fields group_id, region, value. I want to select the chains of values from each group, but only if region = US for all records in the group.
The query I initially tried is
SELECT
GROUP_CONCAT(
             value
             ORDER BY DATE DESC SEPARATOR '<-'
) AS value_chain
FROM my_table
WHERE region = 'US'
GROUP BY (group_id)

This is incorrect, as if there is a US record and a CA record in the same chain, the CA record will be omitted before the GROUP BY, and the US record will be returned as a group of size 1. In this case I don't want to return the chain at all.
Is there a good way of achieving this?
For performance reasons I would rather not build all chains from all regions and then filter if at all possible.

A: Try this:
SELECT GROUP_CONCAT(value ORDER BY DATE DESC SEPARATOR '<-') AS value_chain
FROM my_table
GROUP BY group_id
HAVING SUM(region <> 'US') = 0

This will filter out groups having at least one non-'US' value.
Visual
-- drop table if exists my_table;
create table my_table
(   group_id int not null,
    region varchar(20) not null,
    value int not null,
    date date not null
);
-- truncate table my_table;
insert my_table values
(1,'US',100,'2016-01-07'),
(1,'CAD',200,'2016-01-06'),
(2,'US',700,'2016-02-07'),
(3,'CAD',666666,'2016-01-07'),
(4,'US',1200,'2016-02-04'),
(4,'US',1400,'2016-02-03');

SELECT GROUP_CONCAT(value ORDER BY DATE DESC SEPARATOR '<-') AS value_chain
FROM my_table
GROUP BY group_id
HAVING SUM(region <> 'US') = 0
+-------------+
| value_chain |
+-------------+
| 700         |
| 1200<-1400  |
+-------------+


text:
Q: show comments of a post below the post in single.php wordpress I have single.php file and Im showing single post in it. I want to show comments on related to this post under this post. But the problem is Im getting comments all of comments below any post.
Below is my single.php code
    <?php
/*
* The template for displaying all single posts and attachments
*/
?>
<?php get_header(); ?>

    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<?php the_title(); ?>

<?php the_time('F jS, Y') ?> by <?php the_author() ?>

<?php the_content(); ?>

Posted in <?php the_category(', ') ?> | <?php comments_popup_link('No Comments »', '1 Comment »', '% Comments »'); ?>

    <?php endwhile; endif; ?>
        <?php  foreach (get_comments() as $comment): ?>

<?php echo $comment->comment_author; ?> said: "<?php echo $comment->comment_content; ?>".

        <?php endforeach; ?>
    <?php comments_template(); ?>

<?php get_footer(); ?>

Below is my comments.php code
<?php $comment_args = array(
        'comment_notes_after' => '',
        'title_reply' => 'Have something to say?'
    ) ?>

Thanks in advance.

A: use is_single() to check the post :
<?php if( is_single() ) : ?>

<?php  foreach (get_comments() as $comment): ?>

<?php echo $comment->comment_author; ?> said: "<?php echo $comment->comment_content; ?>".

    <?php endforeach; ?>
<?php comments_template(); ?>

<?php endif; // close to check single.php ?>

A: Remove the foreach from single.php:
<?php get_header(); ?>

    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<?php the_title(); ?>

<?php the_time('F jS, Y') ?> by <?php the_author() ?>

<?php the_content(); ?>

Posted in <?php the_category(', ') ?> | <?php comments_popup_link('No Comments »', '1 Comment »', '% Comments »'); ?>

    <?php comments_template(); ?>
    <?php endwhile; endif; ?>

<?php get_footer(); ?>

Then, add it to your comments.php and pass $comment_args in get_comments() like so:
<?php $comment_args = array(
        'comment_notes_after' => '',
        'title_reply' => 'Have something to say?'
      )
?>
<?php foreach (get_comments($comment_args) as $comment): ?>

        <?php echo $comment->comment_author; ?> said: "<?php echo $comment->comment_content; ?>".

<?php endforeach; ?>

have a look the the function reference for get_comments to see the list of arguments you can pass into get_comments

A: Single.php code. Remove get_comments()
<?php
/*
* The template for displaying all single posts and attachments
*/
?>
<?php get_header(); ?>

    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<?php the_title(); ?>

<?php the_time('F jS, Y') ?> by <?php the_author() ?>

<?php the_content(); ?>

Posted in <?php the_category(', ') ?> | <?php comments_popup_link('No Comments »', '1 Comment »', '% Comments »'); ?>

    <?php endwhile; endif; ?>
        <?php  foreach ($comments as $comment): ?>

<?php echo $comment->comment_author; ?> said: "<?php echo $comment->comment_content; ?>".

        <?php endforeach; ?>
    <?php comments_template(); ?>

<?php get_footer(); ?>

You need to get_the_ID() per single page comment, then add the comment query.
$id - get_the_ID();
<?php $comment_args = array(
        'comment_notes_after' => '',
        'title_reply' => 'Have something to say?',
        'post__in' => $id, //Retrieves comments for an array of posts
        'post_id' => $post_ID // Post's ID you can make sure only comments related to that post appear.
      )
?>
// The comment query
   $comments_query = new WP_Comment_Query;
   $comments = $comments_query->query( $args );


text:
Q: python flask running in one port connected to UI running in node server different port The website is running using node server. I want to create a python flask rest api to connect to pop up chat window of this website.My python flask is running in 8085 port and node server is running in 8082 port.
in python flask app.py

@app.route('/')
  def hello_world():
      return render_template('popupchat.html')
@app.route('/chat',methods=["POST"]) def chat():

this popupchat.html is pointing to website pupupchat window. and there is one bind.js script having  $.post("/chat" , if i want to connect this pop up chat window running in node server to python flask server , how i will connect .
i appreciate your suggestions

A: If you are just debugging try to adjust the port on the side of the chat window. You can tell the chat window to reach a certain port by altering the url you are trying to reach. Example:
http://your_ip:your_port/your_route or in your case http://your_ip:8085/your_route
If you are already deployed please talk to your admin since this might be depending on your server.


text:
Q: Creating data-attributes on table rows with jqGrid I'm trying to read up on the jQuery plugin jqGrid but I'm running short when skimming through the documentation and demos.
What I want to accomplish is to use some parts of my JSON data to display in columns, and other parts to create HTML5 data-attributes on each table row. However, I'm unable to figure out if jqGrid can handle this, and if so, how.
An example of what I want to do:
From the following data (whitespace added for readability)
[
 {
     'id': 1,
     'type': 0,
     'name': 'first',
     'address': '1524, 3rd street',
     'X': 18.0068922,
     'Y': 59.31076795
 },
 {
     'id': 7819,
     'type': 0,
     'name': 'not first',
     'address': 'South Corner',
     'X': 144.18457031,
     'Y': -22.20774917
 }
]

I want to create the following table:

        Name
        Address

            first
            1524, 3rd street

            not first
            South Corner

As you can see, the data attributes may or may not be named the same thing as the properties in the row. Also, not shown in this example, some properties will be used both for showing in the table and for data-attributes.
The API that provides the JSON data is used elsewhere, so I can't change that. The requirements on the data attributes are also defined by another (self-authored) jQuery plugin used elsewhere, so they cannot be changed either.
Is there any way to accomplish this with jqGrid? If so, how? If not, what options do I have?

A: You can use the afterInsertRow event to get hold of each row inserted into the grid and then modify them as you wish(Add custom attributes using jQuery.attr()).


text:
Q: Sublime text: how to disable dual edit? When copying a piece of text then quicking clicking somewhere else and start writing, I find myself writing both in the place I clicked and in place of the selected text simultaneously.
How to disable this feature?

A: This is because you still press the ctrl key when clicking.
To disable the feature of multi edit open your menu » preferences » key bindings - user and add the following content.
{
    "button": "button1", "count": 1, "modifiers": ["ctrl"],
    "press_command": "drag_select",
}


text:
Q: MixItUp with two select / dropdown fields I'm not advanced enough in JS to get this working fully.
I have two select fields with options:
    <select name="" id="filter-position">
      <option value="all">Filter by position</option>
      <option value=".instructor">Instructor</option>
      <option value=".leader">Leader</option>
      <option value=".blah">Blah</option>
      <option value=".whatever">Whatever</option>
    </select>

    <select name="" id="filter-location">
      <option value="all">Filter by position</option>
      <option value=".portland">Portland</option>
      <option value=".missoula">Missoula</option>
      <option value=".chicago">Chicago</option>
      <option value=".newyork">New York</option>
    </select>

The container where the filtered items live looks a little like this:

...

...

...

...

...

...

I can get each one to filter properly but not together (i.e., AND). The JS code I'm using goes like this:
  $(function(){
    var $positionSelect = $('#filter-position'),
        $locationSelect = $('#filter-location'),
        $container = $('#filter-container');

    $container.mixItUp({});

    $positionSelect.on('change', function(){
      $container.mixItUp('filter', this.value);
    });

    $locationSelect.on('change', function(){
      $container.mixItUp('filter', this.value);
    });
  });

If I filter by one select, things filter properly. If I then filter by the other, it overrides the first filter. What I want is for them to both be used.
I know there's a way to get this to work, but I'm not sure how to get that concatenated string to do the "and" logic as documented in the Advanced Filtering section of the docs using <select>. Help?

A: You're really close! Because of how the mixItUp API works, filters aren't additive (e.g. when you call mixItUp.filter, it doesn't add a new filter to what's already active). So, you just need to construct a new filter string from the values of both dropdowns whenever one of them changes. You can accomplish that like so:
$(function(){
    var $positionSelect = $('#filter-position'),
        $locationSelect = $('#filter-location'),
        $container = $('#filter-container');

    $container.mixItUp({});

    $('#filter-position, #filter-location').on('change', function() {

      var filterString = $positionSelect.val() + $locationSelect.val();

      $container.mixItUp('filter', filterString);
    });

  });

I opted to use the jQuery .val() over the native .value in this case since you're already using jQuery, and val() will probably be more reliable in this case. Let me know if you run into trouble.
You may also want to to change this:
<option value="all">Filter by position</option>

To this:
<option value="">Filter by position</option>

for both of your dropdown menus, otherwise you might get some weird behavior.

A: Use comma like..
$('#filter-location, #filter-container')
.on('change', function(){
...
;)

A: Something like this...
$(function(){
    $container = $('#filter-container');

    $container.mixItUp({});

    $container.on('change','#filter-position, #filter-location', function(){
        $container.mixItUp('filter', this.value);
    });
});


text:
Q: Is there a workaround to trigger an option.click event in IE? I am using a dropdown to allow the user to sort search results. These results in a table but not all of the sortable criteria are represented by columns. The columns can be sorted by either clicking on the column header or using a 'Sort By' dropdown. The user can reverse the sort by clicking on the sorted columns header. I am trying to duplicate this functionality in the drop down but can't get it to work in IE7/IE8.
The following is the existing code that works in both IE and Firefox. It changes the sorted column but not the sort direction.
$("#sortSelect").change(function() {
    //change sort
});

This is what I am trying to change it to and it works in Firefox. It changes the sorted column and if the sorted columns is already selected it will change the sort direction.
$("#sortSelect option").click(function() {
    //change sort
});

I was hoping someone would know of a way to trigger the option.click event or know of a good workaround.

A: To reiterate what T.J. Crowder said in the comments, this is an awkward change that you're making to a user interface.  That being said, it's possible to distinguish between clicking on the select element and clicking on an option element if the select doesn't have the multiple attribute set.  Try out the following code in Internet Explorer:
$(document).ready(function ()
{
  $("#sortSelect").click(function (event) {
    if (event.offsetY > this.offsetHeight)
      $(this.options[this.selectedIndex]).click();
  });
  $("#sortSelect option").click(function (event)
  {
    alert('clicked option '+this.parentNode.selectedIndex);
  });
});

It works because when you click on an option element, the click event fires on the select element.  By detecting that you've clicked outside the bounds of the select element checking event.offsetY > this.offsetHeight, you can use jQuery to trigger the click event of the currently selected option element.


text:
Q: Dllmain in DLL library in VC++ I am going through my project code base, which consits of libraries and
applications. Some libraries are Dll's. Code is written in C++ for Windows
using MS VS 2010.
I taught for Dll we should write  DllMain function which is entry point for
the DLL application. But in my project for DLL "DllMain" function is not present.
My question when we require DllMain and when it is not required?
Thanks for your time and help.

A: DllMain is not mandatory. If you have some initialization code required to run when loading the dll, you should create a DllMain function, and treat the initialization there. Otherwise it's not required.
See here some more information.


text:
Q: i does not let me inser the matrice that i want #include <stdio.h>
#include <stdlib.h>

int main()
{
    int i,j;
    int a[2][2];
    //inserting the numbers
    printf("entrer  la matrice\n");
    for (i = 0; i < 2; ++i)
    {
        for (j = 0; j < 2; ++j)
        {
                printf("entrer la ligne %d colonne %d\n",i,j );
                scanf("%d",a[i][j]);
        }
    }
    for (i = 0; i < 2; ++i)
    {
        for (j = 0; j < 2; ++j)
        {
            // printing the numbers that i just put
            printf("%d",a[i][j] );
        }
        printf("\n");
    }

    return 0;
}


text:
Q: ERROR: While executing gem ... (Zlib::GzipFile::Error) not in gzip format I am developing a Sencha touch 2 application. I have been following the "Styling the user interface of a Sencha Touch application" tutorial on theming of secha touch applications.
It requires me to install Ruby, Compass and SASS.
I installed Ruby using the installer from rubyinstaller.org.
On executing the following command, I get the expected result which confirms correct installation:
C:\>ruby -v

ruby 1.9.3p327 (2012-11-10) [i386-mingw32]

Current source is up to date:
C:\>gem sources

** CURRENT SOURCES **

http://rubygems.org/

Next, since I am behind a proxy, I used the following command to install HAML/Compass:
C:\>gem install -p [proxy:port] compass

ERROR:  While executing gem ... (Zlib::GzipFile::Error)
not in gzip format**

Can someone help me? I found solutions such as system update, gem sources update, but everything is up to date on my system.

Edit:
C:\>gem install compass

works perfectly fine on my private system. When I try the same command from my workplace I need to use the proxy as mentioned above and that results in an error.

A: I assume the ERROR occurs since the web sense at my workplace blocks these downloads.
Solution: I downloaded the required gems: chunky_png, fssm, compass, sass, haml etc.. directly from http://rubygems.org/gems and placed these gems in my local directory.
After this I tried gem install compass. This first searches your local directory. On finding the required gems,  installation takes place. Does not require connection to the ruby website.
Note: Run the command from the path where the gems are located
eg: I have placed the gems in C:\Ruby193\lib\ruby\gems\1.9.1\gems
So I run the following command :
C:\Ruby193\lib\ruby\gems\1.9.1\gems>gem install compass

A: I had a similar problem, it worked on my own private laptop, but failed while using a virtual server at work (running Ubuntu 12.10) that used a proxy.
Following the suggestion I found here, from the command line I defined:
export HTTPS_PROXY=proxy-address:proxy-port-number

export HTTP_PROXY=proxy-address:proxy-port-number

and then my gem install package worked fine.


text:
Q: The super group $GL(1|1)$ It is difficult to find information on super groups and I have built my knowledge from various sources. I have the following questions.
$GL(1|1)$ is defined as the group of invertible linear transformations on $\mathbb{C}^{1|1}$.
I see conflicting information on whether the group action should preserve the grading. Is this true? I do not think so, as this would make the matrix diagonal for $GL(1|1)$
Now I can write as a usual $2\times 2$ matrix. What are its entries? Some sources use complex numbers, others use Grassmann variables. Which are supposed to be used?
Regarding invertability, is it true that an arbitrary linear operator on $\mathbb{C}^{1|1}$ is invertible if and only if the $(1,1)$ and $(2,2)$ components of the corresponding matrix are invertible?
For example, is it possible to have a matrix of the following type in $GL(1|1)$:
$$ \left(\begin{array}{cc}
a & b \\
c & 0
\end{array}\right)$$

A: $GL_{\mathbb{C}}{(1|1)}$ is a $\mathbb{C}$-functor which associates to each super $\mathbb{C}$-algebra $R$
the group of $Aut^{sup}_{R}(\mathbb{C}^{1|1}\otimes_\mathbb{C}R)$ of all super $R$-linear automorphisms on $\mathbb{C}^{1|1}\otimes_\mathbb{C}R$.
$GL_{\mathbb{C}}{(1|1)}(\mathbb{C}) = \Bigl\{\left(\begin{array}{ll}a&0\\0&d\end{array}\right)\Big|a,d \in \mathbb{C}^{\times}\Bigr\}$
$GL_{\mathbb{C}}{(1|1)}(\mathbb{C}^{1|1}) =  \Bigl\{\left(\begin{array}{ll}a&b\\c&d\end{array}\right)\Big|a,d \in (\mathbb{C}^{1|1}_{ev})^{\times}\space b,c \in \mathbb{C}^{1|1}_{odd}\Bigr\}$

A: I see conflicting information on whether the group action should preserve the grading. Is this true? I do not think so, as this would make the matrix diagonal for (1|1)
The group acting should always preserve the grading.
The issue that you are having is that you are considering only the $\mathbb{C}$-points of  $\operatorname{GL}(1|1)$ i.e you have only been looking at $\operatorname{GL}(1|1)(\mathbb{C})$ which is, as you have noticed, diagonal.
Since $\operatorname{GL}(1,1)$ is a superscheme (here a Lie supergroup) you need to describe it using the functor of points as described in the answer above.
This will get rid of your problem of wrongly thinking that $\operatorname{GL}(1,1)$ is diagonal.
is it true that an arbitrary linear operator on ℂ1|1 is invertible if and only if the (1,1) and (2,2) components of the corresponding matrix are invertible?
Yes!


text:
Q: redhat + how to find the oracle JRE version 1.7 from redhat site I am searching the JRE 1.7.x version from red-hat site by yum command
bot not find anything
 yum list | grep java | grep "1.7" | grep -i jre

no such patch
or maybe redhat not hold JRE 1,7 patches?

A: You need to enable an extra Red Hat Network channel first -- see their guide at https://access.redhat.com/solutions/732883


text:
Q: Apache http client get encoding I do some simple get request via the latest apache httpclient.
When I do this get request via browser - encoding is OK.
But problem occurs when i'm trying to use httpclient:
        HttpGet get = new HttpGet(fullUrl);
        get.setHeader("Accept-Encoding","UTF-8");
        get.setHeader("Accept-Charset","UTF-8");
        get.setHeader("Content-Encoding","UTF-8");
        get.setHeader("Content-Type", "application/json;charset=UTF-8");

        HttpResponse response = client.execute(get);
...
        EntityUtils.toString(response.getEntity(), "UTF-8");

and some Umlauts are not exists.
BTW, returns null:
     response.getEntity().getContentEncoding();

Edit:
The server returns these headers:
Cache-Control →no-store, no-cache, must-revalidate
Content-Encoding →gzip
Content-Length →3402
Content-Type →application/json; charset=UTF-8
Date →Tue, 29 Nov 2016 10:49:30 GMT
Expires →Mon, 26 Jul 1997 05:00:00 GMT
Pragma →no-cache
Server →Jetty(9.2.15.v20160210)
X-Content-Type-Options →nosni

Edit:
Response:
In Java code:
 "items": [
    {
      "title": "KjøretÃ",
    },
....

In Chrome:
 "items": [
    {
      "title": "Kjøretøy,
    },
....


text:
Q: I'm getting an error when I run this gui in tkinter Python 3.9 count = 0

def click():
    global count
    count+=1
    print(count)

from tkinter import *
window = Tk()

photo = PhotoImage(file='icon.ico')

button = Button(window,
                text="Click me!",
                command=click,
                font=("Comic Sans",30),
                fg="#00ff00",
                bg="black",
                activeforeground="#00ff30",
                activebackground="#0a0a0a",
                state=ACTIVE,
                image=photo,
                compound='bottom')  # ACTIVE, DISABLED
button.pack()
window.mainloop()

error:     self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "icon.ico"


text:
Q: Fast Data structure for finding strict subsets (from a given list) I have a large set of sets e.g. {{2,4,5} , {4,5}, ...}.
Given one of these subsets, I would like to iterate through all other subsets which are strict subsets of this subset.  That is, if I am interested in set A, e.g. {2,4,5}, I want to find all sets B where the relative complement  B / A = {}, the empty set.  Some possibilities could be {2,4}, {2,5} but not {2,3}
I could of course search linearly and check each time, but am looking for an efficient data structure both for the larger set and the subset (if it matters).  The number of subsets is typically in the 10s of thousands, but if it makes a difference I would be interested in cases where it could be in the hundreds of millions.  The size of the subsets is typically in 10s.
I am programming in C++
Thanks

A: Mathematically, you should construct the Hasse diagram for your sets, which will be the partially ordered set with vertices your sets and arrows given by containment. Essentially, you want to create a directed, acyclic graph with an arrow A --> B if A strictly contains B and there is no C such that A strictly contains C  and C strictly contains B.
This is actually going to be a ranked poset, meaning that you can keep track of "levels" of the digraph based on the cardinality of the sets. This is sort of like creating a hash table to jump to the right set.
From A, just do a BFS down the graph to find all proper subsets of A.
How to implement this: (in pseudocode)
for (C in sets) {
    for (B in HasseDiagram at rank rank(C)+1) {
      if (C contains B)
        addArrow(C,B)
    }
    for (A in HasseDiagram at rank rank(C)+1) {
      if (C contains A)
        addArrow(A,C)
    }
    addToDiagram(C)
}

To make this and all the subroutines fast, you can encode each set an a binary where digit i is 1 if i is in C and 0 otherwise. This makes testing containment and determining rank trivial.
The above method works if you have all possible subsets. Since you may be missing some, you'll have to check more things. For the pseudocode, you'll need to change rank(C)-1 to the largest integer l < rank(C) such that some element of the HasseDiagram has rank l, and similarly for rank(C)+1. Then, when you're adding the set C to the diagram:

*

*If A covers C, then you only need to check lower ranked sets B that are also covered by A.

*If C covers B, then you only need to check higher ranked sets A that also cover by B.
By "X covers Y" I mean there is an arrow X -> Y, not just a path.
Furthermore, when you insert C between A and B using one of the above checks, you will need to remove the arrow A --> B when you add A --> C and C --> B.

A: I would suggest storing all of the sets in a tree.  Each node of the tree would represent all sets that contained a specified initial list of integers.  I would have the nodes contain the following pieces of information:

*

*The number of additional elements in the smallest set at this point or below in the tree.  (0 means that this node is in the tree.)

*A bitset representing the intersection of all subsets below this one in the tree.

*A pointer to an array mapping larger integers to subtrees that contain that as the next element.  As a special case, if there is only one subset below this one in the tree, this pointer could be null.  (There is no need to fill out unpopulated parts of the tree.)

Given this tree, and a subset you can do a search with recursion and backtracking for all subsets of the set.  In your search you start with the first element of the subset, look for all subsets that contain that element, then you search for all subsets that don't contain that element.
Building this tree takes time and space at most O(n * m * k) where n is the number of subsets m is the average number of elements per subset, and k is the size of the universe of elements that can be in the sets.  With random sets of sets that are much smaller than the possible universe of subsets of your k elements you won't construct most of the tree, and it will take O(n * m) for your tree.
In theory traversing this tree could be time O(n).  But in practice you'll trim branches of the tree fairly early, and won't traverse most of the other subsets.  A back of the envelope calculation suggests that if you have n random sets out of a k element universe with n << 2k then a search of the tree is O(n0.5k).  (At each integer, half the time it is in your set you're searching for subsets of and you split your search into 2, and half the time it isn't in your set and you eliminate half of your space.  After j integers you've got 2j/2 searches going of sets of sets of size 2-jn.  Thus by the time you get the searches down to single other subsets to compare with, there are O(n0.5) searches going.  The final comparison of bitmaps is O(k).)
Note: I'm convinced by this back of the envelope calculation that the average performance is o(n0.5+epsilon) for every epsilon > 0, but the convergence is very slow.  More precisely I suspect that the arithmetic average of the performance is n0.5 + O(sqrt(log(n)))).  But that sqrt(log(n)) piece takes a long time to converge.
Note that using the number of additional elements in the smallest set at this point or below in the tree lets your search trivially filter out all sets that are too large to be subsets.  Depending on your dataset, this may or may not lead to useful speedups.

A: The approach suggested by PengOne would work, but it is not very efficient.  To see why it fails, consider the following pathological example:
Suppose you have a universe U, which has n distinct elements, and let the set of all the sets you are searching over consist of all subsets of U with exactly k elements.  Then it is true that no pair of sets here are strictly contained in one another; and so in the worst case you would have to search over all n choose k possible sets!  In other words, using his proposed data structure is no better than a naive linear search in the worst case.
Clearly you can do much better than this, and the correct data structure to use would be a trie:  http://en.wikipedia.org/wiki/Trie
To adapt a trie to work for sets instead of just strings, it is sufficient to fix an ordering on the elements of the universal set, then encode each of your subsets as a binary string of finite length, where the ith character is 0 or 1 depending on whether the set contains the ith element.  Here is an implementation in python
import math

class SetTree:
    def __init__(self, index, key, left, right):
        self.index = index
        self.key = key
        self.left = left
        self.right = right

cached_trees = { }
cached_index = 2

def get_index(T):
    if isinstance(T, SetTree):
        return T.index
    if T:
        return 1
    return 0

def make_set_tree(key, left, right):
    global cached_trees, cached_index
    code = (key, get_index(left), get_index(right))
    if not code in cached_trees:
        cached_trees[code] = SetTree(cached_index, key, left, right)
        cached_index += 1
    return cached_trees[code]

def compute_freqs(X):
    freqs, total = {}, 0
    for S in X:
        for a in S:
            if a in freqs:
                freqs[a] += 1
            else:
                freqs[a] = 1
            total += 1
    U = [ (-f, a) for a,f in freqs.items() ]
    U.sort()
    return U

#Constructs the tree recursively
def build_tree_rec(X, U):
    if len(X) == 0:
        return False
    if len(U) == 0:
        return True

    key = U[0][1]

    left_elems = [ S for S in X if key in S]

    if len(left_elems) > 0:
        return make_set_tree(key,
            build_tree_rec(left_elems, U[1:]),
            build_tree_rec([ S for S in X if not key in S ], U[1:]))

    return build_tree_rec(X, U[1:])

#Build a search tree recursively
def build_tree(X):
    U = compute_freqs(X)
    return build_tree_rec(X, U)

#Query a set tree to find all subsets contained in a given set
def query_tree(T, S):
    if not isinstance(T, SetTree):
        return [ [] ] if T else []
    if T.key in S:
        return [ U + [ T.key ] for U in query_tree(T.left, S) ] + query_tree(T.right, S)
    return query_tree(T.right, S)

#Debugging function: Converts a tree to a tuple for printing
def tree_to_tuple(T):
    if isinstance(T, SetTree):
        return (T.key, tree_to_tuple(T.left), tree_to_tuple(T.right))
    return T

Now here is an example usage:
In [15]: search_tree = set_search.build_tree(set_family)

In [16]: set_search.tree_to_tuple(search_tree)
Out[16]:
(2,
 (4, (5, True, True), (5, True, (3, True, False))),
 (4, (5, True, False), (1, True, False)))

In [17]: set_search.query_tree(search_tree, set([2,3,4,5]))
Out[17]: [[5, 4, 2], [4, 2], [5, 2], [3, 2], [5, 4]]

In [18]: set_search.query_tree(search_tree, set([1,2,3,4,5]))
Out[18]: [[5, 4, 2], [4, 2], [5, 2], [3, 2], [5, 4], [1]]

In [19]: set_search.query_tree(search_tree, set([2,4,5]))
Out[19]: [[5, 4, 2], [4, 2], [5, 2], [5, 4]]

In [20]: set_search.query_tree(search_tree, set([2,5]))
Out[20]: [[5, 2]]

In [21]: set_search.query_tree(search_tree, set([1]))
Out[21]: [[1]]

In [22]: set_search.query_tree(search_tree, set([15]))
Out[22]: []

Note that the amount of work performed by query_tree is proportional to the size of the subtree which represents the set of all results returned by query_tree.  Thus our goal is to compute the size of one of the subtries (on average) and then as a secondary goal to minimize this quantity.  One way to do this is to reorder the elements of the universal in terms of descending frequency, so that they are repeated as few times as possible in the lower levels of the tree.  This optimization is also done in the above code.  A secondary optimization is to cache the trees which have already been searched to avoid having to redo unnecessary work.
EDIT:  Just after I got done typing this up, I saw btilly's answer, which is comes to more or less the same conclusion about the problem (modulo some technical nitpicks which I have moved into the comments on his post.)
EDIT 2:  Realized that this is really just a special case of a binary decision diagram.  Don't really have enough energy to fix the write up right now, so will leave it as is.  Perhaps fix it tomorrow.  http://en.wikipedia.org/wiki/Binary_decision_diagram

A: This is interesting. I like the Hasse diagram approach PengOne suggests but I think you can build the Hasse diagram really quickly using a prime number trick. Lets say the union of all of the sets results in natural numbers 1 to N. Map each of these numbers with corresponding primes, like:
PrimeMap [1] = 2;
PrimeMap [2] = 3;
PrimeMap [3] = 5;

Next, caluclate a 'score' for each set by multiplying each of the prime numbers corresponding to the number in the set. For instance a set {1,2,3} would have a score 2*3*5 = 30. Now, for a set A to be a proper subset of another set B score(A) must divide score(B) (scores for {1,2}, {2,3} and {1,3} are 6, 15 and 10, each of which divide 30). Use this score to build your Hasse diagram.
Edit: This seems like one of the nice theoretical solutions. Probably not the way to go. Bitsets as suggested by yi_H is just as good and does not suffer from big integer troubles.

A: Have a look at this python library that implements Hasse diagrams python-lattice]1


text:
Q: Custom responsive 'featured image' sizes My home page has a carousel of 'featured (thumbnail) images' from posts. The carousel uses about two=thirds of the screen width and Google Page Speed Analyser complains that my images are too large.
What I would like to insert into my bootstrap carousel code would be something like:

I'm not completely sure about the sizes element.
I'm trying to address that by declaring custom image sizes
/* Image Sizes
    Large : 525 x 270
    iPhone6 210 * 180   and then 2x that?
*/
add_image_size( "card", 400, 400, false );
add_image_size( "front_page_sm", 420, 360, true );
add_image_size( "front_page_lg", 520, 270, true );

My first problem is that however often I run regenerate thumbnails I do not get these sizes (although I do see images of size 400, which I use elsewhere).

The image regeneration suddenly started working! The following code creates the img tag
function getFeaturedImage($resto) {
    global $table_prefix;
    global $wpdb;
    $query = "...";
    $queryResult = $wpdb->get_results($query);
    $post_id = $queryResult[0]->post_id;
    return get_the_post_thumbnail($post_id, 'front_page_lg');
}

This does get the $post_id correctly, but results in

This is a real problem as it is using the original (large) version of the image.
However, and in some cases I get
<img width="270" height="270"
src="//localhost:3000/wp-content/uploads/2008/03/Oysters-at-A-fusion.jpg"
class="attachment-front_page_lg size-front_page_lg wp-post-image" alt="Oysters at A-fusion"
srcset="//localhost:3000/wp-content/uploads/2008/03/Oysters-at-A-fusion.jpg 768w, //localhost:3000/wp-content/uploads/2008/03/Oysters-at-A-fusion-150x150.jpg 150w, //localhost:3000/wp-content/uploads/2008/03/Oysters-at-A-fusion-500x500.jpg 500w, //localhost:3000/wp-content/uploads/2008/03/Oysters-at-A-fusion-400x400.jpg 400w"
sizes="(max-width: 270px) 100vw, 270px" />

Clearly this srcset is going to be valuable to me and - as far as I know - is being generated by wordpress rather than a plugin. But it only happens for a few posts and with unuseful sizes.
How can I get a src set with my two custom sizes?

A: First off, I'm not really sure why you need to involve the wpdb class just to create the img tag. If you want to get the featured image, you can use the Wordpress functions get_the_post_thumbnail()  and the_post_thumbnail()which both allow you to specify the registered size you want, and return the markup like so:
// In the loop:
the_post_thumbnail( 'front_page_lg' ); // echos the markup

// Outside the loop:
$img_markup = get_the_post_thumbnail( $post->ID, 'front_page_lg' );

From there, you have two different hooks to customize that markup:

*

*wp_calculate_image_srcset filter

*wp_calculate_image_sizes filter

Here's an example of using wp_calculate_image_srcset:
function wpse_custom_image_srcset( $sources, $size_array, $image_src, $image_meta, $attachment_id ){
    $w = 768; // setup a custom width here, repeat below for as many custom widths as you want, linking to your URL
    $sources[$w] = array(
        'url'  => 'myfolder/myimage.jpg',
        'descriptor' => 'w',
        'value'      => $w,
    );
    return $sources;
}
add_filter( 'wp_calculate_image_srcset', 'wpse_custom_image_srcset', 10, 5 );

and here's an example of using wp_calculate_image_sizes:
function wpse_post_thumbnail_sizes_attr( $attr, $attachment, $size ) {
    //Calculate Image Sizes by type and breakpoint
    if ($size === 'front_page_lg') {
        $attr['sizes'] = '(max-width: 768px) 92vw, (max-width: 992px) 450px, (max-width: 1200px) 597px, 730px';
    }
    return $attr;
}
add_filter( 'wp_get_attachment_image_attributes', 'wpse_post_thumbnail_sizes_attr', 10 , 3 );

This should give you a headstart, but obviously you'll have to tweak these until you're getting the markup you're looking for with your custom image sizes and breakpoints. Here's some more resources which should help:

*

*https://make.wordpress.org/core/2015/11/10/responsive-images-in-wordpress-4-4/

*https://viastudio.com/optimizing-your-theme-for-wordpress-4-4s-responsive-images/


text:
Q: Chrome vs Firefox vs IE - Scrolling Issue I am developing a site and it seems to behave differently when in Chrome. Scrolling is not consistent or smooth. It keeps on stopping. However, when I load the same site in Firefox or IE9, I have no problems. Everything scrolls smoothly.
++++++++EDIT++++++++
I was able to fix my problem by adding the following meta tag to my template:
<meta http-equiv="X-UA-Compatible" content="IE=edge" />

I am not sure why, but it seems to fix it... as well as other problems I was having

A: This is a known problem in Chrome and the solution is not logically clear to me.Something to do with how chrome is rendering the javascript. However, on adding a parent container div to the scrolling content it seems to work fine. There is a solution to this problem in javascript in the following link with an example
Stackoverflow solution
For the link you have added to your web page it is more to do with IE than chrome. Do you have chrome frame installed in IE ?
I do not know the technology you are using but the below code will give a hint to the solution.In Gwt (Google web toolkit) I worked out the solution as follows:
My earlier code which was causing the issue was as follows
Old Code:
        <g:FocusPanel addStyleNames="{style.scrollable} {style.fullHeight}" ui:field="bodyContainer">
        <b:CellTable width="100%" ui:field="bodyTable"/>
        </g:FocusPanel>

New Code:
      CSS :
     #scrollContainer {
       overflow:auto;
       position:absolute;
       top:0px; height:100%; width:100%;
     }

 HTML:
    <div id="scrollContainer">
    <g:FocusPanel ui:field="bodyContainer">
        <b:CellTable width="100%" ui:field="bodyTable"/>
    </g:FocusPanel>
    </div>

Hope this helps!


text:
Q: How to Delete an Object from state in react? I have this object that I want to delete according to id.
the classic delete object doesn't seem to be working I am copying the state calling the delete but it is giving me an error is it my syntax or should the delete be handled differently ?
// State Object Model
Items : {
id1 : [some items ],
id2 : [some items ],
id3 : [some items ],
id4 : [some items ],
id4 : [some items ],
}
// Reducer Delete Logic
 case DELETE_OBJ:
return {
  Items: {
    ...state.Items,
    delete Items[id1]
    }
  };

A: Shallow copy first, then delete. You necessarily need to shallow copy all state, and nested state, that you are updating. In this case you shallow copy the root state and then also the nested Items state object.
// Reducer Delete Logic
case DELETE_OBJ:
  const newState = {
    ...state,
    Items: {
      ...state.Items,
    },
  }
  delete newState.Items[id1];
  return newState;
};


text:
Q: Mysqli returns affected row = -1 even on successful updates I am working on database CRUD functions using mysqli api.
While working on update operation with the command below:
$mysqliObject->query('UPDATE table_name SET some_fields WHERE some_conditions')

Now even if the rows are being updated successfully in my database, $mysqliObject->affected_rows gives value -1
Even if some rows(suppose 4 rows) are updated, $mysqliObject->affected_rows still gives -1

Update

Also $mysqliObject->info gives this:
Rows matched: 1  Changed: 1  Warnings: 0

Update 2

I am using PhpStorm as my IDE and I've enabled debug mode on.


text:
Q: Angular UI-Router Not Recognizing State When Optional Parameters Provided I'm using angular ui router to handle state transitions, and I have a state that I can't seem to properly resolve.
The state is:
.state('organization.program.editor', {
    url: "/editor/{contentId:[0-9]{1,8}}/{workflowStateId:[0,9]{1,8}}/{projectId:[0,9]{1,8}}",
    templateUrl: "editor-editor",
    controller: 'EditorController as vm',
    resolve: {
        editorModel: ['$stateParams', 'editorService', 'orgService',
            function ($stateParams, editorService, orgService) {
                debugger;
                //edited for brevity
                return null;

            }]
    },
    params: { contentId: {}, orgId: {}, programId: {},
              workflowStateId: { value: '-1' }, projectId: { value: '-1' } }
        })

If I navigate to /editor/2445, the transition is accepted and it successfully navigates, and my optional parameters are their defaults, -1 and -1.
However, if I try /editor/2445/1, or /editor/2445/1/1, it does not recognize the state.
What am I missing?

A: Ok, so I solved this.  The problem is the params definition:
params: { contentId: {}, orgId: {}, programId: {},
          workflowStateId: { value: '-1' }, projectId: { value: '-1' } }

Since I'm using numeric constraints in the url like so: editor/{contentId:[0-9]{1,8}}/{workflowStateId:[0,9]{1,8}}/{projectId:[0,9]{1,8}}, there are two violations in my param defaults.
First, [0-9]{1,8} will only match numeric values.  Second, it will only match positive numeric values.
So, the '-1' value provided will never match when applied.  It needs to be a number, and 0 or greater.
Hope it helps someone in the future.


text:
Q: Total RAM in Java I have a piece of code that caclulates the total RAM in my system [not Java VM Heap Size].
It is as follows:
        OperatingSystemMXBean operatingSystemMXBean =
            ManagementFactory.getOperatingSystemMXBean();

        Method m = operatingSystemMXBean.getClass().
                    getDeclaredMethod("getTotalPhysicalMemorySize");

        m.setAccessible(true);

        Object value = m.invoke(operatingSystemMXBean);

        if (value != null)
        {
            System.out.println(value);
        }

The problem with the above piece of code is that it gives me incorrect values sometimes. For example in a system with 8 GB of RAM, using a 32 bit JVM, it shows 4 GB. I guess it is because the JVM is 32 bit and using 32 bits 4 GB is the maximum that it can address.
Can anyone suggest ways/workarounds for this. Basically how do we get the total RAM in a system using a 32 bit JVM.
Full details of my System are as follows:
OS : Windows 7
CPU : Intel i7
JDK : Sun Java 1.6 Update 21, 32 bit
RAM : 8 GB

A: Cannot think of a pure Java way, but you can use Runtime.exec() to run the following command
wmic MEMPHYSICAL Get MaxCapacity

EDIT:
Correction - the above gives the maximum capacity for installing RAM. Try the OS alias like below:
wmic OS Get TotalVisibleMemorySize


text:
Q: discord.py command can only work for user with one of several role in a list I am currently building a discord bot using Discord py with one of its command can only be used by a user with one of several roles that I have set up.
Currently, I store all of the role name in a list since I also have a command to add new role to that list. This is a snippet of what I have right now
role_name = ["Moderator"]

@bot.command(name='role',help='adding role for staff moderating role (admin only command)')
@commands.has_permissions(administrator=True)
async def add_role(ctx, role):
    if role not in role_name:
        role_name.append(role)

    print(*role_name) #use case 1: when run this command to add 'mine' it print "Moderator mine"

@bot.command(name='add',help='Add channel, when you run this command, you must be in the channel ')
@commands.has_any_role(role_name)
async def add_channel(ctx):
    if ctx.channel.id not in channel_id:
        channel_id.append(ctx.channel.id)

I have double check on my account's role on discord and it already have Moderator role

However, when I run the command to test - this is what i got
discord.ext.commands.errors.MissingAnyRole: You are missing at least one of the required roles: '['Moderator']'
Is there any way to do what I want?
/Edit: Add the adding role to the role_name for the sake of clarity. I also have tried ",".join(role_name) in has_any_role() however, I still get this issue discord.ext.commands.errors.MissingAnyRole: You are missing at least one of the required roles: ''

A: has_any_role() accepts *items and is looking for str or int objects. The list is read as a string '["Moderator"]'. You can check this by trying to rename your rolename as well.
A simple fix for this would be:
@commands.has_any_role(*role_name) for your bot from read the list as a string.
So it looks like this:
role_name = ["Moderator"]

@bot.command(name='add',help='Add channel, when you run this command, you must be in the channel ')
@commands.has_any_role(*role_name)
async def add_channel(ctx):
    if ctx.channel.id not in channel_id:
        channel_id.append(ctx.channel.id)

A: After some extra research regarding the decorator. Apparently, based on this answer https://stackoverflow.com/a/64544809/10467473 -

A decorator is invoked once as soon as the module is imported, and
then the function that gets called is whatever was provided by the
decorator definition.

Therefore, I tried a different approach to check the role like how I wanted it to be and now it works perfectly fine! This is the method that I use.
role_name=[]

@bot.command(name='role',help='adding role for staff moderating role (admin only command)')
@commands.has_permissions(administrator=True)
async def add_role(ctx, role):
    if role not in role_name:
        role_name.append(role)

@bot.command(name='add',help='Add channel, when you run this command, you must be in the channel ')
async def add_channel(ctx):
    global role_name
    user_role = ctx.author.roles
    for rl in user_role:
        if (rl.name in role_name):
           if ctx.channel.id not in channel_id:
              channel_id.append(ctx.channel.id)
              break


text:
Q: Facebook login doesn't work with hello.js I've created a sample react app using create-react-app npm module. And then I have added hello.js to the application to be able to write a quick app using this api. I've correctly configured my app id and such at facebook developer site (I've tested this with another sample app without using hello.js and it works fine).
When I click on the Login button, it get redirected to FB login page, I enter the correct credentials and it gets redirected to localhost, but without a success response. For some reason this doesn't work. And I can't figure out what's going wrong.
Here's the code if anyone has ideas on what I'm doing wrong:
import React, { Component } from 'react';
import * as hello from 'hellojs';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      askForLogin: true
    };

    hello.init({
      facebook: "XXXXXXXXXXXXXXXX" //correct api is provided here
    });

    hello.api("me").then(function(r){
      console.log("Successful login: ", r);
      this.setState({askForLogin: false});
    }, function(e) {
      console.log("Not successful yet");
      this.setState({askForLogin: true});
    });
  }

  login() {
    const options = { display: "page" };
    const cb = () => { console.log("Login callback");}
    hello.login("facebook", options, cb);
  }

  render() {
    return (

Welcome to React

          To get started, edit src/App.js and save to reload.

        {
          this.state.askForLogin ?

            <button onClick={this.login}>Login to Facebook</button>

 :

        }

    );
  }
}

export default App;

A: I was able to solve it by explicitly telling hello.js to use 'facebook' and it worked immediately. Posting the answer so that if anyone else faces the problem, it might help them:
import React, { Component } from 'react';
import * as hello from 'hellojs';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      askForLogin: true
    };

    hello.init({
      facebook: "XXXXXXXXXXXXXXX"
    });

    const facebook = hello.use("facebook"); //This is the new line

    facebook.api("me").then(function(r){
      console.log("Successful login: ", r);
      this.setState({askForLogin: false});
    }.bind(this), function(e) {
      console.log("Not successful yet");
      this.setState({askForLogin: true});
    }.bind(this));
  }

  login() {
    const options = { display: "page"};
    const cb = () => { console.log("Login callback");}
    hello.login("facebook", options, cb);
  }

  render() {

    return (

Welcome to React

          To get started, edit src/App.js and save to reload.

        {
          this.state.askForLogin ?

            <button onClick={this.login}>Login to Facebook</button>

 :

        }

    );
  }
}

export default App;


text:
Q: How to append HTML elements in Javascript? I am trying to append two HTML elements and pass it to the after() function in jquery:
$('div.masterButtons').after(function () {
    var foobar = $('
foo
bar

');
    var foobaz = $('
foo
baz

');
    return (foobar + foobaz)
    }
);

It prints:
[object Object][object Object]

How do I append the two elements? I am avoiding concatenating two html strings because the divs are far more complicated than these and I would need jquery elements to build it.

A: both foobar and foobaz are jQuery object, you can't use + to add them

$('div.masterButtons').after(function () {
    var foobar = $('
foo
bar

');
    var foobaz = $('
foo
baz

');
    return foobar.add(foobaz)
});

A: If you really like having the function there, use the answer provided by https://stackoverflow.com/users/114251/arun-p-johny . Alternatively, you could just simplify to:
$('div.masterButtons')
    .after('
foo
bar

')
    .after('
foo
baz

');

A: You can also used .insertAfter
$('div.masterButtons').insertAfter('
foo
bar

')

A: Based on the jQuery .after() documentation you have many ways to do that.
$('div.masterButtons')
.after('
foo
bar

','
foo
baz

');

or
$('div.masterButtons')
.after('
foo
bar

')
.after('
foo
baz

');

or
var barAndBaz = ['
foo
bar

','
foo
baz

'];
$('div.masterButtons').after(barAndBaz);


text:
Q: Qt can't compile I am new with QT and c++. So I do this tutorial Tutorial
I copied everything, but qt can't compile this.
    //imageviewer.cpp
#include "imageviewer.h"
#include "ui_imageviewer.h"

ImageViewer::ImageViewer(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ImageViewer)
{
    ui->setupUi(this);

    QImage image("C:/TEST/GoldenGate.png");
    ui->imageLabel->setPixmap(QPixmap::fromImage(image));
}

ImageViewer::~ImageViewer()
{
    delete ui;
}

//imageviewer.h
#ifndef IMAGEVIEWER_H
#define IMAGEVIEWER_H

#include <QMainWindow>
#include <QLabel>
#include <QScrollArea>

namespace Ui {
class ImageViewer;
}

class ImageViewer : public QMainWindow
{
    Q_OBJECT

public:
    explicit ImageViewer(QWidget *parent = 0);
    ~ImageViewer();

private:
    QLabel *imageLabel;
    QScrollArea *scrollArea;
    Ui::ImageViewer *ui;

};

#endif // IMAGEVIEWER_H

And got this:
'class Ui::ImageViewer' has no member named 'imageLabel'
I can't understand why it doesnt't see this variable.

A: Your Ui::ImageViewer is not complete .. it does not have 'imageLabel' added. Open the form in design mode and add QLabel, name it 'imageLabel' and try again.
Otherwise, follow tutorial to the end, it adds the QLabel 'imageLabel' dynamically in imageview.cpp.
// imageview.cpp

#include "imageviewer.h"
#include "ui_imageviewer.h"

ImageViewer::ImageViewer(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ImageViewer)
{
    ui->setupUi(this);

    imageLabel = new QLabel;
    imageLabel->setBackgroundRole(QPalette::Base);
    imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
    imageLabel->setScaledContents(true);

    scrollArea = new QScrollArea;
    scrollArea->setBackgroundRole(QPalette::Dark);
    scrollArea->setWidget(imageLabel);
    setCentralWidget(scrollArea);

    setWindowTitle(tr("Image Viewer"));
    resize(500, 400);
}


text:
Q: How do I get manifest file to generate in Visual Studio 2013 I have two projects that were written by others, one is a WPF application and the other a Console application. The WPF application is generating a .exe.manifest file alongside the executable, somehow automatically generated using the project settings (it is not explicitly declared as app.manifest). But the Console application is not generating one. How would I set it up to generate one?

A: For C/C++ in Visual Studio 2013 I've found 2 ways:
The modern way:  Merge in additional XML

*

*Go to (properties) > Linker > Manifest and change Generate Manifest to YES.  You can also set UAC / admin rights here without needing to create your own manifest XML.

*Add a new XML file to the project, and include other manifest entries that you need inside of an assembly wrapper tag, for example:
<?xml version="1.0" encoding="utf-8"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!--The ID below indicates application support for Windows 8.1 -->
<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
<!-- 10.0 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
</application>
</compatibility>
</assembly>

*Go to (properties) > Manifest Tool > Input and Output and add the XML file from step 2 using the Additional Manifest Files setting
The Manual way:  Use a custom RC file
If you add a second RC file that is manually edited to your project you can include a manifest XML file.

*

*Add the RC file to your project

*(project) > Linker turn manifest generation OFF since you don't want Visual Studio to create its own manifest at link time.

*In the RC file, add these lines
#define MANIFEST_RESOURCE_ID 1
MANIFEST_RESOURCE_ID RT_MANIFEST "res\\my-manifest-xml.manifest"

For this you need to make sure your XML file includes all tags needed for the manifest.
Testing the results
SigCheck from Systenternals has an -m option that will show you the manifest.
SigCheck - SysInternals - TechNet


text:
Q: Sphinx filtering with dropdown lists I have just finished implementing a full-text search engine powered by sphinx using PHP and MySQL. However I would like to add filtering using drop down lists.
I would be more grateful if someone could assist me on that.

A: Sounds like a job for attributes
http://sphinxsearch.com/docs/current.html#attributes
but really not a lot more can be said, without more detail. Ask a specific question get a specific answer. Ask a general question get a general answer.


text:
Q: How to allow edit access to for certain record types only I need all user to be able to see all opportunities. However, Department A should only be able to edit opportunities assigned to 3 record types (x,y,z) and Department B should only be able to edit opportunities assigned to the other 4 record types (t,u,v,w).
I started testing with Department A in the sandbox and this is what I have done so far:

*

*Profile Permissions for Department A Role = Opportunities (Read,
Create, Edit, Delete,View All)

*Org-Wide Defaults for Opportunities:
Public Read Only

*Sharing Rule for Opportunities: when Opportunity
record type = x,y,z share with Department A as "Read/Write"

As a result, when a user assigned to the Department A role goes to an opportunity with an "x" record type then they are able to see the edit button (YAY!). However, when they go to an opportunity with the "t" record they are also able to see the edit button and they shouldn't. They should have read only access to "t" opportunities. What am I missing here to make the Department A role "read only" for certain record types? Should I be opproaching this in a different way?

A: Edit is a CRUD permission on the Object, in this case Opportunity, defined on profile/permission set level. So as long as a User on say Profile A has Edit rights on Opportunity, they will always be able to view the Edit button all across, if the button is available on the page layouts.
Your options here are:

*

*Change the OWD to Private.
As long as Users from Department A do not own the records for record type t,u,v,w, and that such records are shared to them as Read Only, they won't be able to edit any record, even though if Edit button is available on the page layout

*Without Changing the OWD.
Create a different page layout for record types t,u,v,w, specifically for Users on Profile A. Remove the Edit button from the page layout. Mark all the fields on the page layout as Read Only to mimic a read only page. Assign it to the Users from Department A. This is based on the assumption here is that the Users from Department A are on different profile than Users from Department B.

A: If you users have same profile then you cant use page-layouts-profile trick to hide edit button then you have to restrict update using Validation Rule.
AND ($UserRole.Name =='Department A' ,
    CASE(RecordType.Name ,'T',true,'U',true,'V',true,'W',true,false) ,
    ISBLANK(Id)
    )

Src: https://help.salesforce.com/articleView?id=000005286&type=1


text:
Q: Strange Chrome Extension behavior I'm building a simple chrome extension, which at the moment just renders a popup.html page.  However, sometimes when I click my extension, it isn't rendered fully - a small section will appear, however the rest of the background will be transparent.  Example:
Here is the extension, with Bootstrap, working normally:

However, sometimes when it is loaded, the popup works but this is shown:

As you can see, the box appears, there is a small section in the top left corner and the rest of the box is transparent.  The only way to get rid of this is to relaunch the extension.
The only CSS I have is the standard Bootstrap css, and my custom:
body {
    width: 500px;
    height: 200px;
    overflow-x: hidden;
    font-size: 10px;
}

Anyone have any ideas?